/**
 * 评查点管理页面 - 创建或编辑评查点规则
 * 
 * 功能概述:
 * - 支持创建新的评查点规则或编辑现有规则
 * - 评查点包含基本信息、抽取设置和评查设置三大部分
 * - 支持使用三种抽取方式: 大模型(LLM)抽取、多模态(VLM)抽取和正则表达式抽取
 * - 支持配置各种类型的评查规则，如存在性检查、内容一致性检查等
 * - 支持保存评查规则和保存草稿功能
 * 
 * 组件结构:
 * - PageHeader: 页面标题和保存按钮
 * - BasicInfo: 评查点的基本信息设置，如名称、编码、风险级别等
 * - ExtractionSettings: 抽取设置，配置从文档中抽取哪些字段及抽取方式
 * - ReviewSettings: 评查设置，基于抽取字段配置评查规则、评查结果消息等
 * - ActionButtons: 页面底部的操作按钮，包括保存、保存草稿和返回
 * 
 * 数据流转:
 * 1. 页面加载时检查URL参数，确定是新建还是编辑模式
 * 2. 编辑模式下从API获取评查点数据并填充表单
 * 3. ExtractionSettings通过RuleContext将抽取的字段传递给ReviewSettings
 * 4. 各组件的onChange回调收集表单变更并更新formData状态
 * 5. 保存时将formData转换为API需要的格式并提交
 * 
 * @author 中国烟草AI合同及卷宗审核系统开发团队
 */

import { type MetaFunction } from "@remix-run/node";
import { useState, useEffect, useCallback } from "react";
import { BasicInfo } from "~/components/rules/new/BasicInfo";
import { ExtractionSettings } from "~/components/rules/new/ExtractionSettings";
import { ReviewSettings } 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";
// 导入评查点模型定义和常量
import type {
  EvaluationPoint
} from "~/models/evaluation_points";
import { EVALUATION_OPTIONS } from "~/models/evaluation_points";
import type { EvaluationPointGroup } from "~/models/evaluation_point_groups";
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 location = useLocation();
  const [isEditMode, setIsEditMode] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const [formData, setFormData] = useState<EvaluationPoint>({});
  const [evaluationPointGroups, setEvaluationPointGroups] = useState<EvaluationPointGroup[]>([]);

  /**
   * 获取评查点数据
   * 编辑模式下从API获取指定ID的评查点数据
   * @param id 评查点ID
   */
  const fetchEvaluationPoint = useCallback(async (id: number) => {
    try {
      setIsLoading(true);
      console.log(`获取评查点数据，ID: ${id}`);
      const response = await fetch(`http://127.0.0.1:9000/admin/evaluation_points?id=eq.${id}`, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      });
      console.log(response);
      if (response.ok) {
        const data = await response.json();
        setFormData(data.data[0]);
      }
    } catch (error) {
      console.error('获取评查点数据失败:', error);
      alert(`获取评查点数据失败: ${error instanceof Error ? error.message : '未知错误'}`);
      // 获取数据失败时返回上一页
      navigate(-1);
    } finally {
      setIsLoading(false);
    }
  }, [navigate]);

  /**
   * 获取评查点组数据
   * 从API获取所有评查点组，用于基本信息表单中选择
   */
  const fetchEvaluationPointGroups = useCallback(async () => {
    try {
      console.log("获取评查点组数据");
      const response = await fetch("http://127.0.0.1:9000/admin/evaluation_point_groups", {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      });
      console.log(response);
      if (response.ok) {
        const data = await response.json();
        setEvaluationPointGroups(data.data);
      }
    } catch (error) {
      console.error('获取评查点组数据失败:', error);
      // 显示错误提示但不影响应用继续使用
      alert(`获取评查点组数据失败: ${error instanceof Error ? error.message : '未知错误'}\n将使用默认数据`);
    }
  }, []);

  const handleSave = () => {
    console.log("保存评查点", formData);
  }

  const handleSaveDraft = () => {
    console.log("保存草稿");
  }

  const handleBasicInfoChange = (data: Record<string, unknown>) => {
    setFormData(prev => ({ ...prev, ...data }));
  }

  const handleExtractionSettingsChange = (data: Record<string, unknown>) => {
    setFormData(prev => ({ ...prev, ...data }));
  }

  const handleReviewSettingsChange = (data: Record<string, unknown>) => {
    setFormData(prev => ({ ...prev, ...data }));
  }

  /**
   * 页面加载时初始化处理
   * 1. 检查URL参数，判断是新建还是编辑模式
   * 2. 编辑模式下获取评查点数据
   * 3. 获取评查点组数据（用于表单选择项）
   */
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    const id = searchParams.get('id');
    
    // 设置编辑模式
    setIsEditMode(!!id);
    
    if (id) {
      fetchEvaluationPoint(parseInt(id));
    }

    // 获取评查点组数据
    fetchEvaluationPointGroups();
  }, [location.search, fetchEvaluationPoint, fetchEvaluationPointGroups]);

  // 渲染页面内容
  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}
              evaluationPointGroups={evaluationPointGroups}
              riskOptions={EVALUATION_OPTIONS.riskLevelOptions}
            />
          </div>

          {/* 抽取设置 - 配置从文档中提取的字段 */}
          <div className="mb-8">
            <ExtractionSettings
              onChange={handleExtractionSettingsChange}
              initialData={{
                llm: {
                  fields: formData.extraction_config?.llm?.fields,
                  prompt_setting: {
                    type: formData.extraction_config?.llm?.prompt_setting?.type,
                    template: formData.extraction_config?.llm?.prompt_setting?.template
                  }
                },
                vlm: {
                  fields: formData.extraction_config?.vlm?.fields,
                  prompt_setting: {
                    type: formData.extraction_config?.vlm?.prompt_setting?.type,
                    template: formData.extraction_config?.vlm?.prompt_setting?.template
                  }
                },
                regex: {
                  fields: formData.extraction_config?.regex?.fields
                }
              }}
              promptTypeOptions={EVALUATION_OPTIONS.promptTypeOptions}
              vlmFieldTypeOptions={EVALUATION_OPTIONS.vlmFieldTypeOptions}
            />
          </div>

          {/* 评查设置 - 配置评查规则、消息等 */}
          <div className="mb-8">
            <ReviewSettings
              key={`review-settings-${isEditMode ? formData.id : 'new'}`}
              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,
                  score: formData.score
                }}
                ruleTypeOptions={EVALUATION_OPTIONS.ruleTypeOptions}
                logicTypeOptions={EVALUATION_OPTIONS.logicTypeOptions}
                logicOperatorOptions={EVALUATION_OPTIONS.logicOperatorOptions}
                compareMethodOptions={EVALUATION_OPTIONS.compareMethodOptions}
                formatTypeOptions={EVALUATION_OPTIONS.formatTypeOptions}
                comparisonOperatorOptions={EVALUATION_OPTIONS.comparisonOperatorOptions}
                matchTypeOptions={EVALUATION_OPTIONS.matchTypeOptions}
                suggestionMessageTypeOptions={EVALUATION_OPTIONS.suggestionMessageTypeOptions}
              postActionOptions={EVALUATION_OPTIONS.postActionOptions}
            />
          </div>

          {/* 底部操作按钮区域 */}
          <ActionButtons
            onSave={handleSave}
            onSaveDraft={handleSaveDraft}
            isEditMode={isEditMode}
          />
        </>
      )}
    </div>
  );
}
