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

import { dateNotesClient } from '@/client/api';
import type { InferResponseType, InferRequestType } from 'hono/client';
import { CreateDateNotesDto, UpdateDateNotesDto } from '@/server/modules/stock/date-notes.schema';

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 { 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 { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/client/components/ui/table';
import { Badge } from '@/client/components/ui/badge';
import { DataTablePagination } from '@/client/admin/components/DataTablePagination';
import { Skeleton } from '@/client/components/ui/skeleton';

// 定义类型
type DateNotesListResponse = InferResponseType<typeof dateNotesClient.$get, 200>;
type DateNotesItem = DateNotesListResponse['data'][0];
type CreateDateNotesRequest = InferRequestType<typeof dateNotesClient.$post>['json'];
type UpdateDateNotesRequest = InferRequestType<typeof dateNotesClient[':id']['$put']>['json'];

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

export const DateNotesPage = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: '',
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [editingEntity, setEditingEntity] = useState<DateNotesItem | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [entityToDelete, setEntityToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm<CreateDateNotesRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      code: '',
      noteDate: new Date() as any,
      note: '',
    },
  });

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

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

  // 搜索功能
  const handleSearch = () => {
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 显示创建模态框
  const showCreateModal = () => {
    setIsCreateForm(true);
    setEditingEntity(null);
    createForm.reset();
    setIsModalOpen(true);
  };

  // 显示编辑模态框
  const showEditModal = (record: DateNotesItem) => {
    setIsCreateForm(false);
    setEditingEntity(record);
    updateForm.reset({
      code: record.code,
      noteDate: record.noteDate as any,
      note: record.note,
    });
    setIsModalOpen(true);
  };

  // 处理创建提交
  const handleCreateSubmit = async (data: CreateDateNotesRequest) => {
    try {
      const res = await dateNotesClient.$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: UpdateDateNotesRequest) => {
    if (!editingEntity) return;

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

  // 显示删除确认
  const showDeleteDialog = (id: number) => {
    setEntityToDelete(id);
    setDeleteDialogOpen(true);
  };

  // 确认删除
  const confirmDelete = async () => {
    if (!entityToDelete) return;

    try {
      const res = await dateNotesClient[':id'].$delete({
        param: { id: entityToDelete.toString() },
      });
      
      if (res.status !== 204) throw new Error('删除失败');
      
      toast.success('删除成功');
      setDeleteDialogOpen(false);
      refetch();
    } 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>
          <CardHeader>
            <Skeleton className="h-6 w-1/4" />
          </CardHeader>
          <CardContent>
            <Skeleton className="h-10 w-full max-w-sm" />
          </CardContent>
        </Card>

        <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={showCreateModal}>
          <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 className="w-[80px]">ID</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.id}</TableCell>
                    <TableCell>{item.code}</TableCell>
                    <TableCell>
                      {item.noteDate 
                        ? format(new Date(item.noteDate), 'yyyy-MM-dd HH:mm', { locale: zhCN })
                        : '-'}
                    </TableCell>
                    <TableCell>{item.note}</TableCell>
                    <TableCell>
                      {item.createdAt 
                        ? format(new Date(item.createdAt), 'yyyy-MM-dd HH:mm', { locale: zhCN })
                        : '-'}
                    </TableCell>
                    <TableCell>
                      <Badge 
                        variant={new Date(item.updatedAt) > new Date(item.createdAt) ? 'default' : 'secondary'}
                      >
                        {new Date(item.updatedAt) > new Date(item.createdAt) ? '已更新' : '原始数据'}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => showEditModal(item)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => showDeleteDialog(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>股票代码 <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="请输入股票代码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="noteDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>备注日期 <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input 
                          type="datetime-local" 
                          {...field}
                          value={field.value ? new Date(field.value).toISOString().slice(0, 16) : ''}
                          onChange={(e) => field.onChange(new Date(e.target.value))}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="note"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>备注内容 <span className="text-red-500">*</span></FormLabel>
                      <FormControl>
                        <Input placeholder="请输入备注内容" {...field} />
                      </FormControl>
                      <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="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>股票代码</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入股票代码" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="noteDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>备注日期</FormLabel>
                      <FormControl>
                        <Input 
                          type="datetime-local" 
                          {...field}
                          value={field.value ? new Date(field.value).toISOString().slice(0, 16) : ''}
                          onChange={(e) => field.onChange(new Date(e.target.value))}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="note"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>备注内容</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入备注内容" {...field} />
                      </FormControl>
                      <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>
  );
};