import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import { Plus, Search, Edit, Trash2, CalendarIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import type { InferResponseType, InferRequestType } 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 { 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 { Skeleton } from '@/client/components/ui/skeleton';
import { toast } from 'sonner';
import { Calendar } from '@/client/components/ui/calendar';
import { Popover, PopoverContent, PopoverTrigger } from '@/client/components/ui/popover';
import { cn } from '@/client/lib/utils';

import { stockXunlianCodesClient } from '@/client/api';
import { CreateStockXunlianCodesDto, UpdateStockXunlianCodesDto } from '@/server/modules/stock/stock-xunlian-codes.schema';
import { DataTablePagination } from '@/client/admin/components/DataTablePagination';

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

// 表单Schema
const createFormSchema = CreateStockXunlianCodesDto;
const updateFormSchema = UpdateStockXunlianCodesDto;

export const StockXunlianCodesPage = () => {
  const queryClient = useQueryClient();
  
  // 状态管理
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: '',
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingEntity, setEditingEntity] = useState<StockXunlianCode | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [entityToDelete, setEntityToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm<CreateRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      code: '',
      stockName: '',
      name: '',
      type: '',
      description: '',
      trainingStartDate: new Date(),
      trainingEndDate: new Date(),
    },
  });

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

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

  // 创建mutation
  const createMutation = useMutation({
    mutationFn: async (data: CreateRequest) => {
      const res = await stockXunlianCodesClient.$post({ json: data });
      if (res.status !== 201) throw new Error('创建失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('创建成功');
      setIsModalOpen(false);
      createForm.reset();
      refetch();
    },
    onError: (error) => {
      toast.error(`创建失败: ${error.message}`);
    },
  });

  // 更新mutation
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: UpdateRequest }) => {
      const res = await stockXunlianCodesClient[':id']['$put']({
        param: { id: id.toString() },
        json: data,
      });
      if (res.status !== 200) throw new Error('更新失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('更新成功');
      setIsModalOpen(false);
      setEditingEntity(null);
      refetch();
    },
    onError: (error) => {
      toast.error(`更新失败: ${error.message}`);
    },
  });

  // 删除mutation
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await stockXunlianCodesClient[':id']['$delete']({
        param: { id: id.toString() },
      });
      if (res.status !== 204) throw new Error('删除失败');
      return id;
    },
    onSuccess: () => {
      toast.success('删除成功');
      setDeleteDialogOpen(false);
      setEntityToDelete(null);
      refetch();
    },
    onError: (error) => {
      toast.error(`删除失败: ${error.message}`);
    },
  });

  // 业务逻辑函数
  const handleSearch = () => {
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  const handleCreateEntity = () => {
    setIsCreateForm(true);
    setEditingEntity(null);
    createForm.reset();
    setIsModalOpen(true);
  };

  const handleEditEntity = (entity: StockXunlianCode) => {
    setIsCreateForm(false);
    setEditingEntity(entity);
    updateForm.reset({
      code: entity.code,
      stockName: entity.stockName,
      name: entity.name,
      type: entity.type || '',
      description: entity.description || '',
      trainingStartDate: new Date(entity.trainingStartDate),
      trainingEndDate: new Date(entity.trainingEndDate),
    });
    setIsModalOpen(true);
  };

  const handleDeleteEntity = (id: number) => {
    setEntityToDelete(id);
    setDeleteDialogOpen(true);
  };

  const handleCreateSubmit = (data: CreateRequest) => {
    createMutation.mutate(data);
  };

  const handleUpdateSubmit = (data: UpdateRequest) => {
    if (editingEntity) {
      updateMutation.mutate({ id: editingEntity.id, data });
    }
  };

  const confirmDelete = () => {
    if (entityToDelete) {
      deleteMutation.mutate(entityToDelete);
    }
  };

  // 加载骨架屏
  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 w-20" />
                </div>
              ))}
            </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={handleCreateEntity}>
          <Plus className="mr-2 h-4 w-4" />
          创建训练代码
        </Button>
      </div>

      {/* 搜索区域 */}
      <Card>
        <CardHeader>
          <CardTitle>训练代码列表</CardTitle>
          <CardDescription>管理股票训练案例和代码</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-4">
            <form onSubmit={(e) => { e.preventDefault(); 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>
                {data?.data.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell className="font-medium">{item.code}</TableCell>
                    <TableCell>{item.stockName}</TableCell>
                    <TableCell>{item.name}</TableCell>
                    <TableCell>{item.type || '-'}</TableCell>
                    <TableCell>{format(new Date(item.trainingStartDate), 'yyyy-MM-dd')}</TableCell>
                    <TableCell>{format(new Date(item.trainingEndDate), 'yyyy-MM-dd')}</TableCell>
                    <TableCell>{format(new Date(item.createdAt), 'yyyy-MM-dd HH:mm')}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditEntity(item)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeleteEntity(item.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="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>股票代码</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入股票代码，如000001" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="stockName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>股票名称</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="type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>案例类型</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入案例类型，如技术分析" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>案例描述</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入案例描述" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="trainingStartDate"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>训练开始日期</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              className={cn(
                                'w-full pl-3 text-left font-normal',
                                !field.value && 'text-muted-foreground'
                              )}
                            >
                              {field.value ? (
                                format(field.value, 'yyyy-MM-dd')
                              ) : (
                                <span>选择开始日期</span>
                              )}
                              <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                          <Calendar
                            mode="single"
                            selected={field.value}
                            onSelect={field.onChange}
                            disabled={(date) =>
                              date > new Date() || date < new Date('1900-01-01')
                            }
                            initialFocus
                          />
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="trainingEndDate"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>训练结束日期</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              className={cn(
                                'w-full pl-3 text-left font-normal',
                                !field.value && 'text-muted-foreground'
                              )}
                            >
                              {field.value ? (
                                format(field.value, 'yyyy-MM-dd')
                              ) : (
                                <span>选择结束日期</span>
                              )}
                              <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                          <Calendar
                            mode="single"
                            selected={field.value}
                            onSelect={field.onChange}
                            disabled={(date) =>
                              date > new Date() || date < new Date('1900-01-01')
                            }
                            initialFocus
                          />
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={createMutation.isPending}>
                    {createMutation.isPending ? '创建中...' : '创建'}
                  </Button>
                </DialogFooter>
              </form>
            </Form>
          ) : (
            <Form {...updateForm}>
              <form onSubmit={updateForm.handleSubmit(handleUpdateSubmit)} className="space-y-4">
                <FormField
                  control={updateForm.control}
                  name="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>股票代码</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入股票代码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="stockName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>股票名称</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="type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>案例类型</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入案例类型" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>案例描述</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入案例描述" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="trainingStartDate"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>训练开始日期</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              className={cn(
                                'w-full pl-3 text-left font-normal',
                                !field.value && 'text-muted-foreground'
                              )}
                            >
                              {field.value ? (
                                format(field.value, 'yyyy-MM-dd')
                              ) : (
                                <span>选择开始日期</span>
                              )}
                              <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                          <Calendar
                            mode="single"
                            selected={field.value}
                            onSelect={field.onChange}
                            disabled={(date) =>
                              date > new Date() || date < new Date('1900-01-01')
                            }
                            initialFocus
                          />
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="trainingEndDate"
                  render={({ field }) => (
                    <FormItem className="flex flex-col">
                      <FormLabel>训练结束日期</FormLabel>
                      <Popover>
                        <PopoverTrigger asChild>
                          <FormControl>
                            <Button
                              variant="outline"
                              className={cn(
                                'w-full pl-3 text-left font-normal',
                                !field.value && 'text-muted-foreground'
                              )}
                            >
                              {field.value ? (
                                format(field.value, 'yyyy-MM-dd')
                              ) : (
                                <span>选择结束日期</span>
                              )}
                              <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                            </Button>
                          </FormControl>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                          <Calendar
                            mode="single"
                            selected={field.value}
                            onSelect={field.onChange}
                            disabled={(date) =>
                              date > new Date() || date < new Date('1900-01-01')
                            }
                            initialFocus
                          />
                        </PopoverContent>
                      </Popover>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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