import React, { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { disabilityClientManager } from '../api/disabilityClient';
import { Card, CardContent, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';

// 残疾人企业查询页面组件
// TODO: 未来可以添加公司选择器组件（CompanySelector）来替代文本输入，提供更好的用户体验
export const DisabilityPersonCompanyQuery: React.FC = () => {
  const queryClient = useQueryClient();

  // 获取 RPC 客户端实例
  const disabilityClient = disabilityClientManager.get();

  // 筛选条件状态
  const [filters, setFilters] = useState({
    gender: '',
    disabilityType: '',
    disabilityLevel: '',
    minAge: '',
    maxAge: '',
    city: '',
    district: '',
    disabilityId: '',
    companyId: '',
    companyName: '', // 公司名称筛选（前端筛选）
    page: 1,
    limit: 10
  });

  // 查询数据
  const { data, isLoading, error } = useQuery({
    queryKey: ['disability-person-company', filters],
    queryFn: async () => {
      const res = await disabilityClient.findPersonsWithCompany.$get({
        query: {
          gender: filters.gender || undefined,
          disabilityType: filters.disabilityType || undefined,
          disabilityLevel: filters.disabilityLevel || undefined,
          minAge: filters.minAge ? Number(filters.minAge) : undefined,
          maxAge: filters.maxAge ? Number(filters.maxAge) : undefined,
          city: filters.city || undefined,
          district: filters.district || undefined,
          disabilityId: filters.disabilityId || undefined,
          companyId: filters.companyId ? Number(filters.companyId) : undefined,
          skip: (filters.page - 1) * filters.limit,
          take: filters.limit
        }
      });
      if (res.status !== 200) throw new Error('获取残疾人企业关联数据失败');
      return await res.json();
    },
    initialData: {
      data: [],
      total: 0
    }
  });

  // 重置筛选条件
  const handleReset = () => {
    setFilters({
      gender: '',
      disabilityType: '',
      disabilityLevel: '',
      minAge: '',
      maxAge: '',
      city: '',
      district: '',
      disabilityId: '',
      companyId: '',
      companyName: '',
      page: 1,
      limit: 10
    });
  };

  // 查询按钮
  const handleSearch = () => {
    queryClient.invalidateQueries({ queryKey: ['disability-person-company'] });
  };

  // 前端筛选数据（公司名称筛选在前端进行）
  const filteredData = React.useMemo(() => {
    if (!data?.data) return [];
    if (!filters.companyName) return data.data;
    return data.data.filter((item: any) =>
      item.companyName?.toLowerCase().includes(filters.companyName.toLowerCase())
    );
  }, [data?.data, filters.companyName]);

  // 导出数据为 CSV（可选功能）
  const handleExport = () => {
    if (!filteredData.length) return;

    const headers = ['姓名', '残疾类别', '残疾等级', '公司', '残疾证号', '区', '市'];
    const rows = filteredData.map((item: any) => [
      item.name,
      item.disabilityType,
      item.disabilityLevel,
      item.companyName || '未关联',
      item.disabilityId,
      item.district || '-',
      item.city || '-'
    ]);

    const csvContent = [
      headers.join(','),
      ...rows.map(row => row.map(cell => `"${cell || ''}"`).join(','))
    ].join('\n');

    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `残疾人企业查询_${new Date().toLocaleDateString()}.csv`;
    link.click();
  };

  return (
    <div className="p-6 space-y-6" data-testid="disability-person-company-query">
      {/* 筛选条件卡片 */}
      <Card>
        <CardHeader>
          <CardTitle>残疾人企业查询</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* 性别筛选 */}
            <div className="space-y-2">
              <Label htmlFor="gender-filter">性别</Label>
              <Select
                value={filters.gender || 'all'}
                onValueChange={(value) => setFilters({ ...filters, gender: value === 'all' ? '' : value, page: 1 })}
              >
                <SelectTrigger id="gender-filter" data-testid="gender-filter" className="w-full">
                  <SelectValue placeholder="全部" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="男">男</SelectItem>
                  <SelectItem value="女">女</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 残疾类别筛选 */}
            <div className="space-y-2">
              <Label htmlFor="disability-type-filter">残疾类别</Label>
              <Select
                value={filters.disabilityType || 'all'}
                onValueChange={(value) => setFilters({ ...filters, disabilityType: value === 'all' ? '' : value, page: 1 })}
              >
                <SelectTrigger id="disability-type-filter" data-testid="disability-type-filter" className="w-full">
                  <SelectValue placeholder="全部" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="视力残疾">视力残疾</SelectItem>
                  <SelectItem value="听力残疾">听力残疾</SelectItem>
                  <SelectItem value="言语残疾">言语残疾</SelectItem>
                  <SelectItem value="肢体残疾">肢体残疾</SelectItem>
                  <SelectItem value="智力残疾">智力残疾</SelectItem>
                  <SelectItem value="精神残疾">精神残疾</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 残疾等级筛选 */}
            <div className="space-y-2">
              <Label htmlFor="disability-level-filter">残疾等级</Label>
              <Select
                value={filters.disabilityLevel || 'all'}
                onValueChange={(value) => setFilters({ ...filters, disabilityLevel: value === 'all' ? '' : value, page: 1 })}
              >
                <SelectTrigger id="disability-level-filter" data-testid="disability-level-filter" className="w-full">
                  <SelectValue placeholder="全部" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="一级">一级</SelectItem>
                  <SelectItem value="二级">二级</SelectItem>
                  <SelectItem value="三级">三级</SelectItem>
                  <SelectItem value="四级">四级</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 最小年龄筛选 */}
            <div className="space-y-2">
              <Label htmlFor="min-age-filter">最小年龄</Label>
              <Input
                id="min-age-filter"
                data-testid="min-age-filter"
                type="number"
                value={filters.minAge}
                onChange={(e) => setFilters({ ...filters, minAge: e.target.value, page: 1 })}
                placeholder="最小年龄"
              />
            </div>

            {/* 最大年龄筛选 */}
            <div className="space-y-2">
              <Label htmlFor="max-age-filter">最大年龄</Label>
              <Input
                id="max-age-filter"
                data-testid="max-age-filter"
                type="number"
                value={filters.maxAge}
                onChange={(e) => setFilters({ ...filters, maxAge: e.target.value, page: 1 })}
                placeholder="最大年龄"
              />
            </div>

            {/* 公司名称筛选 */}
            <div className="space-y-2">
              <Label htmlFor="company-name-filter">公司名称</Label>
              <Input
                id="company-name-filter"
                data-testid="company-name-filter"
                type="text"
                value={filters.companyName}
                onChange={(e) => setFilters({ ...filters, companyName: e.target.value, page: 1 })}
                placeholder="输入公司名称进行筛选"
              />
            </div>

            {/* 市筛选 */}
            <div className="space-y-2">
              <Label htmlFor="city-filter">市</Label>
              <Input
                id="city-filter"
                data-testid="city-filter"
                type="text"
                value={filters.city}
                onChange={(e) => setFilters({ ...filters, city: e.target.value, page: 1 })}
                placeholder="例如：广州市"
              />
            </div>

            {/* 区筛选 */}
            <div className="space-y-2">
              <Label htmlFor="district-filter">区</Label>
              <Input
                id="district-filter"
                data-testid="district-filter"
                type="text"
                value={filters.district}
                onChange={(e) => setFilters({ ...filters, district: e.target.value, page: 1 })}
                placeholder="例如：天河区"
              />
            </div>

            {/* 残疾证号筛选 */}
            <div className="space-y-2">
              <Label htmlFor="disability-id-filter">残疾证号</Label>
              <Input
                id="disability-id-filter"
                data-testid="disability-id-filter"
                type="text"
                value={filters.disabilityId}
                onChange={(e) => setFilters({ ...filters, disabilityId: e.target.value, page: 1 })}
                placeholder="输入完整的残疾证号"
              />
            </div>
          </div>

          {/* 操作按钮 */}
          <div className="flex gap-2 mt-4">
            <Button
              data-testid="reset-button"
              onClick={handleReset}
              variant="outline"
            >
              重置
            </Button>
            <Button
              data-testid="search-button"
              onClick={handleSearch}
            >
              查询
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 数据表格卡片 */}
      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="p-4 text-center" data-testid="loading-state">加载中...</div>
          ) : error ? (
            <div className="p-4 text-center text-destructive" data-testid="error-state">
              加载失败: {error instanceof Error ? error.message : '未知错误'}
            </div>
          ) : (
            <>
              {/* 表格头部操作栏 */}
              <div className="p-4 flex justify-between items-center border-b">
                <div className="text-sm text-muted-foreground">
                  共 {data.total} 条记录
                  {filters.companyName && `（筛选后 ${filteredData.length} 条）`}
                </div>
                <Button
                  data-testid="export-button"
                  variant="outline"
                  size="sm"
                  onClick={handleExport}
                  disabled={!filteredData.length}
                  title="导出当前筛选结果为CSV文件"
                >
                  导出数据
                </Button>
              </div>

              <Table data-testid="results-table">
                <TableHeader>
                  <TableRow>
                    <TableHead>姓名</TableHead>
                    <TableHead>残疾类别</TableHead>
                    <TableHead>残疾等级</TableHead>
                    <TableHead>公司</TableHead>
                    <TableHead>残疾证号</TableHead>
                    <TableHead>区</TableHead>
                    <TableHead>市</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredData.length === 0 ? (
                    <TableRow data-testid="no-data-row">
                      <TableCell colSpan={7} className="text-center text-muted-foreground">
                        {filters.companyName ? '没有符合条件的公司' : '暂无数据'}
                      </TableCell>
                    </TableRow>
                  ) : (
                    filteredData.map((item: any) => (
                      <TableRow key={`${item.personId}-${item.orderId}`}>
                        <TableCell>{item.name}</TableCell>
                        <TableCell>{item.disabilityType}</TableCell>
                        <TableCell>{item.disabilityLevel}</TableCell>
                        <TableCell>{item.companyName || '未关联'}</TableCell>
                        <TableCell>{item.disabilityId}</TableCell>
                        <TableCell>{item.district || '-'}</TableCell>
                        <TableCell>{item.city || '-'}</TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>

              {/* 分页 */}
              {data.total > 0 && (
                <div className="p-4">
                  <DataTablePagination
                    currentPage={filters.page}
                    pageSize={filters.limit}
                    totalCount={data.total}
                    onPageChange={(page, pageSize) => setFilters({ ...filters, page, limit: pageSize })}
                  />
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

    </div>
  );
};

export default DisabilityPersonCompanyQuery;
