import React, { useState } from 'react';
import { modelsMap } from '../generated/models.index';
import type { PageContext } from './DevShell';

const TYPE_SHORT: Record<string, string> = {
  String: 'String',
  Int: 'Int',
  BigInt: 'BigInt',
  Float: 'Float',
  Decimal: 'Decimal',
  Boolean: 'Boolean',
  DateTime: 'DateTime',
  Json: 'Json',
};

function getModelFields(
  resource: string,
): { name: string; type: string; required: boolean }[] {
  const key = resource.charAt(0).toUpperCase() + resource.slice(1);
  const entry = (modelsMap as Record<string, { model: Record<string, any> }>)[
    key
  ];
  if (!entry?.model) return [];
  return Object.values(entry.model).map((f) => ({
    name: f.name,
    type: TYPE_SHORT[f.type] ?? f.type,
    required: f.isRequired,
  }));
}

interface Props {
  getPageContext: () => PageContext | null;
  onConfirm: (prompt: string) => void;
  onCancel: () => void;
}

export default function EditDataModal({
  getPageContext,
  onConfirm,
  onCancel,
}: Props) {
  const [text, setText] = useState('');
  const r = getPageContext()?.resourceName || '';
  const fields = r ? getModelFields(r) : [];

  function handleConfirm() {
    if (!text.trim()) {
      alert('请描述你想做的修改');
      return;
    }
    onConfirm(
      '请帮我使用 prisma-schema-update skill 修改' +
        (r ? ' ' + r : '') +
        ' 的 prisma model。\n\n以下是修改需求：\n' +
        text.trim(),
    );
  }

  return (
    <div
      id="edit-data-modal-overlay"
      onClick={(e) => {
        if (e.target === e.currentTarget) onCancel();
      }}
    >
      <div id="edit-data-modal-card">
        <div className="add-data-modal-header">
          <h3>✏️ 修改数据表</h3>
          <button className="add-data-modal-close" onClick={onCancel}>
            ×
          </button>
        </div>
        <div className="edit-data-modal-body">
          {/* 左：字段列表 */}
          <div className="edit-data-fields-panel">
            <div className="edit-data-fields-title">
              {r ? r : '模型'} 现有字段
            </div>
            <div className="edit-data-fields-list">
              {fields.length === 0 ? (
                <span className="edit-data-fields-empty">暂无字段信息</span>
              ) : (
                fields.map((f) => (
                  <div key={f.name} className="edit-data-field-row">
                    <span className="edit-data-field-name">{f.name}</span>
                    <span
                      className={`edit-data-field-type${f.required ? '' : ' optional'}`}
                    >
                      {f.type}
                      {f.required ? '' : '?'}
                    </span>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* 右：输入区 */}
          <div className="edit-data-input-panel">
            <p
              className="add-data-hint"
              dangerouslySetInnerHTML={{
                __html:
                  '描述你想对' +
                  (r ? ' <strong>' + r + '</strong>' : '当前数据表') +
                  ' 做的修改，越详细越好：',
              }}
            />
            <textarea
              className="add-data-free-textarea edit-data-textarea"
              placeholder="比如：增加一个手机号字段、把状态改为枚举类型 pending/active/closed、给 userId 加索引…"
              value={text}
              onChange={(e) => setText(e.target.value)}
              autoFocus
            />
          </div>
        </div>
        <div className="add-data-modal-footer">
          <button className="add-data-btn-cancel" onClick={onCancel}>
            取消
          </button>
          <button className="add-data-btn-confirm" onClick={handleConfirm}>
            确认，开始修改
          </button>
        </div>
      </div>
    </div>
  );
}
