import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
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 {
  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 { Input } from '@/client/components/ui/input';
import { Textarea } from '@/client/components/ui/textarea';
import { Switch } from '@/client/components/ui/switch';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/client/components/ui/select';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Plus, Edit, Trash2, Search } from 'lucide-react';
import { membershipPlanClient } from '@/client/api';
import type { InferResponseType, InferRequestType } from 'hono/client';
import { toast } from 'sonner';
import { z } from 'zod';
import { CreateMembershipPlanDto, UpdateMembershipPlanDto, MembershipType } from '@/server/modules/membership/membership-plan.schema';
import { format } from 'date-fns';
import { Badge } from '@/client/components/ui/badge';
import { DataTablePagination } from '@/client/admin/components/DataTablePagination';
import { Skeleton } from '@/client/components/ui/skeleton';

// 类型定义
type MembershipPlanResponse = InferResponseType<typeof membershipPlanClient.$get, 200>['data'][0];
type MembershipPlanListResponse = InferResponseType<typeof membershipPlanClient.$get, 200>;
type CreateMembershipPlanRequest = InferRequestType<typeof membershipPlanClient.$post>['json'];
type UpdateMembershipPlanRequest = InferRequestType<typeof membershipPlanClient[':id']['$put']>['json'];

// 直接使用后端的schema
const createFormSchema = CreateMembershipPlanDto;
const updateFormSchema = UpdateMembershipPlanDto;

// 类型映射
const typeLabels: Record<MembershipType, string> = {
  [MembershipType.SINGLE]: '单次',
  [MembershipType.MONTHLY]: '单月',
  [MembershipType.YEARLY]: '年',
  [MembershipType.LIFETIME]: '永久',
};

export const MembershipPlans = () => {
  // 状态管理
  const [searchParams, setSearchParams] = useState({
    page: 1,
    limit: 10,
    search: '',
  });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [editingPlan, setEditingPlan] = useState<MembershipPlanResponse | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [planToDelete, setPlanToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm<CreateMembershipPlanRequest>({
    resolver: zodResolver(createFormSchema),
    defaultValues: {
      name: '',
      type: MembershipType.MONTHLY,
      price: 0,
      durationDays: 30,
      description: null,
      features: [],
      isActive: 1,
      sortOrder: 0,
    },
  });

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

  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['membership-plans', searchParams],
    queryFn: async () => {
      const res = await membershipPlanClient.$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 }));
    refetch();
  };

  const handleCreatePlan = () => {
    setIsCreateForm(true);
    setEditingPlan(null);
    createForm.reset({
      name: '',
      type: MembershipType.MONTHLY,
      price: 29.99,
      durationDays: 30,
      description: null,
      features: [],
      isActive: 1,
      sortOrder: 0,
    });
    setIsModalOpen(true);
  };

  const handleEditPlan = (plan: MembershipPlanResponse) => {
    setIsCreateForm(false);
    setEditingPlan(plan);
    updateForm.reset({
      name: plan.name,
      type: plan.type,
      price: plan.price,
      durationDays: plan.durationDays,
      description: plan.description,
      features: plan.features,
      isActive: plan.isActive,
      sortOrder: plan.sortOrder,
    });
    setIsModalOpen(true);
  };

  const handleDeletePlan = (id: number) => {
    setPlanToDelete(id);
    setDeleteDialogOpen(true);
  };

  const confirmDelete = async () => {
    if (!planToDelete) return;

    try {
      const res = await membershipPlanClient[':id']['$delete']({
        param: { id: planToDelete.toString() },
      });
      
      if (res.status === 204) {
        toast.success('删除成功');
        setDeleteDialogOpen(false);
        setPlanToDelete(null);
        refetch();
      } else {
        const error = await res.json();
        toast.error(error.message || '删除失败');
      }
    } catch (error) {
      toast.error('删除失败，请重试');
    }
  };

  const handleCreateSubmit = async (data: CreateMembershipPlanRequest) => {
    try {
      const res = await membershipPlanClient.$post({ json: data });
      if (res.status === 201) {
        toast.success('创建成功');
        setIsModalOpen(false);
        refetch();
      } else {
        const error = await res.json();
        toast.error(error.message || '创建失败');
      }
    } catch (error) {
      toast.error('创建失败，请重试');
    }
  };

  const handleUpdateSubmit = async (data: UpdateMembershipPlanRequest) => {
    if (!editingPlan) return;

    try {
      const res = await membershipPlanClient[':id']['$put']({
        param: { id: editingPlan.id.toString() },
        json: data,
      });
      if (res.status === 200) {
        toast.success('更新成功');
        setIsModalOpen(false);
        refetch();
      } else {
        const error = await res.json();
        toast.error(error.message || '更新失败');
      }
    } catch (error) {
      toast.error('更新失败，请重试');
    }
  };

  // 渲染骨架屏
  if (isLoading) {
    return (
      <div className="container mx-auto py-10 space-y-4">
        <div className="flex justify-between items-center">
          <Skeleton className="h-8 w-32" />
          <Skeleton className="h-10 w-32" />
        </div>
        
        <Card>
          <CardHeader>
            <Skeleton className="h-6 w-48" />
            <Skeleton className="h-4 w-64" />
          </CardHeader>
          <CardContent>
            <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 flex-1" />
                  <Skeleton className="h-10 w-20" />
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-10 space-y-4">
      {/* 页面标题区域 */}
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">会员套餐管理</h1>
        <Button onClick={handleCreatePlan}>
          <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((plan) => (
                  <TableRow key={plan.id}>
                    <TableCell className="font-medium">{plan.name}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{typeLabels[plan.type]}</Badge>
                    </TableCell>
                    <TableCell>¥{plan.price.toFixed(2)}</TableCell>
                    <TableCell>
                      {plan.durationDays === 0 ? (
                        <Badge variant="default">永久</Badge>
                      ) : (
                        `${plan.durationDays}天`
                      )}
                    </TableCell>
                    <TableCell>
                      <Badge variant={plan.isActive === 1 ? 'default' : 'secondary'}>
                        {plan.isActive === 1 ? '启用' : '禁用'}
                      </Badge>
                    </TableCell>
                    <TableCell>{plan.sortOrder}</TableCell>
                    <TableCell>
                      {format(new Date(plan.createdAt), 'yyyy-MM-dd HH:mm')}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditPlan(plan)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeletePlan(plan.id)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>

            {data?.data.length === 0 && !isLoading && (
              <div className="text-center py-8">
                <p className="text-muted-foreground">暂无数据</p>
              </div>
            )}
          </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="name"
                  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="type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        套餐类型
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择套餐类型" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value={MembershipType.SINGLE}>单次使用</SelectItem>
                          <SelectItem value={MembershipType.MONTHLY}>单月会员</SelectItem>
                          <SelectItem value={MembershipType.YEARLY}>年度会员</SelectItem>
                          <SelectItem value={MembershipType.LIFETIME}>永久会员</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="price"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        价格（元）
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          min="0"
                          placeholder="请输入价格"
                          {...field}
                          onChange={(e) => field.onChange(parseFloat(e.target.value))}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="durationDays"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        有效期（天）
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="0"
                          placeholder="请输入有效期天数，0表示永久"
                          {...field}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        />
                      </FormControl>
                      <FormDescription>0表示永久有效</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>套餐描述</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入套餐描述"
                          className="resize-none"
                          {...field}
                          value={field.value || ''}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="features"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>套餐功能</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入套餐功能，每行一个功能"
                          className="resize-none"
                          rows={4}
                          value={Array.isArray(field.value) ? field.value.join('\n') : ''}
                          onChange={(e) => {
                            const features = e.target.value
                              .split('\n')
                              .map(f => f.trim())
                              .filter(f => f);
                            field.onChange(features);
                          }}
                        />
                      </FormControl>
                      <FormDescription>每行输入一个功能特性</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="sortOrder"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>排序</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="0"
                          placeholder="请输入排序值"
                          {...field}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        />
                      </FormControl>
                      <FormDescription>数值越小排序越靠前</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={createForm.control}
                  name="isActive"
                  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="name"
                  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="type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        套餐类型
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <Select onValueChange={field.onChange} defaultValue={field.value}>
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue placeholder="选择套餐类型" />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          <SelectItem value={MembershipType.SINGLE}>单次使用</SelectItem>
                          <SelectItem value={MembershipType.MONTHLY}>单月会员</SelectItem>
                          <SelectItem value={MembershipType.YEARLY}>年度会员</SelectItem>
                          <SelectItem value={MembershipType.LIFETIME}>永久会员</SelectItem>
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="price"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        价格（元）
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          step="0.01"
                          min="0"
                          placeholder="请输入价格"
                          {...field}
                          onChange={(e) => field.onChange(parseFloat(e.target.value))}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="durationDays"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="flex items-center">
                        有效期（天）
                        <span className="text-red-500 ml-1">*</span>
                      </FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="0"
                          placeholder="请输入有效期天数，0表示永久"
                          {...field}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        />
                      </FormControl>
                      <FormDescription>0表示永久有效</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>套餐描述</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入套餐描述"
                          className="resize-none"
                          {...field}
                          value={field.value || ''}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="features"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>套餐功能</FormLabel>
                      <FormControl>
                        <Textarea
                          placeholder="请输入套餐功能，每行一个功能"
                          className="resize-none"
                          rows={4}
                          value={Array.isArray(field.value) ? field.value.join('\n') : ''}
                          onChange={(e) => {
                            const features = e.target.value
                              .split('\n')
                              .map(f => f.trim())
                              .filter(f => f);
                            field.onChange(features);
                          }}
                        />
                      </FormControl>
                      <FormDescription>每行输入一个功能特性</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={updateForm.control}
                  name="sortOrder"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>排序</FormLabel>
                      <FormControl>
                        <Input
                          type="number"
                          min="0"
                          placeholder="请输入排序值"
                          {...field}
                          onChange={(e) => field.onChange(parseInt(e.target.value))}
                        />
                      </FormControl>
                      <FormDescription>数值越小排序越靠前</FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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

export default MembershipPlans;