import React, { useState, useEffect, useRef } from "react";
import { Form, useActionData, useLoaderData, useNavigate, useSearchParams } from "@remix-run/react";
import { redirect, type MetaFunction, type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
import { Card } from "~/components/ui/Card";
import { Button } from "~/components/ui/Button";
import documentTypesNewStyles from "~/styles/pages/document-types_new.css?url";
import { getAllRuleGroups, type RuleGroup } from "~/api/evaluation_points/rule-groups";
import { getDocumentType, createDocumentType, updateDocumentType } from "~/api/document-types/document-types";
import { getPromptTemplates, type PromptTemplateUI } from "~/api/prompts/prompts";
import { toastService } from "~/components/ui/Toast";

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

export const handle = {
  breadcrumb: (data:LoaderData) => {
    if (data.isEdit) {
      return "编辑文档类型";
    } else {
      return "新增文档类型";
    }
  }
};

interface LoaderData {
  isEdit: boolean;
}

export const meta: MetaFunction = ({ location }) => {
  const isEdit = new URLSearchParams(location.search).has("id");
  return [
    { title: `${isEdit ? "编辑" : "新增"}文档类型 - 中国烟草AI合同及卷宗审核系统` },
    { name: "description", content: `${isEdit ? "编辑" : "新增"}文档类型，设置文档类型名称、描述和关联的评查点分组` }
  ];
};

// 定义模板类型
const TEMPLATE_TYPES = {
  LLM_EXTRACTION: "LLM_Extraction",
  VLM_EXTRACTION: "VLM_Extraction", 
  EVALUATION: "Evaluation", 
  SUMMARY: "Summary"
};

// 定义动作返回的数据类型
interface ActionData {
  result?: boolean;
  errors?: {
    name?: string;
    groups?: string;
    general?: string;
    llmExtractionTemplate?: string;
    vlmExtractionTemplate?: string;
    evaluationTemplate?: string;
    summaryTemplate?: string;
  };
  values?: Record<string, string | string[]>;
}


// 获取数据
export async function loader({ request }: LoaderFunctionArgs) {
  try {
    const url = new URL(request.url);
    const id = url.searchParams.get("id");
    const isEdit = id ? true : false;
    
    // 1. 获取评查点分组 - 使用getAllRuleGroups获取所有分组
    const ruleGroupsResponse = await getAllRuleGroups();
    if (ruleGroupsResponse.error) {
      console.error("获取评查点分组失败:", ruleGroupsResponse.error);
      // throw new Error(ruleGroupsResponse.error);
    }
    
    // ruleGroupsResponse.data已经是树形结构数据，getAllRuleGroups内部已处理好parent-children关系
    const groupsTree = ruleGroupsResponse.error ? [] : ruleGroupsResponse.data || [];

    
    // 2. 获取各类型的提示词模板
    const [llmExtractionTemplatesResponse, vlmExtractionTemplatesResponse, evaluationTemplatesResponse, summaryTemplatesResponse] = 
      await Promise.all([
        getPromptTemplates({ type: TEMPLATE_TYPES.LLM_EXTRACTION }),
        getPromptTemplates({ type: TEMPLATE_TYPES.VLM_EXTRACTION }),
        getPromptTemplates({ type: TEMPLATE_TYPES.EVALUATION }),
        getPromptTemplates({ type: TEMPLATE_TYPES.SUMMARY })
      ]);
    
    // 3. 如果是编辑模式，获取文档类型详情
    let documentType = undefined;
    if (id) {
      const typeResponse = await getDocumentType(id);
      if (typeResponse.data) {
        documentType = typeResponse.data;
      }
    }
    
    return Response.json({
      isEdit,
      documentType,
      ruleGroups: groupsTree,
      llmExtractionTemplates: llmExtractionTemplatesResponse.data?.templates || [],
      vlmExtractionTemplates: vlmExtractionTemplatesResponse.data?.templates || [],
      evaluationTemplates: evaluationTemplatesResponse.data?.templates || [],
      summaryTemplates: summaryTemplatesResponse.data?.templates || []
    });
  } catch (error) {
    console.error("加载数据失败:", error);
    return Response.json({
      isEdit: false,
      documentType: undefined,
      ruleGroups: [],
      llmExtractionTemplates: [],
      vlmExtractionTemplates: [],
      evaluationTemplates: [],
      summaryTemplates: [],
      error: error || "加载数据失败"
    });
  }
}

// 处理表单提交
export async function action({ request }: ActionFunctionArgs) {
  const formData = await request.formData();
  const id = formData.get("id") as string | null;
  const name = formData.get("name") as string;
  const description = formData.get("description") as string;
  const llmExtractionTemplateId = formData.get("llm_extraction_template") as string;
  const vlmExtractionTemplateId = formData.get("vlm_extraction_template") as string;
  const evaluationTemplateId = formData.get("evaluation_template") as string;
  const summaryTemplateId = formData.get("summary_template") as string;
  
  // 获取选中的评查点分组ID列表
  const selectedGroups = formData.getAll("checkpoint_group_ids") as string[];
  
  // 表单验证
  const errors: ActionData["errors"] = {};
  
  // 收集所有错误
  if (!name || name.trim() === "") {
    errors.name = "文档类型名称不能为空";
  }
  
  if (selectedGroups.length === 0) {
    errors.groups = "请至少选择一个关联的评查点分组";
  }
  
  if (!llmExtractionTemplateId) {
    errors.llmExtractionTemplate = "请选择llm抽取提示词模板";
  }

  if (!vlmExtractionTemplateId) {
    errors.vlmExtractionTemplate = "请选择vlm抽取提示词模板";
  }

  if (!evaluationTemplateId) {
    errors.evaluationTemplate = "请选择评查提示词模板";
  }

  if (!summaryTemplateId) {
    errors.summaryTemplate = "请选择总结提示词模板";
  }
  
  // 如果有错误，返回错误信息
  if (Object.keys(errors).length > 0) {
    return Response.json({ errors, result: false });
  }
  
  try {
    // 构建文档类型数据
    const documentTypeData = {
      name,
      description,
      group_ids: selectedGroups,
      // 确保映射关系与prompt_config字段对应正确
      llm_extraction_template_id: llmExtractionTemplateId ? parseInt(llmExtractionTemplateId) : null,
      vlm_extraction_template_id: vlmExtractionTemplateId ? parseInt(vlmExtractionTemplateId) : null,
      evaluation_template_id: evaluationTemplateId ? parseInt(evaluationTemplateId) : null,
      summary_template_id: summaryTemplateId ? parseInt(summaryTemplateId) : null
    };
    
    // 调用API创建或更新文档类型
    let response;
    if (id) {
      // 更新文档类型
      response = await updateDocumentType(id, {
        ...documentTypeData,
        id: parseInt(id)
      });
    } else {
      // 创建新文档类型
      response = await createDocumentType(documentTypeData);
    }
    
    if (response.error) {
      console.error("保存/更新文档类型失败:", response.error);
      throw new Error(response.error);
    }
    
    // 操作成功，重定向到列表页
    return redirect("/document-types");
  } catch (error) {
    console.error("保存文档类型失败:", error);
    return Response.json({
      result: false,
      errors: {
        general: error instanceof Error ? error.message : "保存文档类型失败"
      }
    });
  }
}

export default function DocumentTypeNew() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const isEditMode = searchParams.has("id");
  
  const { 
    documentType, 
    ruleGroups, 
    llmExtractionTemplates,
    vlmExtractionTemplates,
    evaluationTemplates,
    summaryTemplates
  } = useLoaderData<typeof loader>();
  
  const actionData = useActionData<ActionData>();
  
  // 状态管理
  const [formData, setFormData] = useState({
    id: documentType?.id || "",
    name: documentType?.name || "",
    description: documentType?.description || "",
    llmExtractionTemplateId: documentType?.llm_extraction_template_id || "",
    vlmExtractionTemplateId: documentType?.vlm_extraction_template_id || "",
    evaluationTemplateId: documentType?.evaluation_template_id || "",
    summaryTemplateId: documentType?.summary_template_id || "",
    selectedGroups: documentType?.groups?.map((g: { id: string }) => g.id) || []
  });
  
  // 添加本地验证错误状态
  const [formErrors, setFormErrors] = useState<ActionData["errors"]>({} as ActionData["errors"]);
  
  // 表单引用
  const formRef = useRef<HTMLFormElement>(null);
  
  // 字段是否被触摸过（用于确定何时显示错误）
  const [touchedFields, setTouchedFields] = useState({
    name: false,
    llmExtractionTemplate: false,
    vlmExtractionTemplate: false,
    evaluationTemplate: false,
    summaryTemplate: false,
    groups: false
  });
  
  // 从actionData初始化本地错误
  useEffect(() => {
    if (!actionData?.result) {
      setFormErrors(actionData?.errors);
      if (actionData?.errors?.general) {
        toastService.error(actionData?.errors?.general || "保存文档类型失败");
      }
    }
  }, [actionData]);
  
  // 分组展开状态
  const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({});
  
  // 当文档类型数据加载完成时更新表单
  useEffect(() => {
    if (documentType) {
      setFormData({
        id: documentType.id,
        name: documentType.name,
        description: documentType.description,
        llmExtractionTemplateId: documentType.llm_extraction_template_id || "",
        vlmExtractionTemplateId: documentType.vlm_extraction_template_id || "",
        evaluationTemplateId: documentType.evaluation_template_id || "",
        summaryTemplateId: documentType.summary_template_id || "",
        selectedGroups: documentType.groups.map((g: { id: string }) => g.id)
      });
      
      // 初始化展开状态 - 对于有选中子分组的父分组，默认展开
      const newExpandedGroups: Record<string, boolean> = {};
      
      ruleGroups.forEach((parentGroup: RuleGroup) => {
        // 如果父分组被选中或者有子分组被选中，则展开
        const isParentSelected = documentType.groups.some((g: { id: string }) => g.id === parentGroup.id);
        const hasSelectedChild = parentGroup.children && 
          parentGroup.children.some(child => 
            documentType.groups.some((g: { id: string }) => g.id === child.id)
          );
          
        if (isParentSelected || hasSelectedChild) {
          newExpandedGroups[parentGroup.id] = true;
        }
      });
      
      setExpandedGroups(newExpandedGroups);
    }
  }, [documentType, ruleGroups]);
  
  // 验证表单字段
  const validateField = (field: string, value: string | string[]): string => {
    switch (field) {
      case 'name':
        return !value || (typeof value === 'string' && value.trim() === "") ? "文档类型名称不能为空" : "";
      case 'llmExtractionTemplate':
        return !value || (typeof value === 'string' && value.trim() === "") ? "请选择llm抽取提示词模板" : "";
      case 'vlmExtractionTemplate':
        return !value || (typeof value === 'string' && value.trim() === "") ? "请选择vlm抽取提示词模板" : "";
      case 'evaluationTemplate':
        return !value || (typeof value === 'string' && value.trim() === "") ? "请选择评查提示词模板" : "";
      case 'summaryTemplate':
        return !value || (typeof value === 'string' && value.trim() === "") ? "请选择总结提示词模板" : "";
      case 'groups':
        return Array.isArray(value) && value.length === 0 ? "请至少选择一个关联的评查点分组" : "";
      default:
        return "";
    }
  };
  
  // 处理分组勾选
  const handleGroupCheckChange = (
    groupId: string, 
    isChecked: boolean
  ) => {
    // 单选模式：清空之前所有选择，只保留当前选中的
    let newSelectedGroups: string[] = [];
    
    if (isChecked) {
      // 只添加当前选中的分组
      newSelectedGroups = [groupId];
    }
    
    setFormData(prev => ({ ...prev, selectedGroups: newSelectedGroups }));
    
    // 标记字段为已触摸
    setTouchedFields(prev => ({...prev, groups: true}));
    
    // 实时验证
    const error = validateField('groups', newSelectedGroups);
    setFormErrors(prev => ({...prev, groups: error}));
  };
  
  // 修复展开/折叠功能
  const handleGroupExpand = (groupId: string, event: React.MouseEvent) => {
    // 阻止事件冒泡，避免触发checkbox选中
    event.stopPropagation();
    
    setExpandedGroups(prev => ({
      ...prev,
      [groupId]: !prev[groupId]
    }));
  };
  
  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    
    // 根据name属性映射到对应的formData字段
    let fieldName = name;
    
    if (name === 'llm_extraction_template') {
      fieldName = 'llmExtractionTemplateId';
      // 标记字段为已触摸
      setTouchedFields(prev => ({...prev, llmExtractionTemplate: true}));
    } else if (name === 'vlm_extraction_template') {
      fieldName = 'vlmExtractionTemplateId';
      // 标记字段为已触摸
      setTouchedFields(prev => ({...prev, vlmExtractionTemplate: true}));
    } else if (name === 'evaluation_template') {
      fieldName = 'evaluationTemplateId';
      // 标记字段为已触摸
      setTouchedFields(prev => ({...prev, evaluationTemplate: true}));
    } else if (name === 'summary_template') {
      fieldName = 'summaryTemplateId';
      // 标记字段为已触摸
      setTouchedFields(prev => ({...prev, summaryTemplate: true}));
    } else if (name === 'name') {
      // 标记字段为已触摸
      setTouchedFields(prev => ({...prev, name: true}));
    }
    
    setFormData(prev => ({ ...prev, [fieldName]: value }));
    
    // 实时验证
    if (name === 'name') {
      const error = validateField(name, value);
      setFormErrors(prev => ({...prev, name: error}));
    } else if (name === 'llm_extraction_template') {
      const error = validateField('llmExtractionTemplate', value);
      setFormErrors(prev => ({...prev, llmExtractionTemplate: error}));
    } else if (name === 'vlm_extraction_template') {
      const error = validateField('vlmExtractionTemplate', value);
      setFormErrors(prev => ({...prev, vlmExtractionTemplate: error}));
    } else if (name === 'evaluation_template') {
      const error = validateField('evaluationTemplate', value);
      setFormErrors(prev => ({...prev, evaluationTemplate: error}));
    } else if (name === 'summary_template') {
      const error = validateField('summaryTemplate', value);
      setFormErrors(prev => ({...prev, summaryTemplate: error}));
    }
  };
  
  // 处理表单提交前验证
  const handleBeforeSubmit = (e: React.FormEvent) => {
    // 标记所有字段为已触摸
    setTouchedFields({
      name: true,
      llmExtractionTemplate: true,
      vlmExtractionTemplate: true,
      evaluationTemplate: true,
      summaryTemplate: true,
      groups: true
    });
    
    // 验证所有字段
    const errors = {
      name: validateField('name', formData.name),
      llmExtractionTemplate: validateField('llmExtractionTemplate', formData.llmExtractionTemplateId),
      vlmExtractionTemplate: validateField('vlmExtractionTemplate', formData.vlmExtractionTemplateId),
      evaluationTemplate: validateField('evaluationTemplate', formData.evaluationTemplateId),
      summaryTemplate: validateField('summaryTemplate', formData.summaryTemplateId),
      groups: validateField('groups', formData.selectedGroups)
    };
    
    setFormErrors(errors);
    
    // 如果有错误，阻止提交
    if (errors.name || errors.llmExtractionTemplate || errors.vlmExtractionTemplate || 
        errors.evaluationTemplate || errors.summaryTemplate || errors.groups) {
      e.preventDefault();
    }
  };
  
  return (
    <div className="document-type-new-page">
      {/* 页面头部 */}
      <div className="page-header">
        <h2 className="page-title">{isEditMode ? "编辑文档类型" : "新增文档类型"}</h2>
        <div>
          <Button 
            type="default" 
            icon="ri-arrow-left-line" 
            onClick={() => navigate("/document-types")} 
            className="mr-2"
          >
            返回
          </Button>
          <Button 
            type="primary" 
            icon="ri-save-line"
            form="type-form"
          >
            保存
          </Button>
        </div>
      </div>
      
      {/* 表单内容 */}
      <Card>
        <Form id="type-form" method="post" noValidate ref={formRef} onSubmit={handleBeforeSubmit}>
          {/* 如果是编辑模式，添加隐藏的ID字段 */}
          {formData.id && <input type="hidden" name="id" value={formData.id} />}
          
          <div className="grid grid-cols-1 gap-6">
            {/* 错误提示 */}
            {formErrors?.general && (
              <div className="error-message general-error">
                <i className="ri-error-warning-line"></i>
                {formErrors.general}
              </div>
            )}
            
            {/* 文档类型名称 */}
            <div className="form-group">
              <label htmlFor="type-name" className="form-label">
                文档类型名称 <span className="text-red-500">*</span>
              </label>
              <input 
                type="text" 
                id="type-name" 
                name="name" 
                className={`form-input ${touchedFields.name && formErrors?.name ? 'input-error' : ''}`}
                placeholder="请输入文档类型名称" 
                value={formData.name}
                onChange={handleInputChange}
                required 
              />
              {touchedFields.name && formErrors?.name && (
                <div className="error-message">{formErrors.name}</div>
              )}
              <div className="form-tip">例如：销售合同、采购合同、专卖许可证等</div>
            </div>
            
            {/* 类型描述 */}
            <div className="form-group">
              <label htmlFor="type-description" className="form-label">类型描述</label>
              <textarea 
                id="type-description" 
                name="description" 
                className="form-textarea" 
                placeholder="请输入类型描述，介绍此类型文档的用途和特点" 
                value={formData.description}
                onChange={handleInputChange}
                rows={3}
              ></textarea>
            </div>
            
            {/* 提示词模板选择区域 */}
            <div className="form-group flex space-x-4">
              {/* llm抽取提示词模板 */}
              <div className="w-full">
                <label htmlFor="llm-extraction-template" className="form-label">llm抽取提示词模板 <span className="text-red-500">*</span></label>
                <select 
                  id="llm-extraction-template" 
                  name="llm_extraction_template" 
                  className={`form-select ${touchedFields.llmExtractionTemplate && formErrors?.llmExtractionTemplate ? 'input-error' : ''}`}
                  value={formData.llmExtractionTemplateId}
                  onChange={handleInputChange}
                >
                  <option value="">请选择llm抽取提示词模板</option>
                  {llmExtractionTemplates.map((template: PromptTemplateUI) => (
                    <option key={template.id} value={template.id}>
                      {template.template_name}
                    </option>
                  ))}
                </select>
                {touchedFields.llmExtractionTemplate && formErrors?.llmExtractionTemplate && (
                  <div className="error-message">{formErrors.llmExtractionTemplate}</div>
                )}
                <div className="form-tip">选择用于从此类文档中抽取信息的llm提示词模板</div>
              </div>

              {/* vlm抽取提示词模板 */}
              <div className="w-full">
                <label htmlFor="vlm-extraction-template" className="form-label">vlm抽取提示词模板 <span className="text-red-500">*</span></label>
                <select 
                  id="vlm-extraction-template" 
                  name="vlm_extraction_template" 
                  className={`form-select ${touchedFields.vlmExtractionTemplate && formErrors?.vlmExtractionTemplate ? 'input-error' : ''}`}
                  value={formData.vlmExtractionTemplateId}
                  onChange={handleInputChange}
                >
                  <option value="">请选择vlm抽取提示词模板</option>
                  {vlmExtractionTemplates.map((template: PromptTemplateUI) => (
                    <option key={template.id} value={template.id}>
                      {template.template_name}
                    </option>
                  ))}
                </select>
                {touchedFields.vlmExtractionTemplate && formErrors?.vlmExtractionTemplate && (
                  <div className="error-message">{formErrors.vlmExtractionTemplate}</div>
                )}
                <div className="form-tip">选择用于从此类文档中抽取信息的vlm提示词模板</div>
              </div>
              
              {/* 评查提示词模板 */}
              <div className="w-full">
                <label htmlFor="evaluation-template" className="form-label">评查提示词模板 <span className="text-red-500">*</span></label>
                <select 
                  id="evaluation-template" 
                  name="evaluation_template" 
                  className={`form-select ${touchedFields.evaluationTemplate && formErrors?.evaluationTemplate ? 'input-error' : ''}`}
                  value={formData.evaluationTemplateId}
                  onChange={handleInputChange}
                >
                  <option value="">请选择评查提示词模板</option>
                  {evaluationTemplates.map((template: PromptTemplateUI) => (
                    <option key={template.id} value={template.id}>
                      {template.template_name}
                    </option>
                  ))}
                </select>
                {touchedFields.evaluationTemplate && formErrors?.evaluationTemplate && (
                  <div className="error-message">{formErrors.evaluationTemplate}</div>
                )}
                <div className="form-tip">选择用于评估此类文档内容的提示词模板</div>
              </div>
              
              {/* 总结提示词模板 */}
              <div className="w-full">
                <label htmlFor="summary-template" className="form-label">总结提示词模板 <span className="text-red-500">*</span></label>
                <select 
                  id="summary-template" 
                  name="summary_template" 
                  className={`form-select ${touchedFields.summaryTemplate && formErrors?.summaryTemplate ? 'input-error' : ''}`}
                  value={formData.summaryTemplateId}
                  onChange={handleInputChange}
                >
                  <option value="">请选择总结提示词模板</option>
                  {summaryTemplates.map((template: PromptTemplateUI) => (
                    <option key={template.id} value={template.id}>
                      {template.template_name}
                    </option>
                  ))}
                </select>
                {touchedFields.summaryTemplate && formErrors?.summaryTemplate && (
                  <div className="error-message">{formErrors.summaryTemplate}</div>
                )}
                <div className="form-tip">选择用于生成此类文档摘要的提示词模板</div>
              </div>
            </div>
            
            {/* 关联评查点分组 */}
            <div className="form-group">
              <fieldset>
                <legend className="form-label">
                  关联评查点分组 <span className="text-red-500">*</span>
                </legend>
                <div 
                  className={`checkbox-group ${touchedFields.groups && formErrors?.groups ? 'group-error' : ''}`}
                  aria-labelledby="checkpoint-groups-label"
                  role="group"
                >
                  {ruleGroups.map((group: RuleGroup) => (
                    <React.Fragment key={group.id}>
                      {/* 父分组 */}
                      <div 
                        className={`checkbox-item parent-checkbox-item ${formData.selectedGroups.includes(group.id) ? 'checked' : ''}`}
                      >
                        <button
                          type="button"
                          className="expand-icon"
                          onClick={(e) => handleGroupExpand(group.id, e)}
                          aria-label={`${expandedGroups[group.id] ? '收起' : '展开'}${group.name}分组`}
                        >
                          <i className={`ri-arrow-${expandedGroups[group.id] ? 'down' : 'right'}-s-line text-primary`}></i>
                        </button>
                        <input 
                          type="radio" 
                          id={`group-${group.id}`} 
                          name="checkpoint_group_ids" 
                          value={group.id}
                          checked={formData.selectedGroups.includes(group.id)}
                          onChange={(e) => handleGroupCheckChange(group.id, e.target.checked)}
                          className="radio-input" 
                        />
                        <label
                          htmlFor={`group-${group.id}`}
                          className="checkbox-label"
                        >
                          {group.name}
                          <span className="group-badge parent-badge">一级分组</span>
                        </label>
                      </div>
                      
                      {/* 子分组 */}
                      {group.children && group.children.length > 0 && expandedGroups[group.id] && (
                        group.children.map((child: RuleGroup) => (
                          <div 
                            key={child.id} 
                            className={`checkbox-item child-checkbox-item ${formData.selectedGroups.includes(child.id) ? 'checked' : ''}`}
                          >
                            <input 
                              type="radio" 
                              id={`group-${child.id}`} 
                              name="checkpoint_group_ids" 
                              value={child.id}
                              checked={formData.selectedGroups.includes(child.id)}
                              onChange={(e) => handleGroupCheckChange(child.id, e.target.checked)}
                              className="radio-input" 
                            />
                            <label
                              htmlFor={`group-${child.id}`}
                              className="checkbox-label"
                            >
                              {child.name}
                              <span className="group-badge child-badge">二级分组</span>
                            </label>
                          </div>
                        ))
                      )}
                    </React.Fragment>
                  ))}
                </div>
                {touchedFields.groups && formErrors?.groups && (
                  <div className="error-message">{formErrors.groups}</div>
                )}
                <div className="form-tip">选择与此文档类型关联的评查点分组，文档上传后将应用这些分组中的评查点进行审核</div>
              </fieldset>
            </div>
          </div>
        </Form>
      </Card>
    </div>
  );
}

