import { json, type MetaFunction } from "@remix-run/node";
import { useLoaderData, Link, useNavigate, useSearchParams } from "@remix-run/react";
import { useState } from "react";
import indexStyles from "~/styles/pages/rule-groups_index.css?url";
import { Card } from "~/components/ui/Card";
import { Button } from "~/components/ui/Button";
import { StatusDot } from "~/components/ui/StatusDot";
import { Table } from "~/components/ui/Table";
import { FilterPanel, FilterSelect, SearchFilter } from "~/components/ui/FilterPanel";
import { Pagination } from "~/components/ui/Pagination";

// 定义数据类型
interface RuleGroup {
  id: string;
  name: string;
  code: string;
  ruleCount: number;
  subGroupCount: number;
  status: 'active' | 'inactive';
  createdAt: string;
  children?: RuleGroup[];
}

export const handle = {
  breadcrumb: "评查点分组"
};

export const meta: MetaFunction = () => {
  return [
    { title: "评查点分组 - 中国烟草AI合同及卷宗审核系统" },
    { name: "description", content: "管理评查点分组，包括创建、编辑和删除分组" },
  ];
};

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

// 模拟数据
const MOCK_GROUPS: RuleGroup[] = [
  {
    id: "1",
    name: "合同基本要素检查",
    code: "contract-base",
    ruleCount: 18,
    subGroupCount: 12,
    status: "active",
    createdAt: "2023-10-01 14:30",
    children: [
      {
        id: "2",
        name: "必备要素检查",
        code: "essential-elements",
        ruleCount: 7,
        subGroupCount: 0,
        status: "active",
        createdAt: "2023-10-02 10:15",
      },
      {
        id: "3",
        name: "合同主体检查",
        code: "contract-parties",
        ruleCount: 5,
        subGroupCount: 0,
        status: "active",
        createdAt: "2023-10-03 16:20",
      }
    ]
  },
  {
    id: "4",
    name: "销售合同专项检查",
    code: "contract-sales",
    ruleCount: 12,
    subGroupCount: 5,
    status: "active",
    createdAt: "2023-10-05 09:30",
    children: [
      {
        id: "6",
        name: "付款条件检查",
        code: "payment-terms",
        ruleCount: 5,
        subGroupCount: 0,
        status: "active",
        createdAt: "2023-10-05 14:45",
      }
    ]
  },
  {
    id: "5",
    name: "行政处罚规范性检查",
    code: "punishment",
    ruleCount: 8,
    subGroupCount: 0,
    status: "inactive",
    createdAt: "2023-10-08 11:45",
  }
];

export async function loader() {
  return json({ groups: MOCK_GROUPS });
}

export default function RuleGroupsIndex() {
  const { groups } = useLoaderData<typeof loader>();
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [expandedGroups, setExpandedGroups] = useState<string[]>([]);
  
  // 处理展开/收起
  const toggleGroup = (groupId: string) => {
    setExpandedGroups(prev => 
      prev.includes(groupId) 
        ? prev.filter(id => id !== groupId)
        : [...prev, groupId]
    );
  };
  
  // 展开/收起全部
  const toggleAll = (expand: boolean) => {
    setExpandedGroups(expand ? groups.map(g => g.id) : []);
  };
  
  // 处理删除分组
  const handleDeleteGroup = (groupId: string) => {
    if (confirm("确定要删除该分组吗？此操作将同时删除该分组下的所有评查点，且不可恢复。")) {
      console.log('删除分组ID:', groupId);
      // 实际应用中，这里会调用API删除数据
    }
  };

  // 处理搜索名称
  const handleNameSearch = (value: string) => {
    const newParams = new URLSearchParams(searchParams);
    if (value) {
      newParams.set('name', value);
    } else {
      newParams.delete('name');
    }
    newParams.set('page', '1');
    setSearchParams(newParams);
  };

  // 处理搜索编码
  const handleCodeSearch = (value: string) => {
    const newParams = new URLSearchParams(searchParams);
    if (value) {
      newParams.set('code', value);
    } else {
      newParams.delete('code');
    }
    newParams.set('page', '1');
    setSearchParams(newParams);
  };

  // 处理状态筛选变更
  const handleStatusChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const { value } = e.target;
    const newParams = new URLSearchParams(searchParams);
    if (value) {
      newParams.set('status', value);
    } else {
      newParams.delete('status');
    }
    newParams.set('page', '1');
    setSearchParams(newParams);
  };

  // 处理重置筛选
  const handleReset = () => {
    setSearchParams(new URLSearchParams());
  };

  // 处理表格数据，包括父子级关系
  const processedData = groups.flatMap(group => {
    // 先添加父级分组
    const result: (RuleGroup & { isParent?: boolean, parentId?: string })[] = [
      { ...group, isParent: true }
    ];
    
    // 如果有子级分组并且当前已展开，则添加子级分组
    if (group.children && expandedGroups.includes(group.id)) {
      group.children.forEach(child => {
        result.push({ ...child, parentId: group.id });
      });
    }
    
    return result;
  });

  // 定义表格列配置
  const columns = [
    {
      title: "分组名称",
      key: "name",
      width: "400px",
      render: (_: unknown, record: (RuleGroup & { isParent?: boolean, parentId?: string })) => (
        <div className={`flex items-center ${!record.isParent ? 'ml-8' : ''}`}>
          {record.isParent && (
            <span 
              className="expand-icon" 
              onClick={() => toggleGroup(record.id)}
              role="button"
              tabIndex={0}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  toggleGroup(record.id);
                }
              }}
            >
              <i className={`ri-arrow-${expandedGroups.includes(record.id) ? 'down' : 'right'}-s-line`}></i>
            </span>
          )}
          <Link 
            to={`/rule-groups/${record.id}/rules`}
            className="group-name-link flex items-center ml-1 text-green-800"
          >
            <i className={`${record.isParent ? 'ri-folder-line' : 'ri-file-list-line'} mr-1 text-green-800`}></i> {record.name}
          </Link>
          <span className={`group-badge ${record.isParent ? 'parent-badge' : 'child-badge'}`}>
            {record.isParent ? '一级分组' : '二级分组'}
          </span>
        </div>
      )
    },
    {
      title: "分组编码",
      key: "code",
      render: (_: unknown, record: RuleGroup) => record.code
    },
    {
      title: "评查点数量",
      key: "ruleCount",
      render: (_: unknown, record: RuleGroup) => (
        <>
          <Link to={`/rule-groups/${record.id}/rules`} className="badge bg-primary text-white">
            {record.ruleCount}
          </Link>
          {record.subGroupCount > 0 && (
            <span className="text-secondary text-sm ml-1">
              | 子分组: {record.subGroupCount}
            </span>
          )}
        </>
      )
    },
    {
      title: "状态",
      key: "status",
      render: (_: unknown, record: RuleGroup) => (
        <StatusDot status={record.status === 'active' ? 'success' : 'error'} text={record.status === 'active' ? '启用' : '禁用'} />
      )
    },
    {
      title: "创建时间",
      key: "createdAt",
      render: (_: unknown, record: RuleGroup) => record.createdAt
    },
    {
      title: "操作",
      key: "operation",
      width: "180px",
      render: (_: unknown, record: RuleGroup) => (
        <>
          <button 
            className="ant-btn ant-btn-text ant-btn-sm text-primary"
            onClick={() => navigate(`/rule-groups/${record.id}`)}
          >
            <i className="ri-edit-line"></i> 编辑
          </button>
          <button 
            className="ant-btn ant-btn-text ant-btn-sm text-error"
            onClick={() => handleDeleteGroup(record.id)}
          >
            <i className="ri-delete-bin-line"></i> 删除
          </button>
        </>
      )
    }
  ];

  return (
    <div className="content-container rule-groups-page">
      {/* 页面头部 */}
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-medium">评查点分组管理</h2>
        <div className="flex">
          <Button
            type="default"
            icon="ri-arrow-down-s-line"
            onClick={() => toggleAll(true)}
            className="mr-2"
          >
            展开全部
          </Button>
          <Button
            type="default"
            icon="ri-arrow-up-s-line"
            onClick={() => toggleAll(false)}
            className="mr-2"
          >
            收起全部
          </Button>
          <Button
            type="primary"
            icon="ri-add-line"
            onClick={() => navigate("/rule-groups/new")}
          >
            新增分组
          </Button>
        </div>
      </div>
      
      {/* 搜索栏 - 使用FilterPanel */}
      <FilterPanel 
        className="mb-4" 
        actions={
          <>
            <Button type="default" icon="ri-refresh-line" onClick={handleReset} className="mr-2">
              重置
            </Button>
            <Button type="primary" icon="ri-search-line">
              搜索
            </Button>
          </>
        }
        noActionDivider={true}
      >
        <SearchFilter
          label="分组名称"
          placeholder="请输入分组名称"
          value={searchParams.get('name') || ''}
          onSearch={handleNameSearch}
          className="flex-1 min-w-[200px]"
          instantSearch={true}
        />
        
        <SearchFilter
          label="分组编码"
          placeholder="请输入分组编码"
          value={searchParams.get('code') || ''}
          onSearch={handleCodeSearch}
          className="flex-1 min-w-[200px]"
          instantSearch={true}
        />
        
        <FilterSelect
          label="状态"
          name="status"
          value={searchParams.get('status') || ''}
          options={[
            { value: "active", label: "启用" },
            { value: "inactive", label: "禁用" }
          ]}
          onChange={handleStatusChange}
          className="flex-1 min-w-[200px]"
        />
      </FilterPanel>
      
      {/* 数据表格 - 使用Table组件 */}
      <Card bodyClassName="px-4 py-4">
        <Table
          columns={columns}
          dataSource={processedData}
          rowKey="id"
          emptyText="暂无分组数据"
          className="tree-table"
        />
        
        {/* 分页 - 使用Pagination组件 */}
        <Pagination
          currentPage={1}
          total={groups.length}
          pageSize={10}
          onChange={() => {}}
          showTotal={true}
        />
      </Card>
    </div>
  );
}