import React, { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Search, Eye } from 'lucide-react';
import { format } from 'date-fns';
import { Input } from '@/client/components/ui/input';
import { Button } from '@/client/components/ui/button';
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 { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { DataTablePagination } from '@/client/admin/components/DataTablePagination';
import ImageSelector from '@/client/admin/components/ImageSelector';
import AdvertisementTypeSelector from '@/client/admin/components/AdvertisementTypeSelector';
import { advertisementClient } from '@/client/api';
import type { InferRequestType, InferResponseType } from 'hono/client';
import { CreateAdvertisementDto, UpdateAdvertisementDto } from '@d8d/advertisements-module/schemas';

type CreateRequest = InferRequestType<typeof advertisementClient.$post>['json'];
type UpdateRequest = InferRequestType<typeof advertisementClient[':id']['$put']>['json'];
type AdvertisementResponse = InferResponseType<typeof advertisementClient.$get, 200>['data'][0];

const createFormSchema = CreateAdvertisementDto;
const updateFormSchema = UpdateAdvertisementDto;

export const AdvertisementsPage = () => {
  const queryClient = useQueryClient();
  const [searchParams, setSearchParams] = useState({ page: 1, limit: 10, search: '' });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingAdvertisement, setEditingAdvertisement] = useState<AdvertisementResponse | null>(null);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [advertisementToDelete, setAdvertisementToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm<CreateRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      title: '',
      typeId: 1,
      code: '',
      url: '',
      imageFileId: undefined,
      sort: 0,
      status: 1,
      actionType: 1
    }
  });

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

  // 获取广告类型列表 - 现在由 AdvertisementTypeSelector 内部处理

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

  // 创建广告
  const createMutation = useMutation({
    mutationFn: async (data: CreateRequest) => {
      const res = await advertisementClient.$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 instanceof Error ? error.message : '创建广告失败');
    }
  });

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

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

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

  // 处理创建广告
  const handleCreateAdvertisement = () => {
    setIsCreateForm(true);
    setEditingAdvertisement(null);
    createForm.reset();
    setIsModalOpen(true);
  };

  // 处理编辑广告
  const handleEditAdvertisement = (advertisement: AdvertisementResponse) => {
    setIsCreateForm(false);
    setEditingAdvertisement(advertisement);
    updateForm.reset({
      title: advertisement.title || undefined,
      typeId: advertisement.typeId || undefined,
      code: advertisement.code || undefined,
      url: advertisement.url || undefined,
      imageFileId: advertisement.imageFileId || undefined,
      sort: advertisement.sort || undefined,
      status: advertisement.status || undefined,
      actionType: advertisement.actionType || undefined
    });
    setIsModalOpen(true);
  };

  // 处理删除广告
  const handleDeleteAdvertisement = (id: number) => {
    setAdvertisementToDelete(id);
    setDeleteDialogOpen(true);
  };

  // 确认删除
  const confirmDelete = () => {
    if (advertisementToDelete) {
      deleteMutation.mutate(advertisementToDelete);
    }
  };

  // 处理创建表单提交
  const handleCreateSubmit = async (data: CreateRequest) => {
    try {
      await createMutation.mutateAsync(data);
    } catch (error) {
      throw error;
    }
  };

  // 处理编辑表单提交
  const handleUpdateSubmit = async (data: UpdateRequest) => {
    if (!editingAdvertisement) return;
    
    try {
      await updateMutation.mutateAsync({
        id: editingAdvertisement.id,
        data
      });
    } catch (error) {
      throw error;
    }
  };

  // 渲染加载骨架
  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>
            <Skeleton className="h-32 w-full" />
          </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={handleCreateAdvertisement}>
          <Plus className="mr-2 h-4 w-4" />
          创建广告
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>广告列表</CardTitle>
          <CardDescription>管理网站的所有广告内容</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>ID</TableHead>
                  <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((advertisement) => (
                  <TableRow key={advertisement.id}>
                    <TableCell>{advertisement.id}</TableCell>
                    <TableCell>{advertisement.title || '-'}</TableCell>
                    <TableCell>
                      {advertisement.advertisementType?.name || '-'}
                    </TableCell>
                    <TableCell>
                      <code className="text-xs bg-muted px-1 rounded">{advertisement.code || '-'}</code>
                    </TableCell>
                    <TableCell>
                      {advertisement.imageFile?.fullUrl ? (
                        <img
                          src={advertisement.imageFile.fullUrl}
                          alt={advertisement.title || '广告图片'}
                          className="w-16 h-10 object-cover rounded"
                          onError={(e) => {
                            e.currentTarget.src = '/placeholder.png';
                          }}
                        />
                      ) : (
                        <span className="text-muted-foreground text-xs">无图片</span>
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant={advertisement.status === 1 ? 'default' : 'secondary'}>
                        {advertisement.status === 1 ? '启用' : '禁用'}
                      </Badge>
                    </TableCell>
                    <TableCell>{advertisement.sort}</TableCell>
                    <TableCell>
                      {advertisement.createdAt ? format(new Date(advertisement.createdAt), 'yyyy-MM-dd HH:mm') : '-'}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => handleEditAdvertisement(advertisement)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button 
                          variant="ghost" 
                          size="icon" 
                          onClick={() => handleDeleteAdvertisement(advertisement.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-[600px] 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="title"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        标题 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入广告标题" {...field} />
                      </FormControl>
                      <FormDescription>广告显示的标题文本，最多30个字符</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="typeId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        广告类型 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <AdvertisementTypeSelector
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="请选择广告类型"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        调用别名 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入调用别名" {...field} />
                      </FormControl>
                      <FormDescription>用于程序调用的唯一标识，最多20个字符</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="imageFileId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>广告图片</FormLabel>
                      <FormControl>
                        <ImageSelector
                          value={field.value || undefined}
                          onChange={field.onChange}
                          maxSize={2}
                          uploadPath="/advertisements"
                          uploadButtonText="上传广告图片"
                          previewSize="medium"
                          placeholder="选择广告图片"
                          title="选择广告图片"
                          description="上传新图片或从已有图片中选择"
                        />
                      </FormControl>
                      <FormDescription>推荐尺寸：1200x400px，支持jpg、png格式</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="url"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>跳转链接</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入跳转链接" {...field} />
                      </FormControl>
                      <FormDescription>点击广告后跳转的URL地址</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={createForm.control}
                    name="actionType"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>跳转类型</FormLabel>
                        <FormControl>
                          <select
                            {...field}
                            className="h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                            value={field.value || 1}
                            onChange={(e) => field.onChange(parseInt(e.target.value))}
                          >
                            <option value={0}>不跳转</option>
                            <option value={1}>Web页面</option>
                            <option value={2}>小程序页面</option>
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={createForm.control}
                    name="sort"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>排序值</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            placeholder="排序值"
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value))}
                          />
                        </FormControl>
                        <FormDescription>数值越大排序越靠前</FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <FormField
                  control={createForm.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <FormControl>
                        <select
                          {...field}
                          className="h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                          value={field.value || 1}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        >
                          <option value={1}>启用</option>
                          <option value={0}>禁用</option>
                        </select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={createMutation.isPending}>
                    创建
                  </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>
                      <FormDescription>广告显示的标题文本，最多30个字符</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="typeId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        广告类型 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <AdvertisementTypeSelector
                          value={field.value}
                          onChange={field.onChange}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="code"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        调用别名 <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input placeholder="请输入调用别名" {...field} />
                      </FormControl>
                      <FormDescription>用于程序调用的唯一标识，最多20个字符</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="imageFileId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>广告图片</FormLabel>
                      <FormControl>
                        <ImageSelector
                          value={field.value || undefined}
                          onChange={field.onChange}
                          maxSize={2}
                          uploadPath="/advertisements"
                          uploadButtonText="上传广告图片"
                          previewSize="medium"
                          placeholder="选择广告图片"
                          title="选择广告图片"
                          description="上传新图片或从已有图片中选择"
                        />
                      </FormControl>
                      <FormDescription>推荐尺寸：1200x400px，支持jpg、png格式</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="url"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>跳转链接</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入跳转链接" {...field} />
                      </FormControl>
                      <FormDescription>点击广告后跳转的URL地址</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <div className="grid grid-cols-2 gap-4">
                  <FormField
                    control={updateForm.control}
                    name="actionType"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>跳转类型</FormLabel>
                        <FormControl>
                          <select
                            {...field}
                            className="h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                            value={field.value || 1}
                            onChange={(e) => field.onChange(parseInt(e.target.value))}
                          >
                            <option value={0}>不跳转</option>
                            <option value={1}>Web页面</option>
                            <option value={2}>小程序页面</option>
                          </select>
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

                  <FormField
                    control={updateForm.control}
                    name="sort"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>排序值</FormLabel>
                        <FormControl>
                          <Input
                            type="number"
                            placeholder="排序值"
                            {...field}
                            onChange={(e) => field.onChange(parseInt(e.target.value))}
                          />
                        </FormControl>
                        <FormDescription>数值越大排序越靠前</FormDescription>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <FormField
                  control={updateForm.control}
                  name="status"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>状态</FormLabel>
                      <FormControl>
                        <select
                          {...field}
                          className="h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                          value={field.value || 1}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        >
                          <option value={1}>启用</option>
                          <option value={0}>禁用</option>
                        </select>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <DialogFooter>
                  <Button type="button" variant="outline" onClick={() => setIsModalOpen(false)}>
                    取消
                  </Button>
                  <Button type="submit" disabled={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>
  );
};

// 简单的骨架屏组件
const Skeleton = ({ className }: { className?: string }) => (
  <div className={`animate-pulse rounded-md bg-muted ${className}`} />
);