import React, { useState } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Plus, Edit, Trash2, Search } from 'lucide-react';
import { format } from 'date-fns';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@d8d/shared-ui-components/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@d8d/shared-ui-components/components/ui/table';
import { Skeleton } from '@d8d/shared-ui-components/components/ui/skeleton';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { toast } from 'sonner';
import { DataTablePagination } from '@d8d/shared-ui-components/components/admin/DataTablePagination';
import { channelClientManager } from '../api/channelClient';
import { CreateChannelSchema, UpdateChannelSchema } from '@d8d/allin-channel-module/schemas';
import type { CreateChannelDto, UpdateChannelDto } from '@d8d/allin-channel-module/schemas';
import type { ChannelListItem } from '../types';

interface ChannelSearchParams {
  page: number;
  limit: number;
  search: string;
}

const ChannelManagement: React.FC = () => {
  const [searchParams, setSearchParams] = useState<ChannelSearchParams>({ page: 1, limit: 10, search: '' });
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isCreateForm, setIsCreateForm] = useState(true);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [channelToDelete, setChannelToDelete] = useState<number | null>(null);

  // 表单实例
  const createForm = useForm<CreateChannelDto>({
    resolver: zodResolver(CreateChannelSchema),
    defaultValues: {
      channelName: '',
      channelType: '',
      contactPerson: '',
      contactPhone: '',
      description: ''
    }
  });

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

  // 数据查询
  const { data, isLoading, refetch } = useQuery({
    queryKey: ['channels', searchParams],
    queryFn: async () => {
      const res = await channelClientManager.get().getAllChannels.$get({
        query: {
          skip: (searchParams.page - 1) * searchParams.limit,
          take: searchParams.limit
        }
      });
      if (res.status !== 200) throw new Error('获取渠道列表失败');
      return await res.json();
    },
    initialData: {
      data: [],
      total: 0
    }
  });

  // 创建渠道
  const createMutation = useMutation({
    mutationFn: async (data: CreateChannelDto) => {
      const res = await channelClientManager.get().createChannel.$post({ json: data });
      if (res.status !== 200) 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 (data: UpdateChannelDto) => {
      const res = await channelClientManager.get().updateChannel.$post({
        json: data
      });
      if (res.status !== 200) throw new Error('更新渠道失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('渠道更新成功');
      setIsModalOpen(false);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '更新渠道失败');
    }
  });

  // 删除渠道
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      const res = await channelClientManager.get().deleteChannel.$post({
        json: { id }
      });
      if (res.status !== 200) throw new Error('删除渠道失败');
      return await res.json();
    },
    onSuccess: () => {
      toast.success('渠道删除成功');
      setDeleteDialogOpen(false);
      setChannelToDelete(null);
      refetch();
    },
    onError: (error) => {
      toast.error(error instanceof Error ? error.message : '删除渠道失败');
    }
  });

  // 处理搜索
  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    if (searchParams.search.trim()) {
      // 如果有搜索关键词，使用搜索接口
      const searchQuery = async () => {
        const res = await channelClientManager.get().searchChannels.$get({
          query: {
            name: searchParams.search,
            skip: 0,
            take: searchParams.limit
          }
        });
        if (res.status !== 200) throw new Error('搜索渠道失败');
        return await res.json();
      };
      searchQuery().then(() => {
        // 暂时使用refetch，实际应该更新数据
        refetch();
      }).catch(error => {
        toast.error(error instanceof Error ? error.message : '搜索失败');
      });
    } else {
      // 没有搜索关键词，使用普通列表接口
      setSearchParams(prev => ({ ...prev, page: 1 }));
      refetch();
    }
  };

  // 处理创建渠道
  const handleCreateChannel = () => {
    setIsCreateForm(true);
    createForm.reset();
    setIsModalOpen(true);
  };

  // 处理编辑渠道
  const handleEditChannel = (channel: ChannelListItem) => {
    setIsCreateForm(false);
    updateForm.reset({
      id: channel.id,
      channelName: channel.channelName || undefined,
      channelType: channel.channelType || undefined,
      contactPerson: channel.contactPerson || undefined,
      contactPhone: channel.contactPhone || undefined,
      description: channel.description || undefined
    });
    setIsModalOpen(true);
  };

  // 处理删除渠道
  const handleDeleteChannel = (id: number) => {
    setChannelToDelete(id);
    setDeleteDialogOpen(true);
  };

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

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

  // 处理编辑表单提交
  const handleUpdateSubmit = async (data: UpdateChannelDto) => {
    try {
      await updateMutation.mutateAsync(data);
    } catch (error) {
      throw error;
    }
  };

  // 日期格式化函数
  const formatDate = (dateString: string): string => {
    if (!dateString) return '';
    try {
      const date = new Date(dateString);
      if (isNaN(date.getTime())) return dateString;
      return format(date, 'yyyy-MM-dd HH:mm');
    } catch (error) {
      return dateString;
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">渠道管理</h1>
        <Button onClick={handleCreateChannel} data-testid="create-channel-button">
          <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"
                  data-testid="search-input"
                />
              </div>
              <Button type="submit" variant="outline" data-testid="search-button">
                搜索
              </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>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  Array.from({ length: 5 }).map((_, index) => (
                    <TableRow key={index}>
                      <TableCell><Skeleton className="h-4 w-12" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-32" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-20" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-20" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-24" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-32" /></TableCell>
                      <TableCell><Skeleton className="h-4 w-20" /></TableCell>
                    </TableRow>
                  ))
                ) : data?.data?.length ? (
                  data.data.map((channel) => (
                    <TableRow key={channel.id}>
                      <TableCell>{channel.id}</TableCell>
                      <TableCell>{channel.channelName}</TableCell>
                      <TableCell>{channel.channelType || '-'}</TableCell>
                      <TableCell>{channel.contactPerson || '-'}</TableCell>
                      <TableCell>{channel.contactPhone || '-'}</TableCell>
                      <TableCell>{formatDate(channel.createTime)}</TableCell>
                      <TableCell>
                        <div className="flex gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleEditChannel(channel)}
                            data-testid={`edit-channel-${channel.id}`}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleDeleteChannel(channel.id)}
                            data-testid={`delete-channel-${channel.id}`}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
                      暂无数据
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>

          { data.total > 0 && (
            <div className="mt-4">
              <DataTablePagination
                currentPage={searchParams.page}
                pageSize={searchParams.limit}
                totalCount={data.total}
                onPageChange={(page, pageSize) => setSearchParams(prev => ({ ...prev, page, limit: pageSize }))}
              />
            </div>
          )}
        </CardContent>
      </Card>

      {/* 创建/编辑渠道对话框 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle data-testid="create-channel-modal-title">{isCreateForm ? '创建渠道' : '编辑渠道'}</DialogTitle>
            <DialogDescription>
              {isCreateForm ? '填写渠道信息以创建新渠道' : '修改渠道信息'}
            </DialogDescription>
          </DialogHeader>
          {isCreateForm ? (
            <Form {...createForm}>
              <form onSubmit={createForm.handleSubmit(handleCreateSubmit)} className="space-y-4">
                <FormField
                  control={createForm.control}
                  name="channelName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>渠道名称 *</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入渠道名称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="channelType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>渠道类型</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入渠道类型" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="contactPerson"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系人姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="contactPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系电话</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系电话" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={createForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>描述</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入渠道描述" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <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="id"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>渠道ID</FormLabel>
                      <FormControl>
                        <Input {...field} disabled />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="channelName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>渠道名称 *</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入渠道名称" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="channelType"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>渠道类型</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入渠道类型" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="contactPerson"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系人</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系人姓名" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="contactPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>联系电话</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入联系电话" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={updateForm.control}
                  name="description"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>描述</FormLabel>
                      <FormControl>
                        <Input placeholder="请输入渠道描述" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <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 data-testid="delete-confirm-dialog-title">确认删除</DialogTitle>
            <DialogDescription>
              确定要删除这个渠道吗？此操作不可撤销。
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button variant="destructive" onClick={confirmDelete} disabled={deleteMutation.isPending}>
              确认删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default ChannelManagement;