import { useState, useEffect } from "react";
import { useSearchParams, useNavigate, useLoaderData } from "@remix-run/react";
import { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { Table } from "~/components/ui/Table";
import { Card } from "~/components/ui/Card";
import { Button } from "~/components/ui/Button";
import { Pagination } from "~/components/ui/Pagination";
import { FilterPanel, FilterSelect, SearchFilter } from "~/components/ui/FilterPanel";
import { getRuleTypes, getRuleGroupsByType, type RuleType, type RuleGroup } from "~/api/evaluation_points/rules";
import { toastService } from "~/components/ui/Toast";
import { 
  getDocumentTypes, 
  deleteDocumentType, 
  type DocumentTypeUI, 
  type DocumentTypeSearchParams,
  type DocumentTypeGroup
} from "~/api/document-types/document-types";
import documentTypesStyles from "~/styles/pages/document-types_index.css?url";


// 引入CSS样式
export function links() {
  return [
    { rel: "stylesheet", href: documentTypesStyles }
  ];
}

// 页面元数据
export const meta: MetaFunction = () => {
  return [
    { title: "文档类型管理 - 中国烟草AI合同及卷宗审核系统" },
    { name: "description", content: "管理文档类型，包括查看、编辑和删除文档类型" },
  ];
};

// 定义加载器返回的数据类型
interface LoaderData {
  types: DocumentTypeUI[];
  total: number;
  pageSize: number;
  currentPage: number;
  error?: string;
  groups: DocumentTypeGroup[];
  ruleTypes: RuleType[];
}

// 加载函数 - 获取文档类型列表
export async function loader({ request }: LoaderFunctionArgs) {
  try {
    const url = new URL(request.url);
    const name = url.searchParams.get('name') || undefined;
    const ruleType = url.searchParams.get('ruleType') || undefined;
    const groupId = url.searchParams.get('groupId') || undefined;
    const page = parseInt(url.searchParams.get('page') || '1', 10);
    const pageSize = parseInt(url.searchParams.get('pageSize') || '10', 10);
    
    // 构建搜索参数
    const searchParams: DocumentTypeSearchParams = {
      name,
      ruleType,
      groupId,
      page,
      pageSize
    };
    
    // 并行获取文档类型数据和父级评查点分组
    const ruleTypesResponse = await getRuleTypes();
    if(ruleTypesResponse.error){
      console.error("获取父级评查点分组失败:", ruleTypesResponse.error);
    }
    const ruleTypes = ruleTypesResponse.error ? [] : ruleTypesResponse.data;

    const typesResponse = await getDocumentTypes(searchParams);
    if(typesResponse.error){
      console.error("获取文档类型失败:", typesResponse.error);
      throw new Error(typesResponse.error);
    }
    const typesResult = typesResponse.data?.types || [];
    
    // console.log('文档类型数据:', typesResult.data?.types);
    // console.log('父级评查点分组:', groupsResult.data);
    
    return Response.json({
      types: typesResult,
      total: typesResponse.data?.total || typesResult.length,
      pageSize,
      currentPage: page,
      ruleTypes
    });
  } catch (error) {
    console.error("加载文档类型列表失败:", error);
    return Response.json(
      {
        error: error || "加载文档类型列表失败",
        status: 500
      }
    );
  }
}

// 动作函数 - 处理删除请求
export async function action({ request }: ActionFunctionArgs) {
  // 获取表单数据
  const formData = await request.formData();
  const id = formData.get("id") as string;
  const intent = formData.get("intent") as string;
  
  if (intent === "delete" && id) {
    try {
      const result = await deleteDocumentType(id);
      
      if (result.error) {
        return Response.json({ success: false, error: result.error }, { status: result.status || 500 });
      }
      
      return Response.json({ success: true });
    } catch (error) {
      return Response.json(
        { success: false, error: error instanceof Error ? error.message : "删除文档类型失败" },
        { status: 500 }
      );
    }
  }
  
  return Response.json({ success: false, error: "无效的操作" }, { status: 400 });
}

// 文档类型列表组件
export default function DocumentTypesList() {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [isDeleting, setIsDeleting] = useState(false);
  
  // 获取加载器数据
  const { types, total, error, ruleTypes } = useLoaderData<LoaderData>();
  
  // 状态管理
  const [ruleGroups, setRuleGroups] = useState<RuleGroup[]>([]);
  const [loadingGroups, setLoadingGroups] = useState(false);
  
  // 获取当前的ruleType值
  const ruleTypeParam = searchParams.get('ruleType');
  // 获取搜索参数
  const name = searchParams.get('name') || '';
  const currentPage = parseInt(searchParams.get('page') || String(1), 10);
  const pageSize = parseInt(searchParams.get('pageSize') || String(10), 10);
  
  // 判断是否禁用子级评查分组选择，true表示禁用，false表示不禁用
  const isRuleGroupSelectDisabled = loadingGroups || !ruleTypeParam || ruleGroups.length === 0;
  
  // 当评查点类型变化时，加载对应的子级评查分组
  useEffect(() => {
    // 如果选择了"全部"或未选择，则清空子级评查分组
    if (!ruleTypeParam || ruleTypeParam === 'all') {
      setRuleGroups([]);
      return;
    }
    
    // 加载当前类型的子级评查分组
    const loadRuleGroups = async () => {
      setLoadingGroups(true);
      try {
        const response = await getRuleGroupsByType(ruleTypeParam);
        if (response.data) {
          setRuleGroups(response.data);
        } else if (response.error) {
          console.error('加载子级规则组失败:', response.error);
          setRuleGroups([]);
        }
      } catch (error) {
        console.error('加载子级规则组出错:', error);
        toastService.error('加载子级规则组出错:' + error);
        setRuleGroups([]);
      } finally {
        setLoadingGroups(false);
      }
    };
    
    loadRuleGroups();
  }, [ruleTypeParam]);
  
  // 处理loader加载数据的时候的错误
  useEffect(() => {
    if(error){
      toastService.error(error);
    }
  }, [error]);
  
  
  // 处理名称搜索
  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 handleFilterChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const { name, value } = e.target;
    const newParams = new URLSearchParams(searchParams);
    
    // 如果是子级评查分组选择，但是当前应该被禁用，则不处理
    if (name === 'groupId' && isRuleGroupSelectDisabled) {
      return;
    }
    
    if (value) {
      newParams.set(name, value);
      
      // 如果是评查点类型变更，清空子级评查分组选择
      if (name === 'ruleType') {
        newParams.delete('groupId');
        // 如果选择了"全部"或空值，也清空子级评查分组选择
        if (value === '' || value === 'all') {
          setRuleGroups([]);
        }
      }
    } else {
      newParams.delete(name);
      
      // 如果清除评查点类型，也清除规则组
      if (name === 'ruleType') {
        newParams.delete('groupId');
        setRuleGroups([]);
      }
    }
    
    // 切换筛选条件时，重置到第一页
    newParams.set('page', '1');
    
    setSearchParams(newParams);
  };
  
  // 处理重置筛选
  const handleReset = () => {
    const nameInput = document.querySelector('input[placeholder="请输入文档类型名称"]');
    if (nameInput) {
      (nameInput as HTMLInputElement).value = '';
    }
    
    // 重置所有筛选条件
    setSearchParams(new URLSearchParams());
  };
  
  // 处理删除文档类型
  const handleDelete = async (id: number) => {
    if (confirm('确定要删除该文档类型吗？此操作不会影响关联的评查点分组，但可能会影响使用该类型的文档评查。')) {
      setIsDeleting(true);
      
      try {
        const formData = new FormData();
        formData.append('id', id.toString());
        formData.append('intent', 'delete');
        
        const response = await fetch('/document-types?index', {
          method: 'POST',
          body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
          alert('删除成功！');
          // 刷新页面
          window.location.reload();
        } else {
          alert(`删除失败: ${result.error || '未知错误'}`);
        }
      } catch (error) {
        alert(`删除失败: ${error instanceof Error ? error.message : '未知错误'}`);
      } finally {
        setIsDeleting(false);
      }
    }
  };
  
  // 处理编辑文档类型
  const handleEdit = (id: number) => {
    navigate(`/document-types/new?id=${id}`);
  };
  
  // 处理分页变更
  const handlePageChange = (page: number) => {
    const newParams = new URLSearchParams(searchParams);
    newParams.set('page', page.toString());
    setSearchParams(newParams);
  };
  
  // 处理每页条数变更
  const handlePageSizeChange = (size: number) => {
    const newParams = new URLSearchParams(searchParams);
    newParams.set('pageSize', size.toString());
    newParams.set('page', '1');
    setSearchParams(newParams);
  };
  
  // 定义表格列配置
  const columns = [
    {
      title: "文档类型名称",
      key: "name",
      width: "200px",
      render: (_: unknown, record: DocumentTypeUI) => (
        <div className="flex items-center">
          <i className="ri-file-text-line text-primary mr-2"></i>
          <span>{record.name}</span>
        </div>
      )
    },
    {
      title: "描述",
      key: "description",
      width: "300px",
      render: (_: unknown, record: DocumentTypeUI) => (
        <div className="text-secondary text-sm truncate max-w-xs" title={record.description}>
          {record.description}
        </div>
      )
    },
    {
      title: "关联的评查点分组",
      key: "groups",
      render: (_: unknown, record: DocumentTypeUI) => (
        <div className="groups-container">
          {record.groups && record.groups.length > 0 ? (
            record.groups.map(group => (
              <span key={group.id} className="type-badge">
                {group.name}
              </span>
            ))
          ) : (
            <span className="text-gray-400">暂无关联分组</span>
          )}
        </div>
      )
    },
    {
      title: "创建时间",
      key: "created_at",
      width: "150px",
      render: (_: unknown, record: DocumentTypeUI) => record.created_at
    },
    {
      title: "更新时间",
      key: "updated_at",
      width: "150px",
      render: (_: unknown, record: DocumentTypeUI) => record.updated_at
    },
    {
      title: "操作",
      key: "operation",
      width: "150px",
      render: (_: unknown, record: DocumentTypeUI) => (
        <>
          <button
            className="operation-btn text-primary"
            onClick={() => handleEdit(record.id)}
          >
            <i className="ri-edit-line"></i> 编辑
          </button>
          <button
            className="operation-btn text-error !hidden"
            onClick={() => handleDelete(record.id)}
            disabled={isDeleting}
          >
            <i className="ri-delete-bin-line"></i> 删除
          </button>
        </>
      )
    }
  ];
  
  return (
    <div className="document-types-page">
      {error && (
        <div className="alert alert-error mb-4">
          <p>{error}</p>
        </div>
      )}
      
      {/* 页面头部 */}
      <div className="page-header">
        <h2 className="page-title">文档类型管理</h2>
        <div>
          <Button 
            type="primary" 
            icon="ri-add-line" 
            onClick={() => navigate("/document-types/new")}
          >
            新增文档类型
          </Button>
        </div>
      </div>
      
      {/* 搜索栏 */}
      <FilterPanel
        className="mb-4"
        actions={
          <>
            <Button
              type="default"
              icon="ri-refresh-line"
              onClick={handleReset}
              className="mr-2"
            >
              重置
            </Button>
          </>
        }
        noActionDivider={true}
      >
        <FilterSelect
          label="父级评查分组"
          name="ruleType"
          value={searchParams.get('ruleType') || ''}
          options={[
            ...(ruleTypes || []).map(type => ({ 
              value: type.id, 
              label: type.name 
            }))
          ]}
          onChange={handleFilterChange}
          className="mr-3 w-[20%]"
        />
        
        <FilterSelect
          label="所属子级评查分组"
          name="groupId"
          value={searchParams.get('groupId') || ''}
          options={[
            ...(isRuleGroupSelectDisabled ? [{ value: "", label: "请先选择评查点类型" }] : []),
            ...ruleGroups.map(group => ({ 
              value: group.id, 
              label: group.name 
            }))
          ]}
          onChange={handleFilterChange}
          className={`mr-3 w-[20%] ${isRuleGroupSelectDisabled ? 'opacity-50' : ''}`}
        />

        <SearchFilter
          label="类型名称"
          placeholder="请输入文档类型名称"
          value={name}
          onSearch={handleNameSearch}
          className="flex-1 min-w-[200px]"
          instantSearch={true}
        />

      </FilterPanel>
      
      {/* 数据表格 */}
      <Card bodyClassName="px-0 py-0">
        <Table
          columns={columns}
          dataSource={types}
          rowKey="id"
          emptyText="暂无文档类型数据"
          loading={false}
        />
        
        {/* 分页 */}
        <div className="px-4 py-3">
          <Pagination
            currentPage={currentPage}
            total={total}
            pageSize={pageSize}
            onChange={handlePageChange}
            onPageSizeChange={handlePageSizeChange}
            showTotal={true}
            showPageSizeChanger={true}
            pageSizeOptions={[10, 20, 50, 100]}
          />
        </div>
      </Card>
    </div>
  );
}

