import React, { useState } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Search } from 'lucide-react';
import { format } from 'date-fns';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
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 { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
import { platformClientManager } from '../api/platformClient';
import { CreatePlatformSchema, UpdatePlatformSchema } from '@d8d/allin-platform-module/schemas';
import type { CreatePlatformRequest, UpdatePlatformRequest } from '../api/types';

interface PlatformSearchParams {
  page: number;
  limit: number;
  search: string;
}

import type { PlatformResponse } from '../api/types';

const PlatformManagement: React.FC = () => {
  const [searchParams, setSearchParams] = useState<PlatformSearchParams>({ page: 1, limit: 10, search: '' });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [platformToDelete, setPlatformToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm<CreatePlatformRequest>({
    resolver: zodResolver(CreatePlatformSchema),
    defaultValues: {
      platformName: '',
      contactPerson: '',
      contactPhone: '',
      contactEmail: undefined
    }
  });

  const updateForm = useForm<UpdatePlatformRequest>({
    resolver: zodResolver(UpdatePlatformSchema),
    defaultValues: {}
  });

  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['platforms', searchParams],
    queryFn: async () => {
      const res = await platformClientManager.get().getAllPlatforms.$get({
        query: {
          skip: (searchParams.page - 1) * searchParams.limit,
          take: searchParams.limit
        }
      });
      if (res.status !== 200) throw new Error('获取平台列表失败');
      return await res.json();
    },
    initialData: {
      data: [],
      total: 0
    }
  });

  // 创建平台
  const createMutation = useMutation({
    mutationFn: async (data: CreatePlatformRequest) => {
      const res = await platformClientManager.get().createPlatform.$post({ json: data });
      if (res.status !== 200) throw new Error('创建平台失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('平台创建成功');
      setIsModalOpen(false);
      createForm.reset();
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '创建平台失败');
    }
  });

  // 更新平台
  const updateMutation = useMutation({
    mutationFn: async (data: UpdatePlatformRequest) => {
      const res = await platformClientManager.get().updatePlatform.$post({
        json: data
      });
      if (res.status !== 200) throw new Error('更新平台失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('平台更新成功');
      setIsModalOpen(false);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '更新平台失败');
    }
  });

  // 删除平台
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await platformClientManager.get().deletePlatform.$post({
        json: { id }
      });
      if (res.status !== 200) throw new Error('删除平台失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('平台删除成功');
      setDeleteDialogOpen(false);
      setPlatformToDelete(null);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '删除平台失败');
    }
  });

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchParams.search.trim()) {
      // 如果有搜索关键词，使用搜索接口
      const searchQuery = async () => {
        const res = await platformClientManager.get().searchPlatforms.$get({
          query: {
            name: searchParams.search,
            skip: 0,
            take: searchParams.limit
          }
        });
        if (res.status !== 200) throw new Error('搜索平台失败');
        return await res.json();
      };
      searchQuery().then(() => {
        // 暂时使用refetch，实际应该更新数据
        refetch();
      }).catch(error => {
        toast.error(error instanceof Error ? error.message : '搜索失败');
      });
    } else {
      // 没有搜索关键词，使用普通列表接口
      setSearchParams(prev => ({ ...prev, page: 1 }));
      refetch();
    }
  };

  // 处理创建平台
  const handleCreatePlatform = () => {
    setIsCreateForm(true);
    createForm.reset();
    setIsModalOpen(true);
  };

  // 处理编辑平台
  const handleEditPlatform = (platform: PlatformResponse) => {
    setIsCreateForm(false);
    updateForm.reset({
      id: platform.id,
      platformName: platform.platformName || undefined,
      contactPerson: platform.contactPerson || undefined,
      contactPhone: platform.contactPhone || undefined,
      contactEmail: platform.contactEmail || undefined
    });
    setIsModalOpen(true);
  };

  // 处理删除平台
  const handleDeletePlatform = (id: number) => {
    setPlatformToDelete(id);
    setDeleteDialogOpen(true);
  };

  // 确认删除
  const confirmDelete = () => {
    if (platformToDelete) {
      deleteMutation.mutate(platformToDelete);
    }
  };

  // 处理创建表单提交
  const handleCreateSubmit = async (data: CreatePlatformRequest) => {
    try {
      await createMutation.mutateAsync(data);
    } catch (error) {
      throw error;
    }
  };

  // 处理编辑表单提交
  const handleUpdateSubmit = async (data: UpdatePlatformRequest) => {
    try {
      await updateMutation.mutateAsync(data);
    } catch (error) {
      throw error;
    }
  };

  // 日期格式化函数
  const formatDate = (dateString: string): string => {
    if (!dateString) return '';
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return dateString;
      return format(date, 'yyyy-MM-dd HH:mm');
    } catch (error) {
      return dateString;
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">平台管理</h1>
        <Button onClick={handleCreatePlatform} data-testid="create-platform-button">
          <Plus className="mr-2 h-4 w-4" />
          创建平台
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>平台列表</CardTitle>
          <CardDescription>管理所有用人平台</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-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.search}
                  onChange={(e) => setSearchParams(prev => ({ ...prev, search: e.target.value }))}
                  className="pl-8"
                  data-testid="search-input"
                />
              </div>
              <Button type="submit" variant="outline" data-testid="search-button">
                搜索
              </Button>
            </form>
          </div>

          <div className="rounded-md border">
            <div className="relative w-full overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>平台ID</TableHead>
                    <TableHead>平台名称</TableHead>
                    <TableHead>联系人</TableHead>
                    <TableHead>联系电话</TableHead>
                    <TableHead>联系邮箱</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    Array.from({ length: 5 }).map((_, index) => (
                      <TableRow key={index}>
                        <TableCell><Skeleton className="h-4 w-8" /></TableCell>
                        <TableCell><Skeleton className="h-4 w-32" /></TableCell>
                        <TableCell><Skeleton className="h-4 w-20" /></TableCell>
                        <TableCell><Skeleton className="h-4 w-24" /></TableCell>
                        <TableCell><Skeleton className="h-4 w-32" /></TableCell>
                        <TableCell><Skeleton className="h-4 w-24" /></TableCell>
                        <TableCell>
                          <div className="flex justify-end gap-2">
                            <Skeleton className="h-8 w-8 rounded" />
                            <Skeleton className="h-8 w-8 rounded" />
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : data?.data && data.data.length > 0 ? (
                    data.data.map((platform: PlatformResponse) => (
                      <TableRow key={platform.id}>
                        <TableCell>{platform.id}</TableCell>
                        <TableCell>{platform.platformName || '-'}</TableCell>
                        <TableCell>{platform.contactPerson || '-'}</TableCell>
                        <TableCell>{platform.contactPhone || '-'}</TableCell>
                        <TableCell>{platform.contactEmail || '-'}</TableCell>
                        <TableCell>{formatDate(platform.createTime)}</TableCell>
                        <TableCell className="text-right">
                          <div className="flex justify-end gap-2">
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleEditPlatform(platform)}
                              data-testid={`edit-button-${platform.id}`}
                            >
                              <Edit className="h-4 w-4" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="icon"
                              onClick={() => handleDeletePlatform(platform.id)}
                              data-testid={`delete-button-${platform.id}`}
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={7} className="text-center py-8">
                        <p className="text-muted-foreground">暂无平台数据</p>
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          </div>

          {data.total > 0 && (<DataTablePagination
            currentPage={searchParams.page}
            pageSize={searchParams.limit}
            totalCount={data?.total || 0}
            onPageChange={(page, limit) => setSearchParams(prev => ({ ...prev, page, limit }))}
          />)}
        </CardContent>
      </Card>

      {/* 创建/编辑对话框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="sm:max-w-[500px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle data-testid={isCreateForm ? 'create-platform-dialog-title' : 'edit-platform-dialog-title'}>{isCreateForm ? '创建平台' : '编辑平台'}</DialogTitle>
            <DialogDescription>
              {isCreateForm ? '创建一个新的用人平台' : '编辑现有平台信息'}
            </DialogDescription>
          </DialogHeader>

          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="platformName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        平台名称 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入平台名称" {...field} data-testid="platform-name-input" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="contactPerson"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系人姓名" {...field} data-testid="contact-person-input" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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

                <FormField
                  control={createForm.control}
                  name="contactEmail"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系邮箱</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系邮箱"
                          value={field.value || ''}
                          onChange={field.onChange}
                          onBlur={field.onBlur}
                          name={field.name}
                          ref={field.ref}
                          data-testid="contact-email-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={createMutation.isPending} data-testid="create-submit-button">
                    创建
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="platformName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        平台名称 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入平台名称" {...field} data-testid="platform-name-input" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="contactPerson"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系人姓名" {...field} data-testid="contact-person-input" />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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

                <FormField
                  control={updateForm.control}
                  name="contactEmail"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系邮箱</FormLabel>
                      <FormControl>
                        <Input
                          placeholder="请输入联系邮箱"
                          value={field.value || ''}
                          onChange={field.onChange}
                          onBlur={field.onBlur}
                          name={field.name}
                          ref={field.ref}
                          data-testid="contact-email-input"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={updateMutation.isPending} data-testid="update-submit-button">
                    更新
                  </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}
              disabled={deleteMutation.isPending}
              data-testid="confirm-delete-button"
            >
              {deleteMutation.isPending ? '删除中...' : '删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default PlatformManagement;