import { type MetaFunction } from "@remix-run/node";
import { useState } 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 } 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: "新增评查点"
};

export default function RuleNew() {
  const navigate = useNavigate();
  const [extractionFields, setExtractionFields] = useState<string[]>([]);
  const [formData, setFormData] = useState({
    // 基本信息字段
    name: '',
    code: '',
    risk: 'medium',
    is_enabled: true,
    description: '',
    references_laws: {
      name: '',
      articles: [],
      content: ''
    },
    evaluation_point_groups_id: null,
    
    // 抽取设置
    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: ''
  });

  // 更新抽取字段列表，用于在评查规则中选择
  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 => ({
      ...prevData,
      ...data
    }));
  };

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

  // 保存评查点
  const handleSave = async () => {
    try {
      // 构建完整的评查点数据
      const evaluationPointData = {
        code: formData.code,
        name: formData.name,
        evaluation_point_groups_id: formData.evaluation_point_groups_id,
        risk: formData.risk,
        description: formData.description,
        is_enabled: formData.is_enabled,
        references_laws: formData.references_laws,
        extraction_config: formData.extraction_config,
        evaluation_config: formData.evaluation_config,
        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
      };
      
      // 发送数据到API
      const response = await fetch('/api/evaluation-points', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(evaluationPointData)
      });
      
      if (!response.ok) {
        throw new Error(`API响应错误: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('保存成功:', result);
      
      // 保存成功后跳转到评查点列表页面
      navigate('/rules');
    } catch (error) {
      console.error('保存失败:', error);
      alert(`保存失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };
  
  // 保存为草稿
  const handleSaveDraft = async () => {
    try {
      // 构建带草稿标记的评查点数据
      const draftData = {
        ...formData,
        is_enabled: false, // 草稿默认不启用
        is_draft: true // 标记为草稿
      };
      
      // 发送数据到API
      const response = await fetch('/api/evaluation-points/draft', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(draftData)
      });
      
      if (!response.ok) {
        throw new Error(`API响应错误: ${response.status}`);
      }
      
      const result = await response.json();
      console.log('保存草稿成功:', result);
      
      // 保存成功后跳转到评查点列表页面
      navigate('/rules');
    } catch (error) {
      console.error('保存草稿失败:', error);
      alert(`保存草稿失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  };

  return (
    <div className="container">
      <PageHeader 
        title="新增评查点" 
        onSave={handleSave} 
      />
      
      <div className="mb-8">
        <BasicInfo onChange={handleBasicInfoChange} />
      </div>
      
      <div className="mb-8">
        <RuleContext.Provider value={{ extractionFields, updateFields: updateExtractionFields }}>
          <ExtractionSettings onChange={handleExtractionSettingsChange} />
        </RuleContext.Provider>
      </div>
      
      <div className="mb-8">
        <RuleContext.Provider value={{ extractionFields, updateFields: updateExtractionFields }}>
          <ReviewSettings onChange={handleReviewSettingsChange} />
        </RuleContext.Provider>
      </div>
      
      <ActionButtons 
        onSave={handleSave}
        onSaveDraft={handleSaveDraft}
      />
    </div>
  );
}
