import { json, redirect, type ActionFunctionArgs, type LoaderFunctionArgs, type MetaFunction } from "@remix-run/node";
import { Form, useLoaderData, useNavigation, useActionData } from "@remix-run/react";
import { useState, useEffect } from "react";

export const meta: MetaFunction = ({ data }) => {
  return [
    { title: `编辑评查点分组 - ${data?.group?.name || '加载中'} - 中国烟草AI合同及卷宗审核系统` },
    { name: "description", content: "编辑评查点分组信息，包括名称、编码、描述和状态" },
  ];
};

// 模拟数据
const MOCK_GROUPS = [
  {
    id: "1",
    name: "合同条款类",
    code: "CONTRACT",
    description: "关于合同条款的评查点分组",
    status: "active",
    sortOrder: 1,
    createdAt: "2024-01-01T00:00:00Z",
    updatedAt: "2024-01-01T00:00:00Z",
  },
  {
    id: "2",
    name: "合规性类",
    code: "COMPLIANCE",
    description: "关于合规性的评查点分组",
    status: "active",
    sortOrder: 2,
    createdAt: "2024-01-01T00:00:00Z",
    updatedAt: "2024-01-01T00:00:00Z",
  },
  {
    id: "3",
    name: "风险提示类",
    code: "RISK",
    description: "关于风险提示的评查点分组",
    status: "inactive",
    sortOrder: 3,
    createdAt: "2024-01-01T00:00:00Z",
    updatedAt: "2024-01-01T00:00:00Z",
  },
];

export async function loader({ params }: LoaderFunctionArgs) {
  const { groupId } = params;
  
  // 真实环境中，这里会调用API获取数据
  // const response = await fetch(`${process.env.API_URL}/api/rule-groups/${groupId}`);
  // if (response.status === 404) {
  //   throw new Response("评查点分组不存在", { status: 404 });
  // }
  // if (!response.ok) {
  //   throw new Response("获取评查点分组失败", { status: response.status });
  // }
  // const group = await response.json();
  
  // 使用模拟数据
  const group = MOCK_GROUPS.find(g => g.id === groupId);
  if (!group) {
    throw new Response("评查点分组不存在", { status: 404 });
  }
  
  return json({ group });
}

export async function action({ request, params }: ActionFunctionArgs) {
  const formData = await request.formData();
  const groupId = params.groupId;
  
  const name = formData.get("name");
  const code = formData.get("code");
  const description = formData.get("description");
  const status = formData.get("status");
  const sortOrder = formData.get("sortOrder");
  
  // 基本验证
  const errors = {};
  if (!name) errors.name = "分组名称不能为空";
  if (!code) errors.code = "分组编码不能为空";
  if (Object.keys(errors).length > 0) {
    return json({ errors, values: Object.fromEntries(formData) });
  }
  
  // 构建更新数据
  const updateData = {
    name,
    code,
    description,
    status,
    sortOrder: Number(sortOrder) || 0,
  };
  
  // 真实环境中，这里会调用API更新数据
  // const response = await fetch(`${process.env.API_URL}/api/rule-groups/${groupId}`, {
  //   method: "PUT",
  //   headers: { "Content-Type": "application/json" },
  //   body: JSON.stringify(updateData),
  // });
  // 
  // if (!response.ok) {
  //   throw new Response("更新评查点分组失败", { status: response.status });
  // }
  
  // 模拟更新成功
  console.log('保存分组数据:', { id: groupId, ...updateData });
  
  // 重定向回列表页
  return redirect('/rule-groups');
}

export default function EditRuleGroup() {
  const { group } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  
  const isSubmitting = navigation.state === "submitting";
  
  const [formData, setFormData] = useState({
    name: group.name,
    code: group.code,
    description: group.description || "",
    status: group.status,
    sortOrder: group.sortOrder.toString(),
  });
  
  // 当actionData中有错误时，保留用户输入的值
  useEffect(() => {
    if (actionData?.values) {
      setFormData({
        name: actionData.values.name,
        code: actionData.values.code,
        description: actionData.values.description || "",
        status: actionData.values.status,
        sortOrder: actionData.values.sortOrder,
      });
    }
  }, [actionData]);
  
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };
  
  return (
    <div className="edit-rule-group">
      <div className="mb-6">
        <h1 className="text-2xl font-medium">编辑评查点分组</h1>
      </div>
      
      <div className="card">
        <Form method="post" className="space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="form-group">
              <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">
                分组名称 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                id="name"
                name="name"
                value={formData.name}
                onChange={handleChange}
                className={`w-full h-10 px-3 border ${actionData?.errors?.name ? 'border-red-500' : 'border-gray-300'} rounded-md focus:border-primary focus:ring-1 focus:ring-primary`}
                placeholder="请输入分组名称"
              />
              {actionData?.errors?.name && (
                <p className="mt-1 text-sm text-red-500">{actionData.errors.name}</p>
              )}
            </div>
            
            <div className="form-group">
              <label htmlFor="code" className="block text-sm font-medium text-gray-700 mb-1">
                分组编码 <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                id="code"
                name="code"
                value={formData.code}
                onChange={handleChange}
                className={`w-full h-10 px-3 border ${actionData?.errors?.code ? 'border-red-500' : 'border-gray-300'} rounded-md focus:border-primary focus:ring-1 focus:ring-primary`}
                placeholder="请输入分组编码"
              />
              {actionData?.errors?.code && (
                <p className="mt-1 text-sm text-red-500">{actionData.errors.code}</p>
              )}
            </div>
          </div>
          
          <div className="form-group">
            <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">
              分组描述
            </label>
            <textarea
              id="description"
              name="description"
              value={formData.description}
              onChange={handleChange}
              rows={3}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:border-primary focus:ring-1 focus:ring-primary"
              placeholder="请输入分组描述"
            ></textarea>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="form-group">
              <label htmlFor="status" className="block text-sm font-medium text-gray-700 mb-1">
                状态
              </label>
              <select
                id="status"
                name="status"
                value={formData.status}
                onChange={handleChange}
                className="w-full h-10 px-3 border border-gray-300 rounded-md focus:border-primary focus:ring-1 focus:ring-primary"
              >
                <option value="active">启用</option>
                <option value="inactive">禁用</option>
              </select>
            </div>
            
            <div className="form-group">
              <label htmlFor="sortOrder" className="block text-sm font-medium text-gray-700 mb-1">
                排序
              </label>
              <input
                type="number"
                id="sortOrder"
                name="sortOrder"
                value={formData.sortOrder}
                onChange={handleChange}
                className="w-full h-10 px-3 border border-gray-300 rounded-md focus:border-primary focus:ring-1 focus:ring-primary"
                placeholder="请输入排序值"
                min="0"
              />
            </div>
          </div>
          
          <div className="flex justify-end space-x-3 pt-4 border-t border-gray-100">
            <a 
              href="/rule-groups"
              className="ant-btn ant-btn-default"
              onClick={(e) => {
                e.preventDefault();
                window.history.back();
              }}
            >
              取消
            </a>
            <button 
              type="submit"
              className="ant-btn ant-btn-primary"
              disabled={isSubmitting}
            >
              {isSubmitting ? '保存中...' : '保存'}
            </button>
          </div>
        </Form>
      </div>
    </div>
  );
}