import React, { useState, useMemo, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Plus, Search, Edit, Trash2, Filter, X, Settings } from 'lucide-react';
import { tenantClientManager, tenantClient } from '../api/tenantClient';
import type { InferRequestType, InferResponseType } from 'hono/client';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { Badge } from '@d8d/shared-ui-components/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Popover, PopoverContent, PopoverTrigger } from '@d8d/shared-ui-components/components/ui/popover';
import { Calendar } from '@d8d/shared-ui-components/components/ui/calendar';
import { DataTablePagination } from './DataTablePagination';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { CreateTenantDto, UpdateTenantDto } from '@d8d/tenant-module-mt/schemas';
import { cn } from '../utils/cn';
import { formatTenantStatus } from '../utils/formatTenantStatus';
import { useNavigate } from 'react-router-dom';

// 使用RPC方式提取类型
type CreateTenantRequest = InferRequestType<typeof tenantClient.index.$post>['json'];
type UpdateTenantRequest = InferRequestType<typeof tenantClient[':id']['$put']>['json'];
type TenantResponse = InferResponseType<typeof tenantClient.index.$get, 200>['data'][0];

// 直接使用后端定义的 schema
const createTenantFormSchema = CreateTenantDto;
const updateTenantFormSchema = UpdateTenantDto;

type CreateTenantFormData = CreateTenantRequest;
type UpdateTenantFormData = UpdateTenantRequest;

export const TenantsPage = () => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    keyword: ''
  });
  const [filters, setFilters] = useState({
    status: undefined as number | undefined,
    createdAt: undefined as { gte?: string; lte?: string } | undefined
  });
  const [showFilters, setShowFilters] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingTenant, setEditingTenant] = useState<TenantResponse | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [tenantToDelete, setTenantToDelete] = useState<number | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);

  const createForm = useForm<CreateTenantFormData>({
    resolver: zodResolver(createTenantFormSchema),
    defaultValues: {
      name: '',
      code: '',
      phone: null,
      contactName: null,
      status: 1,
      config: null,
      rsaPublicKey: null,
      aesKey: null,
    },
  });

  const updateForm = useForm<UpdateTenantFormData>({
    resolver: zodResolver(updateTenantFormSchema),
    defaultValues: {
      name: undefined,
      code: undefined,
      phone: null,
      contactName: null,
      status: undefined,
      config: null,
      rsaPublicKey: null,
      aesKey: null,
    },
  });

  const { data: tenantsData, isLoading, refetch } = useQuery({
    queryKey: ['tenants', searchParams, filters],
    queryFn: async () => {
      const filterParams: Record<string, unknown> = {};

      if (filters.status !== undefined) {
        filterParams.status = filters.status;
      }

      if (filters.createdAt) {
        filterParams.createdAt = filters.createdAt;
      }

      const res = await tenantClientManager.get().index.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.keyword,
          filters: Object.keys(filterParams).length > 0 ? JSON.stringify(filterParams) : undefined
        }
      });
      if (res.status !== 200) {
        throw new Error('获取租户列表失败');
      }
      return await res.json();
    }
  });

  const tenants = tenantsData?.data || [];
  const totalCount = tenantsData?.pagination?.total || 0;

  // 防抖搜索函数
  const debounce = <T extends (...args: unknown[]) => void>(func: T, delay: number) => {
    let timeoutId: NodeJS.Timeout;
    return (...args: Parameters<T>) => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func(...args), delay);
    };
  };

  // 使用useCallback包装防抖搜索
  const debouncedSearch = useCallback(
    debounce((keyword: string) => {
      setSearchParams(prev => ({ ...prev, keyword, page: 1 }));
    }, 300),
    []
  );

  // 处理搜索输入变化
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const keyword = e.target.value;
    setSearchParams(prev => ({ ...prev, keyword }));
    debouncedSearch(keyword);
  };

  // 处理搜索表单提交
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 处理分页
  const handlePageChange = (page: number, limit: number) => {
    setSearchParams(prev => ({ ...prev, page, limit }));
  };

  // 处理过滤条件变化
  const handleFilterChange = (newFilters: Partial<typeof filters>) => {
    setFilters(prev => ({ ...prev, ...newFilters }));
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 重置所有过滤条件
  const resetFilters = () => {
    setFilters({
      status: undefined,
      createdAt: undefined
    });
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 检查是否有活跃的过滤条件
  const hasActiveFilters = useMemo(() => {
    return filters.status !== undefined ||
           filters.createdAt !== undefined;
  }, [filters]);

  // 打开创建租户对话框
  const handleCreateTenant = () => {
    setEditingTenant(null);
    setIsCreateForm(true);
    createForm.reset({
      name: '',
      code: '',
      phone: null,
      contactName: null,
      status: 1,
      config: null,
      rsaPublicKey: null,
      aesKey: null,
    });
    setIsModalOpen(true);
  };

  // 打开编辑租户对话框
  const handleEditTenant = (tenant: TenantResponse) => {
    setEditingTenant(tenant);
    setIsCreateForm(false);
    updateForm.reset({
      name: tenant.name,
      code: tenant.code,
      phone: tenant.phone,
      contactName: tenant.contactName,
      status: tenant.status,
      config: tenant.config,
      rsaPublicKey: tenant.rsaPublicKey,
      aesKey: tenant.aesKey,
    });
    setIsModalOpen(true);
  };

  // 跳转到租户配置页面
  const handleConfigTenant = (tenantId: number) => {
    navigate(`/tenant/config/${tenantId}`);
  };

  // 处理创建表单提交
  const handleCreateSubmit = async (data: CreateTenantFormData) => {
    try {
      const res = await tenantClientManager.get().index.$post({
        json: data
      });
      if (res.status !== 201) {
        throw new Error('创建租户失败');
      }
      toast.success('租户创建成功');
      setIsModalOpen(false);
      refetch();
    } catch {
      toast.error('创建失败，请重试');
    }
  };

  // 处理更新表单提交
  const handleUpdateSubmit = async (data: UpdateTenantFormData) => {
    if (!editingTenant) return;

    try {
      const res = await tenantClient[':id']['$put']({
        param: { id: editingTenant.id },
        json: data
      });
      if (res.status !== 200) {
        throw new Error('更新租户失败');
      }
      toast.success('租户更新成功');
      setIsModalOpen(false);
      refetch();
    } catch {
      toast.error('更新失败，请重试');
    }
  };

  // 处理删除租户
  const handleDeleteTenant = (id: number) => {
    setTenantToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!tenantToDelete) return;

    try {
      const res = await tenantClient[':id']['$delete']({
        param: { id: tenantToDelete }
      });
      if (res.status !== 204) {
        throw new Error('删除租户失败');
      }
      toast.success('租户删除成功');
      refetch();
    } catch {
      toast.error('删除失败，请重试');
    } finally {
      setDeleteDialogOpen(false);
      setTenantToDelete(null);
    }
  };

  // 渲染表格部分的骨架屏
  const renderTableSkeleton = () => (
    <div className="space-y-2">
      {Array.from({ length: 5 }).map((_, index) => (
        <div key={index} className="flex space-x-4">
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 w-16" />
        </div>
      ))}
    </div>
  );

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">租户管理</h1>
        <Button onClick={handleCreateTenant}>
          <Plus className="mr-2 h-4 w-4" />
          创建租户
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>租户列表</CardTitle>
          <CardDescription>
            管理系统中的所有租户，共 {totalCount} 个租户
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-4 space-y-4">
            <form onSubmit={handleSearch} className="flex gap-2">
              <div className="relative flex-1 max-w-sm">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索租户名称、代码或联系人..."
                  value={searchParams.keyword}
                  onChange={handleSearchChange}
                  className="pl-8"
                />
              </div>
              <Button type="submit" variant="outline">
                搜索
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={() => setShowFilters(!showFilters)}
                className="flex items-center gap-2"
              >
                <Filter className="h-4 w-4" />
                高级筛选
                {hasActiveFilters && (
                  <Badge variant="secondary" className="ml-1">
                    {Object.values(filters).filter(v =>
                      v !== undefined &&
                      (!Array.isArray(v) || v.length > 0)
                    ).length}
                  </Badge>
                )}
              </Button>
              {hasActiveFilters && (
                <Button
                  type="button"
                  variant="ghost"
                  onClick={resetFilters}
                  className="flex items-center gap-2"
                >
                  <X className="h-4 w-4" />
                  重置
                </Button>
              )}
            </form>

            {showFilters && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 border rounded-lg bg-muted/50">
                {/* 状态筛选 */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">租户状态</label>
                  <Select
                    value={filters.status === undefined ? 'all' : filters.status.toString()}
                    onValueChange={(value) =>
                      handleFilterChange({
                        status: value === 'all' ? undefined : parseInt(value)
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">全部状态</SelectItem>
                      <SelectItem value="1">启用</SelectItem>
                      <SelectItem value="2">禁用</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 创建时间筛选 */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">创建时间</label>
                  <Popover>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        className={cn(
                          "w-full justify-start text-left font-normal",
                          !filters.createdAt && "text-muted-foreground"
                        )}
                      >
                        {filters.createdAt ?
                          `${filters.createdAt.gte || ''} 至 ${filters.createdAt.lte || ''}` :
                          '选择日期范围'
                        }
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-auto p-0" align="start">
                      <Calendar
                        mode="range"
                        selected={{
                          from: filters.createdAt?.gte ? new Date(filters.createdAt.gte) : undefined,
                          to: filters.createdAt?.lte ? new Date(filters.createdAt.lte) : undefined
                        }}
                        onSelect={(range) => {
                          handleFilterChange({
                            createdAt: range?.from && range?.to ? {
                              gte: format(range.from, 'yyyy-MM-dd'),
                              lte: format(range.to, 'yyyy-MM-dd')
                            } : undefined
                          });
                        }}
                        initialFocus
                      />
                    </PopoverContent>
                  </Popover>
                </div>
              </div>
            )}

            {/* 过滤条件标签 */}
            {hasActiveFilters && (
              <div className="flex flex-wrap gap-2">
                {filters.status !== undefined && (
                  <Badge variant="secondary" className="flex items-center gap-1">
                    状态: {filters.status === 1 ? '启用' : '禁用'}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => handleFilterChange({ status: undefined })}
                    />
                  </Badge>
                )}
                {filters.createdAt && (
                  <Badge variant="secondary" className="flex items-center gap-1">
                    创建时间: {filters.createdAt.gte || ''} 至 {filters.createdAt.lte || ''}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => handleFilterChange({ createdAt: undefined })}
                    />
                  </Badge>
                )}
              </div>
            )}
          </div>

          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>租户名称</TableHead>
                  <TableHead>租户代码</TableHead>
                  <TableHead>联系人</TableHead>
                  <TableHead>联系电话</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  // 显示表格骨架屏
                  <TableRow>
                    <TableCell colSpan={7} className="p-4">
                      {renderTableSkeleton()}
                    </TableCell>
                  </TableRow>
                ) : (
                  // 显示实际租户数据
                  tenants.map((tenant) => {
                    const statusInfo = formatTenantStatus(tenant.status);
                    return (
                      <TableRow key={tenant.id}>
                        <TableCell className="font-medium">{tenant.name || '-'}</TableCell>
                        <TableCell>{tenant.code}</TableCell>
                        <TableCell>{tenant.contactName || '-'}</TableCell>
                        <TableCell>{tenant.phone || '-'}</TableCell>
                        <TableCell>
                          <Badge variant={statusInfo.variant}>
                            {statusInfo.label}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          {format(new Date(tenant.createdAt), 'yyyy-MM-dd HH:mm')}
                        </TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleConfigTenant(tenant.id)}
                              title="配置"
                            >
                              <Settings className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleEditTenant(tenant)}
                              title="编辑"
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleDeleteTenant(tenant.id)}
                              title="删除"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    );
                  })
                )}
              </TableBody>
            </Table>
          </div>

          <DataTablePagination
            currentPage={searchParams.page}
            totalCount={totalCount}
            pageSize={searchParams.limit}
            onPageChange={handlePageChange}
          />
        </CardContent>
      </Card>

      {/* 创建/编辑租户对话框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingTenant ? '编辑租户' : '创建租户'}
            </DialogTitle>
            <DialogDescription>
              {editingTenant ? '编辑现有租户信息' : '创建一个新的租户'}
            </DialogDescription>
          </DialogHeader>

          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>租户名称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入租户名称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        租户代码
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入租户代码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="contactName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人姓名</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系人姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系电话</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系电话" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">租户状态</FormLabel>
                        <FormDescription>
                          禁用后租户将无法使用系统
                        </FormDescription>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value === 1}
                          onCheckedChange={(checked) => field.onChange(checked ? 1 : 2)}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit">
                    创建租户
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>租户名称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入租户名称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        租户代码
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入租户代码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="contactName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人姓名</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系人姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="phone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系电话</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系电话" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
                      <div className="space-y-0.5">
                        <FormLabel className="text-base">租户状态</FormLabel>
                        <FormDescription>
                          禁用后租户将无法使用系统
                        </FormDescription>
                      </div>
                      <FormControl>
                        <Switch
                          checked={field.value === 1}
                          onCheckedChange={(checked) => field.onChange(checked ? 1 : 2)}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit">
                    更新租户
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          )}
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这个租户吗？此操作无法撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={confirmDelete}>
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};