import { type MetaFunction } from "@remix-run/node";
import { useState, useEffect } from "react";
import { BasicInfo } from "~/components/rules/new/BasicInfo";
import { ExtractionSettings } from "~/components/rules/new/ExtractionSettings";
import { ReviewSettings, RuleContext } from "~/components/rules/new/ReviewSettings";
import { ActionButtons } from "~/components/rules/new/ActionButtons";
import { PageHeader } from "~/components/rules/new/PageHeader";
import rulesStyles from "~/styles/rules.css?url";
import { useNavigate, useLocation } from "@remix-run/react";

export const meta: MetaFunction = () => {
  return [
    { title: "评查点管理 - 中国烟草AI合同及卷宗审核系统" },
    { 
      name: "description", 
      content: "创建或修改评查点，设置规则参数" 
    }
  ];
};

export function links() {
  return [{ rel: "stylesheet", href: rulesStyles }];
}

export const handle = {
  breadcrumb: "评查点管理"
};

// 定义类型
interface RegexField {
  fieldName: string;
  regex: string;
}

interface ApiRegexField {
  field: string;
  pattern: string;
}

interface ApiVlmField {
  name: string;
  type: string;
}

interface PromptSetting {
  type: string;
  template: string;
}

interface ExtactionConfigType {
  llm_ocr: {
    fields: string[];
    prompt_setting: PromptSetting;
  };
  llm_vl: {
    fields: string[];
    prompt_setting: PromptSetting;
  };
  ocr_regex: {
    fields: RegexField[];
  };
}

interface ApiExtactionConfigType {
  llm?: {
    fields?: string[];
    prompt_setting?: {
      type?: string;
      template?: string;
    }
  };
  vlm?: {
    fields?: ApiVlmField[];
    prompt_setting?: {
      type?: string;
      template?: string;
    }
  };
  regex?: {
    fields?: ApiRegexField[];
  };
}

interface RuleConfigType {
  [key: string]: unknown;
}

interface Rule {
  id: string;
  type: string;
  config: RuleConfigType;
}

interface EvaluationConfigType {
  logicType: string;
  customLogic: string;
  rules: Rule[];
}

interface FormDataType {
  id?: number;
  name: string;
  code: string;
  risk: string;
  is_enabled: boolean;
  description: string;
  references_laws: {
    name: string;
    articles: string[];
    content: string;
  };
  evaluation_point_groups_id: number | null;
  extraction_config: ExtactionConfigType;
  evaluation_config: EvaluationConfigType;
  pass_message: string;
  fail_message: string;
  suggestion_message: string;
  suggestion_message_type: string;
  post_action: string;
  action_config: string;
  type?: string;
}

// API响应类型
interface ApiResponseType<T> {
  code: number;
  msg: string;
  data: T;
}

interface ApiPointData {
  id: number;
  name: string;
  code: string;
  risk: string;
  is_enabled: boolean;
  description: string;
  references_laws: {
    name: string;
    articles: string[];
    content: string;
  };
  evaluation_point_groups_id: number | null;
  extraction_config: ApiExtactionConfigType;
  evaluation_config: {
    logicType?: string;
    customLogic?: string;
    rules?: Array<{
      id: string;
      type: string;
      config: Record<string, unknown>;
    }>;
  };
  pass_message: string;
  fail_message: string;
  suggestion_message: string;
  suggestion_message_type: string;
  post_action: string;
  action_config: string;
  type?: string;
}

export default function RuleNew() {
  const navigate = useNavigate();
  const location = useLocation();
  const [extractionFields, setExtractionFields] = useState<string[]>([]);
  const [isEditMode, setIsEditMode] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [formData, setFormData] = useState<FormDataType>({
    // 基本信息字段
    name: '',
    code: '',
    risk: 'medium',
    is_enabled: true,
    description: '',
    references_laws: {
      name: '',
      articles: [],
      content: ''
    },
    evaluation_point_groups_id: null,
    type: '',
    
    // 抽取设置
    extraction_config: {
      llm_ocr: {
        fields: [],
        prompt_setting: {
          type: 'system',
          template: ''
        }
      },
      llm_vl: {
        fields: [],
        prompt_setting: {
          type: 'system',
          template: ''
        }
      },
      ocr_regex: {
        fields: []
      }
    },
    
    // 评查设置
    evaluation_config: {
      logicType: 'and',
      customLogic: '',
      rules: []
    },
    
    // 评查结果消息
    pass_message: '文档检查通过，符合规范要求。',
    fail_message: '文档存在以下问题，请修改后重新提交。',
    suggestion_message: '',
    suggestion_message_type: 'warning',
    
    // 评查后动作
    post_action: 'none',
    action_config: ''
  });

  // 页面加载时检查URL中是否有ID参数，如果有则为编辑模式
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const id = searchParams.get('id');
    
    if (id) {
      setIsEditMode(true);
      fetchEvaluationPoint(parseInt(id));
    }
  }, [location]);

  // 获取评查点数据
  const fetchEvaluationPoint = async (id: number) => {
    setIsLoading(true);
    try {
      const response = await fetch(`http://127.0.0.1:9000/admin/evaluation_points?id=eq.${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error(`获取评查点数据失败: ${response.status}`);
      }

      const responseData = await response.json() as ApiResponseType<ApiPointData[]>;
      
      // 根据API返回结构解析数据
      if (responseData && responseData.code === 0 && responseData.data && responseData.data.length > 0) {
        const pointData = responseData.data[0];
        
        // 转换API数据为表单数据格式
        const extractionConfig = pointData.extraction_config || {};
        const evaluationConfig = pointData.evaluation_config || {};
        
        // 提取字段列表，用于规则设置
        const extractedFields: string[] = [
          ...(extractionConfig.llm?.fields || []),
          ...(extractionConfig.vlm?.fields || []).map((field) => {
            if (typeof field === 'object' && field.name) {
              return field.type ? `${field.name}_${field.type}` : field.name;
            }
            return '';
          }),
          ...(extractionConfig.regex?.fields || []).map((field) => field.field || '')
        ].filter(Boolean);
        
        setExtractionFields(extractedFields);
        
        // 构建表单数据
        setFormData({
          id: pointData.id,
          name: pointData.name || '',
          code: pointData.code || '',
          risk: pointData.risk || 'medium',
          is_enabled: pointData.is_enabled || false,
          description: pointData.description || '',
          references_laws: pointData.references_laws || {
            name: '',
            articles: [],
            content: ''
          },
          evaluation_point_groups_id: pointData.evaluation_point_groups_id || null,
          type: pointData.type || '',
          
          // 将API数据格式转换为内部使用的格式
          extraction_config: {
            llm_ocr: {
              fields: extractionConfig.llm?.fields || [],
              prompt_setting: {
                type: extractionConfig.llm?.prompt_setting?.type || 'system',
                template: extractionConfig.llm?.prompt_setting?.template || ''
              }
            },
            llm_vl: {
              fields: (extractionConfig.vlm?.fields || []).map((field) => {
                if (typeof field === 'object' && field.name) {
                  return field.type ? `${field.name}_${field.type}` : field.name;
                }
                return '';
              }).filter(Boolean),
              prompt_setting: {
                type: extractionConfig.vlm?.prompt_setting?.type || 'system',
                template: extractionConfig.vlm?.prompt_setting?.template || ''
              }
            },
            ocr_regex: {
              fields: (extractionConfig.regex?.fields || []).map((field) => ({
                fieldName: field.field || '',
                regex: field.pattern || ''
              }))
            }
          },
          
          evaluation_config: {
            logicType: evaluationConfig.logicType || 'and',
            customLogic: evaluationConfig.customLogic || '',
            rules: (evaluationConfig.rules || []).map((rule) => {
              // 将API规则格式转换为UI使用的格式
              let config: RuleConfigType = {};
              
              switch (rule.type) {
                case 'exists':
                  config = {
                    selectedFields: rule.config?.fields || [],
                    logicRelation: rule.config?.logic || 'and'
                  };
                  break;
                case 'consistency':
                  config = {
                    pairs: rule.config?.pairs || [],
                    logicRelation: rule.config?.logic || 'and'
                  };
                  break;
                case 'format':
                  config = {
                    field: rule.config?.field || '',
                    formatType: rule.config?.formatType || '',
                    parameters: rule.config?.parameters || ''
                  };
                  break;
                case 'logic':
                  config = {
                    conditions: rule.config?.conditions || [],
                    logicRelation: rule.config?.logic || 'and'
                  };
                  break;
                case 'regex':
                  config = {
                    field: rule.config?.field || '',
                    pattern: rule.config?.pattern || '',
                    matchType: rule.config?.matchType || 'match'
                  };
                  break;
                case 'ai':
                  config = {
                    model: rule.config?.model || 'qwen14b',
                    temperature: rule.config?.temperature || 0.1,
                    prompt: rule.config?.prompt || ''
                  };
                  break;
                case 'code':
                  config = {
                    language: rule.config?.language || 'javascript',
                    code: rule.config?.code || ''
                  };
                  break;
                default:
                  config = rule.config || {};
              }
              
              return {
                id: rule.id,
                type: rule.type,
                config
              };
            })
          },
          
          pass_message: pointData.pass_message || '文档检查通过，符合规范要求。',
          fail_message: pointData.fail_message || '文档存在以下问题，请修改后重新提交。',
          suggestion_message: pointData.suggestion_message || '',
          suggestion_message_type: pointData.suggestion_message_type || 'warning',
          post_action: pointData.post_action || 'none',
          action_config: pointData.action_config || ''
        });
      } else {
        throw new Error('未找到评查点数据或数据格式不正确');
      }
    } catch (error) {
      console.error('获取评查点数据失败:', error);
      alert(`获取评查点数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setIsLoading(false);
    }
  };

  // 更新抽取字段列表，用于在评查规则中选择
  const updateExtractionFields = (fields: string[]) => {
    setExtractionFields(fields);
  };

  // 处理BasicInfo组件数据变更
  const handleBasicInfoChange = (data: Record<string, unknown>) => {
    setFormData(prevData => ({
      ...prevData,
      ...data
    }));
  };

  // 处理ExtractionSettings组件数据变更
  const handleExtractionSettingsChange = (data: Record<string, unknown>) => {
    setFormData(prevData => {
      // 获取数据
      const extractionMethod = data.extractionMethod as string;
      const regexFields = data.regexFields as Array<{ id: string; fieldName: string; regex: string }>;
      const fields = data.fields as Record<string, string[]>;
      
      // 根据抽取方法更新对应字段
      const updatedExtractionConfig = { ...prevData.extraction_config };
      
      // 更新正则抽取字段
      if (regexFields) {
        updatedExtractionConfig.ocr_regex.fields = regexFields
          .filter(field => field.fieldName && field.regex)
          .map(field => ({
            fieldName: field.fieldName,
            regex: field.regex
          }));
      }
      
      // 更新LLM字段
      if (fields) {
        if (fields.llm_ocr) {
          updatedExtractionConfig.llm_ocr.fields = fields.llm_ocr;
        }
        if (fields.llm) {
          updatedExtractionConfig.llm_vl.fields = fields.llm;
        }
      }
      
      // 更新提示词设置
      if (data.promptSettings) {
        const promptSettings = data.promptSettings as Record<string, unknown>;
        
        // 确定当前是处理哪种类型的提示词
        if (extractionMethod === 'llm_ocr') {
          updatedExtractionConfig.llm_ocr.prompt_setting.type = promptSettings.type as string || 'system';
          updatedExtractionConfig.llm_ocr.prompt_setting.template = promptSettings.content as string || '';
        } else if (extractionMethod === 'llm') {
          updatedExtractionConfig.llm_vl.prompt_setting.type = promptSettings.type as string || 'system';
          updatedExtractionConfig.llm_vl.prompt_setting.template = promptSettings.content as string || '';
        }
      } else {
        // 兼容旧的API
        if (data.promptType) {
          const promptType = data.promptType as Record<string, string>;
          if (promptType.llm_ocr) {
            updatedExtractionConfig.llm_ocr.prompt_setting.type = promptType.llm_ocr;
          }
          if (promptType.llm) {
            updatedExtractionConfig.llm_vl.prompt_setting.type = promptType.llm;
          }
        }
        
        if (data.promptContent) {
          const promptContent = data.promptContent as Record<string, string>;
          if (promptContent.llm_ocr) {
            updatedExtractionConfig.llm_ocr.prompt_setting.template = promptContent.llm_ocr;
          }
          if (promptContent.llm) {
            updatedExtractionConfig.llm_vl.prompt_setting.template = promptContent.llm;
          }
        }
      }
      
      console.log('更新的抽取设置:', updatedExtractionConfig);
      
      return {
        ...prevData,
        extraction_config: updatedExtractionConfig
      };
    });
  };

  // 处理ReviewSettings组件数据变更
  const handleReviewSettingsChange = (data: Record<string, unknown>) => {
    setFormData(prevData => {
      const updatedData = { ...prevData };
      
      // 更新规则
      if (data.rules) {
        updatedData.evaluation_config.rules = data.rules as Rule[];
      }
      
      // 更新组合逻辑
      if (data.combinationLogic !== undefined) {
        updatedData.evaluation_config.logicType = data.combinationLogic as string;
      }
      
      // 更新自定义逻辑
      if (data.customLogic !== undefined) {
        updatedData.evaluation_config.customLogic = data.customLogic as string;
      }
      
      // 更新通过/不通过/建议消息
      if (data.pass_message !== undefined) {
        updatedData.pass_message = data.pass_message as string;
      }
      
      if (data.fail_message !== undefined) {
        updatedData.fail_message = data.fail_message as string;
      }
      
      if (data.suggestion_message !== undefined) {
        updatedData.suggestion_message = data.suggestion_message as string;
      }
      
      if (data.suggestion_message_type !== undefined) {
        updatedData.suggestion_message_type = data.suggestion_message_type as string;
      }
      
      // 更新评查后动作
      if (data.post_action !== undefined) {
        updatedData.post_action = data.post_action as string;
      }
      
      if (data.action_config !== undefined) {
        updatedData.action_config = data.action_config as string;
      }
      
      return updatedData;
    });
  };

  // 格式化数据，准备提交到接口
  const formatDataForApi = (formData: FormDataType, isDraft: boolean = false) => {
    // 转换提取配置为符合数据库格式的JSON
    const extractionConfig = {
      llm: {
        fields: formData.extraction_config.llm_ocr.fields || [],
        prompt_setting: {
          type: formData.extraction_config.llm_ocr.prompt_setting.type || 'system',
          template: formData.extraction_config.llm_ocr.prompt_setting.template || ''
        }
      },
      vlm: {
        fields: (formData.extraction_config.llm_vl.fields || []).map((field: string) => {
          // 处理带有类型后缀的字段名 (如 "字段名_类型")
          if (field.includes('_')) {
            const [name, type] = field.split('_');
            return {
              name,
              type: type || 'default'
            };
          }
          return { name: field, type: 'default' };
        }),
        prompt_setting: {
          type: formData.extraction_config.llm_vl.prompt_setting.type || 'system',
          template: formData.extraction_config.llm_vl.prompt_setting.template || ''
        }
      },
      regex: {
        fields: (formData.extraction_config.ocr_regex.fields || []).map((field: RegexField) => {
          return {
            field: field.fieldName || '',
            pattern: field.regex || ''
          };
        })
      }
    };
    
    // 转换评查配置为符合数据库格式的JSON
    const evaluationConfig = {
      logicType: formData.evaluation_config.logicType || 'and',
      customLogic: formData.evaluation_config.customLogic || '',
      rules: (formData.evaluation_config.rules || []).map((rule: Rule) => {
        let config = {};
        
        // 根据不同的规则类型生成对应的配置
        switch (rule.type) {
          case 'exists': 
            config = {
              fields: rule.config?.selectedFields || [],
              logic: rule.config?.logicRelation || 'and'
            };
            break;
          case 'consistency':
            config = {
              pairs: rule.config?.pairs || [],
              logic: rule.config?.logicRelation || 'and'
            };
            break;
          case 'format':
            config = {
              field: rule.config?.field || '',
              formatType: rule.config?.formatType || '',
              parameters: rule.config?.parameters || ''
            };
            break;
          case 'logic':
            config = {
              conditions: rule.config?.conditions || [],
              logic: rule.config?.logicRelation || 'and'
            };
            break;
          case 'regex':
            config = {
              field: rule.config?.field || '',
              pattern: rule.config?.pattern || '',
              matchType: rule.config?.matchType || 'match'
            };
            break;
          case 'ai':
            config = {
              model: rule.config?.model || 'qwen14b',
              temperature: rule.config?.temperature || 0.1,
              prompt: rule.config?.prompt || ''
            };
            break;
          case 'code':
            config = {
              language: rule.config?.language || 'javascript',
              code: rule.config?.code || ''
            };
            break;
          default:
            config = rule.config || {};
        }
        
        return {
          id: rule.id,
          type: rule.type,
          config
        };
      })
    };

    // 构建完整的评查点数据
    const evaluationPointData: Record<string, unknown> = {
      code: formData.code,
      name: formData.name,
      evaluation_point_groups_id: formData.evaluation_point_groups_id,
      risk: formData.risk,
      description: formData.description,
      is_enabled: isDraft ? false : formData.is_enabled,
      is_draft: isDraft,
      type: formData.type,
      references_laws: formData.references_laws,
      extraction_config: extractionConfig,
      evaluation_config: evaluationConfig,
      pass_message: formData.pass_message,
      fail_message: formData.fail_message,
      suggestion_message: formData.suggestion_message,
      suggestion_message_type: formData.suggestion_message_type,
      post_action: formData.post_action,
      action_config: formData.action_config
    };

    // 如果是编辑模式，添加ID
    if (isEditMode && formData.id) {
      evaluationPointData.id = formData.id;
    }
    
    return evaluationPointData;
  };

  // 保存评查点
  const handleSave = async () => {
    try {
      setIsLoading(true);
      const evaluationPointData = formatDataForApi(formData);
      
      // 确定使用的HTTP方法和URL
      let method = 'POST';
      let endpoint = 'http://127.0.0.1:9000/admin/evaluation_points';
      
      // 如果是编辑模式，使用PATCH更新现有记录
      if (isEditMode && formData.id) {
        method = 'PATCH';
        endpoint = `http://127.0.0.1:9000/admin/evaluation_points?id=eq.${formData.id}`;
      }
      
      // 发送数据到API
      const response = await fetch(endpoint, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Prefer': isEditMode ? 'return=representation' : 'return=representation'
        },
        body: JSON.stringify(evaluationPointData)
      });
      
      if (!response.ok) {
        throw new Error(`API响应错误: ${response.status}`);
      }
      
      const responseData = await response.json() as ApiResponseType<unknown>;
      
      if (responseData.code === 0) {
        console.log('保存成功:', responseData.data);
        // 保存成功后跳转到评查点列表页面
        navigate('/rules');
      } else {
        throw new Error(`API错误: ${responseData.msg || '未知错误'}`);
      }
    } catch (error) {
      console.error('保存失败:', error);
      alert(`保存失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setIsLoading(false);
    }
  };
  
  // 保存为草稿
  const handleSaveDraft = async () => {
    try {
      setIsLoading(true);
      const draftData = formatDataForApi(formData, true);
      
      // 确定使用的HTTP方法和URL
      let method = 'POST';
      let endpoint = 'http://127.0.0.1:9000/admin/evaluation_points';
      
      // 如果是编辑模式，使用PATCH更新现有记录
      if (isEditMode && formData.id) {
        method = 'PATCH';
        endpoint = `http://127.0.0.1:9000/admin/evaluation_points?id=eq.${formData.id}`;
      }
      
      // 发送数据到API
      const response = await fetch(endpoint, {
        method: method,
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Prefer': 'return=representation'
        },
        body: JSON.stringify(draftData)
      });
      
      if (!response.ok) {
        throw new Error(`API响应错误: ${response.status}`);
      }
      
      const responseData = await response.json() as ApiResponseType<unknown>;
      
      if (responseData.code === 0) {
        console.log('保存草稿成功:', responseData.data);
        // 保存成功后跳转到评查点列表页面
        navigate('/rules');
      } else {
        throw new Error(`API错误: ${responseData.msg || '未知错误'}`);
      }
    } catch (error) {
      console.error('保存草稿失败:', error);
      alert(`保存草稿失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="container">
      <PageHeader 
        title={isEditMode ? "编辑评查点" : "新增评查点"} 
        onSave={handleSave} 
      />
      
      {isLoading ? (
        <div className="flex justify-center items-center p-12">
          <div className="loading-spinner"></div>
          <span className="ml-3">加载中...</span>
        </div>
      ) : (
        <>
          <div className="mb-8">
            <BasicInfo onChange={handleBasicInfoChange} initialData={formData} />
          </div>
          
          <div className="mb-8">
            <RuleContext.Provider value={{ extractionFields, updateFields: updateExtractionFields }}>
              <ExtractionSettings 
                onChange={handleExtractionSettingsChange} 
                initialData={{
                  llm_ocr: formData.extraction_config.llm_ocr,
                  llm_vl: formData.extraction_config.llm_vl,
                  ocr_regex: formData.extraction_config.ocr_regex
                }} 
              />
            </RuleContext.Provider>
          </div>
          
          <div className="mb-8">
            <RuleContext.Provider value={{ extractionFields, updateFields: updateExtractionFields }}>
              <ReviewSettings 
                onChange={handleReviewSettingsChange} 
                initialData={{
                  rules: formData.evaluation_config.rules,
                  combinationLogic: formData.evaluation_config.logicType,
                  customLogic: formData.evaluation_config.customLogic,
                  pass_message: formData.pass_message,
                  fail_message: formData.fail_message,
                  suggestion_message: formData.suggestion_message,
                  suggestion_message_type: formData.suggestion_message_type,
                  post_action: formData.post_action,
                  action_config: formData.action_config
                }} 
              />
            </RuleContext.Provider>
          </div>
          
          <ActionButtons 
            onSave={handleSave}
            onSaveDraft={handleSaveDraft}
            isEditMode={isEditMode}
          />
        </>
      )}
    </div>
  );
}
