import React, { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Plus, Search, Edit, Trash2, Download, Eye } from 'lucide-react';
import { templateClient } from '@/client/api';
import FilePreviewDialog from '@/client/admin/components/FilePreviewDialog';
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { DisabledStatus, DeleteStatus } from '@/share/types';
import { CreateTemplateDto, UpdateTemplateDto } from '@/server/modules/templates/template.schema';
import FileSelector from '@/client/admin/components/FileSelector';

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

// 直接使用后端定义的 schema
const createTemplateFormSchema = CreateTemplateDto;
const updateTemplateFormSchema = UpdateTemplateDto;

type CreateTemplateFormData = CreateTemplateRequest;
type UpdateTemplateFormData = UpdateTemplateRequest;

export const TemplatesPage = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: ''
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<any>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [templateToDelete, setTemplateToDelete] = useState<number | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [previewDialogOpen, setPreviewDialogOpen] = useState(false);
  const [previewFile, setPreviewFile] = useState<any>(null);
  
  const createForm = useForm<CreateTemplateFormData>({
    resolver: zodResolver(createTemplateFormSchema),
    defaultValues: {
      title: '',
      description: null,
      fileId: undefined,
      category: '',
      isFree: 0,
    },
  });

  const updateForm = useForm<UpdateTemplateFormData>({
    resolver: zodResolver(updateTemplateFormSchema),
    defaultValues: {
      title: undefined,
      description: null,
      fileId: undefined,
      category: undefined,
      isFree: undefined,
      isDisabled: undefined,
    },
  });

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

  const templates = templatesData?.data || [];
  const totalCount = templatesData?.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 handleCreateTemplate = () => {
    setEditingTemplate(null);
    setIsCreateForm(true);
    createForm.reset({
      title: '',
      description: null,
      fileId: undefined,
      category: '',
      isFree: 0,
    });
    setIsModalOpen(true);
  };

  // 打开编辑模板对话框
  const handleEditTemplate = (template: TemplateResponse) => {
    setEditingTemplate(template);
    setIsCreateForm(false);
    updateForm.reset({
      title: template.title,
      description: template.description,
      fileId: template.fileId,
      category: template.category,
      isFree: template.isFree,
      isDisabled: template.isDisabled,
    });
    setIsModalOpen(true);
  };

  // 处理创建表单提交
  const handleCreateSubmit = async (data: CreateTemplateFormData) => {
    try {
      const res = await templateClient.$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: UpdateTemplateFormData) => {
    if (!editingTemplate) return;
    
    try {
      const res = await templateClient[':id']['$put']({
        param: { id: editingTemplate.id },
        json: data
      });
      if (res.status !== 200) {
        throw new Error('更新模板失败');
      }
      toast.success('模板更新成功');
      setIsModalOpen(false);
      refetch();
    } catch (error) {
      console.error('更新模板失败:', error);
      toast.error('更新失败，请重试');
    }
  };

  // 处理删除模板
  const handleDeleteTemplate = (id: number) => {
    setTemplateToDelete(id);
    setDeleteDialogOpen(true);
  };

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

  // 处理预览模板文件
  const handlePreviewTemplate = (template: TemplateResponse) => {
    if (!template.file) {
      toast.warning('该模板没有关联文件');
      return;
    }
    setPreviewFile(template.file);
    setPreviewDialogOpen(true);
  };

  // 渲染加载骨架
  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={handleCreateTemplate}>
          <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>
                {templates.map((template) => (
                  <TableRow key={template.id}>
                    <TableCell className="font-medium">{template.title}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{template.category}</Badge>
                    </TableCell>
                    <TableCell>
                      {template.file?.name ? (
                        <span className="text-sm text-muted-foreground">
                          {template.file.name}
                        </span>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge
                        variant={template.isFree === 1 ? 'default' : 'secondary'}
                      >
                        {template.isFree === 1 ? '免费' : '收费'}
                      </Badge>
                    </TableCell>
                    <TableCell>{template.downloadCount}</TableCell>
                    <TableCell>
                      <Badge
                        variant={template.isDisabled === 1 ? 'secondary' : 'default'}
                      >
                        {template.isDisabled === 1 ? '禁用' : '启用'}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {format(new Date(template.createdAt), 'yyyy-MM-dd HH:mm')}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handlePreviewTemplate(template)}
                          title="预览文件"
                        >
                          <Eye className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditTemplate(template)}
                          title="编辑模板"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeleteTemplate(template.id)}
                          title="删除模板"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {templates.length === 0 && !isLoading && (
            <div className="text-center py-8">
              <p className="text-muted-foreground">暂无模板数据</p>
            </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>
              {editingTemplate ? '编辑模板' : '创建模板'}
            </DialogTitle>
            <DialogDescription>
              {editingTemplate ? '编辑现有模板信息' : '创建一个新的模板'}
            </DialogDescription>
          </DialogHeader>
          
          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="title"
                  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="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>模板描述</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入模板描述" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="fileId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        关联文件
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <FileSelector
                          value={field.value || undefined}
                          onChange={(value) => field.onChange(value)}
                          maxSize={50}
                          uploadPath="/templates"
                          uploadButtonText="上传模板文件"
                          previewSize="medium"
                          placeholder="选择模板文件"
                          title="选择模板文件"
                          description="上传新文件或从已有文件中选择"
                          filterType="all"
                        />
                      </FormControl>
                      <FormDescription>请选择或上传模板文件</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="category"
                  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="isFree"
                  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 : 0)}
                        />
                      </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="title"
                  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="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>模板描述</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入模板描述" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="fileId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>关联文件</FormLabel>
                      <FormControl>
                        <FileSelector
                          value={field.value || undefined}
                          onChange={(value) => field.onChange(value)}
                          maxSize={50}
                          uploadPath="/templates"
                          uploadButtonText="上传模板文件"
                          previewSize="medium"
                          placeholder="选择模板文件"
                          title="选择模板文件"
                          description="上传新文件或从已有文件中选择"
                          filterType="all"
                        />
                      </FormControl>
                      <FormDescription>修改关联的模板文件</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="category"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>分类</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入分类名称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="isFree"
                  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 : 0)}
                        />
                      </FormControl>
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="isDisabled"
                  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 : 0)}
                        />
                      </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>
      
      {/* 文件预览对话框 */}
      <FilePreviewDialog
        open={previewDialogOpen}
        onOpenChange={setPreviewDialogOpen}
        file={previewFile}
      />
    </div>
  );
};

export default TemplatesPage;