import React, { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import {
  Search,
  Plus,
  Edit,
  Trash2,
  User,
  Phone,
  Eye,
  EyeOff
} from 'lucide-react';

import { supplierClient } from '@/client/api';
import type { InferRequestType, InferResponseType } from 'hono/client';
import { CreateAdminSupplierDto, UpdateAdminSupplierDto } from '@d8d/supplier-module/schemas';

import { Button } from '@/client/components/ui/button';
import { Input } from '@/client/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/client/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
import { Badge } from '@/client/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/client/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { Skeleton } from '@/client/components/ui/skeleton';
import { DataTablePagination } from '@/client/admin/components/DataTablePagination';

// 类型定义
type SupplierResponse = InferResponseType<typeof supplierClient.$get, 200>;
type SupplierItem = SupplierResponse['data'][0];
type CreateRequest = InferRequestType<typeof supplierClient.$post>['json'];
type UpdateRequest = InferRequestType<typeof supplierClient[':id']['$put']>['json'];

// 表单Schema直接使用后端定义
const createFormSchema = CreateAdminSupplierDto;
const updateFormSchema = UpdateAdminSupplierDto;

export const SuppliersPage = () => {
  // 状态管理
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: '',
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingSupplier, setEditingSupplier] = useState<SupplierItem | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [supplierToDelete, setSupplierToDelete] = useState<number | null>(null);
  const [showPassword, setShowPassword] = useState(false);

  // 表单实例
  const createForm = useForm<CreateRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      name: '',
      username: '',
      password: '',
      phone: '',
      realname: '',
      state: 2,
    },
  });

  const updateForm = useForm<UpdateRequest>({
    resolver: zodResolver(updateFormSchema),
  });

  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['suppliers', searchParams],
    queryFn: async () => {
      const res = await supplierClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.search,
        },
      });
      if (res.status !== 200) throw new Error('获取供应商列表失败');
      return await res.json();
    },
  });

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

  // 创建供应商
  const handleCreateSupplier = () => {
    setIsCreateForm(true);
    setEditingSupplier(null);
    createForm.reset({
      name: '',
      username: '',
      password: '',
      phone: '',
      realname: '',
      state: 2,
    });
    setIsModalOpen(true);
  };

  // 编辑供应商
  const handleEditSupplier = (supplier: SupplierItem) => {
    setIsCreateForm(false);
    setEditingSupplier(supplier);
    updateForm.reset({
      name: supplier.name,
      username: supplier.username,
      phone: supplier.phone,
      realname: supplier.realname,
      state: supplier.state,
    });
    setIsModalOpen(true);
  };

  // 删除供应商
  const handleDeleteSupplier = (id: number) => {
    setSupplierToDelete(id);
    setDeleteDialogOpen(true);
  };

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

    try {
      const res = await supplierClient[':id']['$delete']({
        param: { id: supplierToDelete.toString() },
      });
      
      if (res.status === 204) {
        toast.success('删除成功');
        setDeleteDialogOpen(false);
        refetch();
      } else {
        throw new Error('删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      toast.error('删除失败，请重试');
    }
  };

  // 表单提交处理
  const handleCreateSubmit = async (data: CreateRequest) => {
    try {
      const res = await supplierClient.$post({ json: data });
      if (res.status === 201) {
        toast.success('创建成功');
        setIsModalOpen(false);
        refetch();
      } else {
        const error = await res.json();
        toast.error(error.message || '创建失败');
      }
    } catch (error) {
      console.error('创建失败:', error);
      toast.error('操作失败，请重试');
    }
  };

  const handleUpdateSubmit = async (data: UpdateRequest) => {
    if (!editingSupplier) return;

    try {
      const updateData = {
        ...data,
        ...(data.password === '' && { password: undefined }),
      };

      const res = await supplierClient[':id']['$put']({
        param: { id: editingSupplier.id.toString() },
        json: updateData,
      });
      
      if (res.status === 200) {
        toast.success('更新成功');
        setIsModalOpen(false);
        refetch();
      } else {
        const error = await res.json();
        toast.error(error.message || '更新失败');
      }
    } catch (error) {
      console.error('更新失败:', error);
      toast.error('操作失败，请重试');
    }
  };

  // 加载状态
  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <Skeleton className="h-8 w-48" />
          <Skeleton className="h-10 w-32" />
        </div>
        
        <Card>
          <CardContent className="pt-6">
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="flex gap-4">
                  <Skeleton className="h-10 flex-1" />
                  <Skeleton className="h-10 flex-1" />
                  <Skeleton className="h-10 flex-1" />
                  <Skeleton className="h-10 flex-1" />
                  <Skeleton className="h-10 w-20" />
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* 页面标题 */}
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-2xl font-bold">供应商管理</h1>
          <p className="text-muted-foreground">管理供应商信息和状态</p>
        </div>
        <Button onClick={handleCreateSupplier}>
          <Plus className="mr-2 h-4 w-4" />
          创建供应商
        </Button>
      </div>

      {/* 搜索区域 */}
      <Card>
        <CardHeader>
          <CardTitle>供应商列表</CardTitle>
          <CardDescription>查看和管理所有供应商信息</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSearch} className="flex gap-2 mb-4">
            <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"
              />
            </div>
            <Button type="submit" variant="outline">
              搜索
            </Button>
          </form>

          {/* 数据表格 */}
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>供应商名称</TableHead>
                  <TableHead>用户名</TableHead>
                  <TableHead>联系人</TableHead>
                  <TableHead>手机号码</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data?.data.map((supplier) => (
                  <TableRow key={supplier.id}>
                    <TableCell>{supplier.id}</TableCell>
                    <TableCell>{supplier.name || '-'}</TableCell>
                    <TableCell>{supplier.username}</TableCell>
                    <TableCell>{supplier.realname || '-'}</TableCell>
                    <TableCell>{supplier.phone || '-'}</TableCell>
                    <TableCell>
                      <Badge variant={supplier.state === 1 ? 'default' : 'secondary'}>
                        {supplier.state === 1 ? '启用' : '禁用'}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {format(new Date(supplier.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN })}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditSupplier(supplier)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeleteSupplier(supplier.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {data?.data.length === 0 && !isLoading && (
            <div className="text-center py-8">
              <p className="text-muted-foreground">暂无供应商数据</p>
            </div>
          )}

          {/* 分页 */}
          <DataTablePagination
            currentPage={searchParams.page}
            pageSize={searchParams.limit}
            totalCount={data?.pagination.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>{isCreateForm ? '创建供应商' : '编辑供应商'}</DialogTitle>
            <DialogDescription>
              {isCreateForm ? '创建一个新的供应商账户' : '编辑供应商基本信息'}
            </DialogDescription>
          </DialogHeader>

          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="name"
                  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="username"
                  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="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        密码
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type={showPassword ? 'text' : 'password'}
                            placeholder="请输入密码"
                            {...field}
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3"
                            onClick={() => setShowPassword(!showPassword)}
                          >
                            {showPassword ? (
                              <EyeOff className="h-4 w-4" />
                            ) : (
                              <Eye className="h-4 w-4" />
                            )}
                          </Button>
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="realname"
                  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="state"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <Select
                        onValueChange={(value) => field.onChange(parseInt(value))}
                        defaultValue={field.value?.toString()}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择状态" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="1">启用</SelectItem>
                          <SelectItem value="2">禁用</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </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 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="username"
                  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="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>密码（留空不修改）</FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            type={showPassword ? 'text' : 'password'}
                            placeholder="不修改请留空"
                            {...field}
                          />
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            className="absolute right-0 top-0 h-full px-3"
                            onClick={() => setShowPassword(!showPassword)}
                          >
                            {showPassword ? (
                              <EyeOff className="h-4 w-4" />
                            ) : (
                              <Eye className="h-4 w-4" />
                            )}
                          </Button>
                        </div>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="realname"
                  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="state"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <Select
                        onValueChange={(value) => field.onChange(parseInt(value))}
                        value={field.value?.toString()}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="请选择状态" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value="1">启用</SelectItem>
                          <SelectItem value="2">禁用</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </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>
  );
};