import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Plus, Search, Edit, Trash2 } from 'lucide-react';
import { agentClient } from '@/client/api';
import type { InferRequestType, InferResponseType } from 'hono/client';
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 { DataTablePagination } from '@/client/admin/components/DataTablePagination';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { Skeleton } from '@/client/components/ui/skeleton';
import { Switch } from '@/client/components/ui/switch';
import { CreateAgentDto, UpdateAgentDto } from '@d8d/server/modules/agent/agent.schema';

// 使用RPC方式提取类型
type CreateAgentRequest = InferRequestType<typeof agentClient.$post>['json'];
type UpdateAgentRequest = InferRequestType<typeof agentClient[':id']['$put']>['json'];
type AgentResponse = InferResponseType<typeof agentClient.$get, 200>['data'][0];

// 直接使用后端定义的 schema
const createAgentFormSchema = CreateAgentDto;
const updateAgentFormSchema = UpdateAgentDto;

type CreateAgentFormData = CreateAgentRequest;
type UpdateAgentFormData = UpdateAgentRequest;

export const AgentsPage = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: ''
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingAgent, setEditingAgent] = useState<any>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [agentToDelete, setAgentToDelete] = useState<number | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);
  
  const createForm = useForm<CreateAgentFormData>({
    resolver: zodResolver(createAgentFormSchema),
    defaultValues: {
      username: '',
      name: null,
      phone: null,
      realname: null,
      password: '',
      state: 2,
    },
  });

  const updateForm = useForm<UpdateAgentFormData>({
    resolver: zodResolver(updateAgentFormSchema),
    defaultValues: {
      username: undefined,
      name: undefined,
      phone: null,
      realname: null,
      password: undefined,
      state: undefined,
    },
  });

  const { data: agentsData, isLoading, refetch } = useQuery({
    queryKey: ['agents', searchParams],
    queryFn: async () => {
      const res = await agentClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.limit,
          keyword: searchParams.search
        }
      });
      if (res.status !== 200) {
        throw new Error('获取代理商列表失败');
      }
      return await res.json();
    }
  });

  const agents = agentsData?.data || [];
  const totalCount = agentsData?.pagination?.total || 0;

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

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

  // 打开创建代理商对话框
  const handleCreateAgent = () => {
    setEditingAgent(null);
    setIsCreateForm(true);
    createForm.reset({
      username: '',
      name: null,
      phone: null,
      realname: null,
      password: '',
      state: 2,
    });
    setIsModalOpen(true);
  };

  // 打开编辑代理商对话框
  const handleEditAgent = (agent: AgentResponse) => {
    setEditingAgent(agent);
    setIsCreateForm(false);
    updateForm.reset({
      username: agent.username,
      name: agent.name,
      phone: agent.phone,
      realname: agent.realname,
      state: agent.state,
    });
    setIsModalOpen(true);
  };

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

  // 处理更新表单提交
  const handleUpdateSubmit = async (data: UpdateAgentFormData) => {
    if (!editingAgent) return;
    
    try {
      const res = await agentClient[':id']['$put']({
        param: { id: editingAgent.id },
        json: data
      });
      if (res.status !== 200) {
        throw new Error('更新代理商失败');
      }
      toast.success('代理商更新成功');
      setIsModalOpen(false);
      refetch();
    } catch (error) {
      console.error('更新代理商失败:', error);
      toast.error('更新失败，请重试');
    }
  };

  // 处理删除代理商
  const handleDeleteAgent = (id: number) => {
    setAgentToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!agentToDelete) return;
    
    try {
      const res = await agentClient[':id']['$delete']({
        param: { id: agentToDelete }
      });
      if (res.status !== 204) {
        throw new Error('删除代理商失败');
      }
      toast.success('代理商删除成功');
      refetch();
    } catch (error) {
      console.error('删除代理商失败:', error);
      toast.error('删除失败，请重试');
    } finally {
      setDeleteDialogOpen(false);
      setAgentToDelete(null);
    }
  };

  // 渲染加载骨架
  if (isLoading) {
    return (
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <h1 className="text-2xl font-bold">代理商管理</h1>
          <Button disabled>
            <Plus className="mr-2 h-4 w-4" />
            创建代理商
          </Button>
        </div>
        
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-1/4" />
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-full" />
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

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

      <Card>
        <CardHeader>
          <CardTitle>代理商列表</CardTitle>
          <CardDescription>
            管理系统中的所有代理商，共 {totalCount} 位代理商
          </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"
                />
              </div>
              <Button type="submit" variant="outline">
                搜索
              </Button>
            </form>
          </div>

          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>用户名</TableHead>
                  <TableHead>代理商名称</TableHead>
                  <TableHead>姓名</TableHead>
                  <TableHead>手机号</TableHead>
                  <TableHead>登录次数</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>创建时间</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {agents.map((agent) => (
                  <TableRow key={agent.id}>
                    <TableCell className="font-medium">{agent.username}</TableCell>
                    <TableCell>{agent.name || '-'}</TableCell>
                    <TableCell>{agent.realname || '-'}</TableCell>
                    <TableCell>{agent.phone || '-'}</TableCell>
                    <TableCell>{agent.loginNum}</TableCell>
                    <TableCell>
                      <Badge
                        variant={agent.state === 1 ? 'default' : 'secondary'}
                      >
                        {agent.state === 1 ? '启用' : '禁用'}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {format(new Date(agent.createdAt), 'yyyy-MM-dd HH:mm')}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditAgent(agent)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeleteAgent(agent.id)}
                        >
                          <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>
              {editingAgent ? '编辑代理商' : '创建代理商'}
            </DialogTitle>
            <DialogDescription>
              {editingAgent ? '编辑现有代理商信息' : '创建一个新的代理商账户'}
            </DialogDescription>
          </DialogHeader>
          
          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <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="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>代理商名称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入代理商名称" {...field} />
                      </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="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        密码
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input type="password" placeholder="请输入密码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="state"
                  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="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="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>代理商名称</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入代理商名称" {...field} />
                      </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="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>新密码</FormLabel>
                      <FormControl>
                        <Input type="password" placeholder="留空则不修改密码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="state"
                  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>
  );
};