// app/routes/rule-groups.new.tsx
import { json, redirect, type ActionFunctionArgs, type MetaFunction } from "@remix-run/node";
import { Form, useNavigation, useActionData } from "@remix-run/react";
import { useState, useEffect } from "react";

export const meta: MetaFunction = () => {
  return [
    { title: "新建评查点分组 - 中国烟草AI合同及卷宗审核系统" },
    { name: "description", content: "创建新的评查点分组，包括分组名称、编码、描述和状态" },
  ];
};

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

export default function NewRuleGroup() {
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();
  
  const isSubmitting = navigation.state === "submitting";
  
  const [formData, setFormData] = useState({
    name: "",
    code: "",
    description: "",
    status: "active",
    sortOrder: "0",
  });
  
  // 当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="new-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>
  );
}