import { type MetaFunction, LinksFunction } 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";

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

export const links: LinksFunction = () => [
  { rel: "stylesheet", href: rulesStyles }
];

export const handle = {
  breadcrumb: "新增评查点"
};

export default function RuleNew() {
  // 用于保存抽取字段的状态，在抽取设置和评查设置组件之间共享
  const [extractionFields, setExtractionFields] = useState<string[]>([]);
  
  const updateExtractionFields = (fields: string[]) => {
    setExtractionFields(fields);
  };

  const handleSave = () => {
    // 实现保存逻辑
    console.log('保存评查点');
  };
  
  const handleSaveDraft = () => {
    // 实现保存草稿逻辑
    console.log('保存为草稿');
  };

  const handleExtractionChange = (data: Record<string, unknown>) => {
    // 当抽取设置更新时，获取最新的字段列表
    if (data.fields) {
      const fieldData = data.fields as Record<string, string[]>;
      const currentMethod = data.extractionMethod as string;
      
      // 提取当前抽取方法的字段
      if (fieldData[currentMethod]) {
        updateExtractionFields(fieldData[currentMethod]);
      }
    } else if (data.regexFields) {
      // 处理正则字段情况
      const regexFields = data.regexFields as { id: string; fieldName: string; regex: string }[];
      const fieldNames = regexFields
        .map(field => field.fieldName)
        .filter(name => name.trim() !== '');
        
      updateExtractionFields(fieldNames);
    }
  };

  return (
    <RuleContext.Provider value={{ extractionFields, updateExtractionFields }}>
      <div className="px-4 py-6 bg-white border-b border-gray-200 shadow-sm">
        <PageHeader 
          title="新增评查点" 
          onSave={handleSave} 
        />
      </div>
      
      <div className="container py-6">
        <div className="px-4">
          <BasicInfo />
          
          <ExtractionSettings onChange={handleExtractionChange} />
          
          <ReviewSettings />
          
          <ActionButtons 
            onSave={handleSave}
            onSaveDraft={handleSaveDraft}
          />
        </div>
      </div>
    </RuleContext.Provider>
  );
} 