/**
 * 占位符表单组件
 * 用于合同起草时填写占位符值
 */

import { useState, useEffect } from 'react';
import type { PlaceholderSchema } from '~/types/contract-draft';

interface PlaceholderFormProps {
  schema: PlaceholderSchema | null;
  values: Record<string, string>;
  onChange: (values: Record<string, string>) => void;
  onBatchReplace: () => void;
  onExportDocument: () => void;  // 改名：导出文档
  onComplete: () => void;
  isReplacing: boolean;
  isDeleting: boolean;  // 改名：是否正在删除
  onSingleReplace?: (key: string, value: string) => void;  // 单个替换
  onFieldFocus?: (key: string) => void;  // 字段聚焦（高亮）
}

export function PlaceholderForm({
  schema,
  values,
  onChange,
  onBatchReplace,
  onExportDocument,
  onComplete,
  isReplacing,
  isDeleting,
  onSingleReplace,
  onFieldFocus
}: PlaceholderFormProps) {
  const [localValues, setLocalValues] = useState<Record<string, string>>(values);
  const [replacingFields, setReplacingFields] = useState<Set<string>>(new Set());

  // 同步外部 values 到本地状态
  useEffect(() => {
    setLocalValues(values);
  }, [values]);

  // 处理字段变化
  const handleFieldChange = (key: string, value: string) => {
    const newValues = { ...localValues, [key]: value };
    setLocalValues(newValues);
    onChange(newValues);
  };

  // 处理字段聚焦（高亮文档中的占位符）
  const handleFieldFocus = (key: string) => {
    if (onFieldFocus) {
      onFieldFocus(key);
    }
  };

  // 处理单个字段替换
  const handleSingleReplace = async (key: string) => {
    const value = localValues[key];
    if (!value || !onSingleReplace) return;

    setReplacingFields(prev => new Set(prev).add(key));
    try {
      await onSingleReplace(key, value);
    } finally {
      setReplacingFields(prev => {
        const next = new Set(prev);
        next.delete(key);
        return next;
      });
    }
  };

  // 检查是否有未填写的必填字段
  const getMissingRequiredFields = () => {
    if (!schema) return [];
    return schema.fields
      .filter(f => f.required && !localValues[f.key])
      .map(f => f.label);
  };

  const handleCompleteClick = () => {
    const missing = getMissingRequiredFields();
    if (missing.length > 0) {
      alert(`请填写以下必填字段：\n${missing.join('\n')}`);
      return;
    }
    onComplete();
  };

  if (!schema || !schema.fields || schema.fields.length === 0) {
    return (
      <div className="h-full flex items-center justify-center p-8">
        <div className="text-center">
          <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
            <i className="ri-information-line text-3xl text-gray-400"></i>
          </div>
          <h3 className="text-lg font-semibold text-gray-700 mb-2">暂无占位符配置</h3>
          <p className="text-sm text-gray-500">该模板尚未配置占位符字段</p>
          <p className="text-xs text-gray-400 mt-2">请联系管理员配置模板占位符</p>
        </div>
      </div>
    );
  }

  return (
    <div className="h-full flex flex-col bg-white">
      {/* 表单头部 */}
      <div className="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-white">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-primary to-[#004d38] flex items-center justify-center shadow-sm">
            <i className="ri-file-edit-line text-white text-base"></i>
          </div>
          <h2 className="text-lg font-bold text-gray-900">填写合同信息</h2>
        </div>
      </div>

      {/* 表单内容区域 */}
      <div className="flex-1 overflow-y-auto px-6 py-4">
        <div className="space-y-4">
          {schema?.fields.map((field) => (
            <div key={field.key} className="form-field">
              <label className="block text-sm font-medium text-gray-700 mb-1.5">
                {field.label}
                {field.required && (
                  <span className="text-red-500 ml-1">*</span>
                )}
              </label>

              <div className="flex gap-2">
                {field.type === 'textarea' ? (
                  <textarea
                    value={localValues[field.key] || ''}
                    onChange={(e) => handleFieldChange(field.key, e.target.value)}
                    onFocus={() => handleFieldFocus(field.key)}
                    placeholder={field.placeholder || `请输入${field.label}`}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-150 resize-none bg-white text-gray-900 placeholder-gray-400 text-sm"
                    rows={3}
                  />
                ) : (
                  <input
                    type={field.type}
                    value={localValues[field.key] || ''}
                    onChange={(e) => handleFieldChange(field.key, e.target.value)}
                    onFocus={() => handleFieldFocus(field.key)}
                    placeholder={field.placeholder || `请输入${field.label}`}
                    className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary transition-all duration-150 bg-white text-gray-900 placeholder-gray-400 text-sm"
                  />
                )}

                {/* 单独的替换按钮 */}
                <button
                  onClick={() => handleSingleReplace(field.key)}
                  disabled={!localValues[field.key] || replacingFields.has(field.key)}
                  className={`px-3 py-2 rounded-lg transition-all duration-150 flex items-center gap-1.5 text-sm font-medium whitespace-nowrap ${
                    !localValues[field.key] || replacingFields.has(field.key)
                      ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                      : 'bg-primary text-white hover:bg-primary-hover shadow-sm hover:shadow'
                  }`}
                  title="替换此占位符"
                >
                  {replacingFields.has(field.key) ? (
                    <>
                      <i className="ri-loader-4-line animate-spin text-base"></i>
                      <span>替换中</span>
                    </>
                  ) : (
                    <>
                      <i className="ri-refresh-line text-base"></i>
                      <span>替换</span>
                    </>
                  )}
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 操作按钮区域（固定在底部） */}
      <div className="border-t border-gray-200 px-6 py-3 bg-gray-50 flex gap-2">
        <button
          onClick={onBatchReplace}
          disabled={isReplacing || isDeleting}
          className={`flex-1 flex items-center justify-center gap-1.5 px-4 py-2 text-white text-sm font-medium rounded-lg transition-all duration-150 ${
            isReplacing || isDeleting
              ? 'bg-gray-300 cursor-not-allowed'
              : 'bg-gradient-to-r from-primary to-[#004d38] hover:shadow-md active:scale-[0.98]'
          }`}
        >
          {isReplacing ? (
            <>
              <i className="ri-loader-4-line animate-spin"></i>
              <span>替换中</span>
            </>
          ) : (
            <>
              <i className="ri-refresh-line"></i>
              <span>全部替换</span>
            </>
          )}
        </button>

        <button
          onClick={handleCompleteClick}
          disabled={isReplacing || isDeleting}
          className={`flex-1 flex items-center justify-center gap-1.5 px-4 py-2 text-sm font-medium rounded-lg transition-all duration-150 ${
            isReplacing || isDeleting
              ? 'bg-gray-200 text-gray-400 cursor-not-allowed'
              : 'bg-green-600 text-white hover:bg-green-700 hover:shadow-md active:scale-[0.98]'
          }`}
        >
          {isDeleting ? (
            <>
              <i className="ri-loader-4-line animate-spin"></i>
              <span>处理中</span>
            </>
          ) : (
            <>
              <i className="ri-check-line"></i>
              <span>完成</span>
            </>
          )}
        </button>
      </div>
    </div>
  );
}
