import React from 'react';
import { useQuery, useMutation, useQueryClient } 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 { DataTablePagination } from '../components/DataTablePagination';
import { Plus, Edit, Trash2, Calendar, Search, Filter, Power } from 'lucide-react';
import { useState, useCallback } from 'react';
import { activityClient } from '@/client/api';
import type { InferResponseType, InferRequestType } from 'hono/client';
import { Input } from '@/client/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { Badge } from '@/client/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/client/components/ui/alert-dialog';
import { ActivityForm } from '../components/ActivityForm';
import type { CreateActivityInput, UpdateActivityInput } from '@d8d/server/modules/activities/activity.schema';
import { LocationSelect } from '../components/LocationSelect';

// 类型提取规范
type ActivityResponse = InferResponseType<typeof activityClient.$get, 200>['data'][0];
type CreateActivityRequest = InferRequestType<typeof activityClient.$post>['json'];
type UpdateActivityRequest = InferRequestType<typeof activityClient[':id']['$put']>['json'];

// 统一操作处理函数
const handleOperation = async (operation: () => Promise<any>) => {
  try {
    await operation();
    // toast.success('操作成功');
    console.log('操作成功');
  } catch (error) {
    console.error('操作失败:', error);
    // toast.error('操作失败，请重试');
    throw error;
  }
};

// 防抖搜索函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout;
  return (...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
};

export const ActivitiesPage: React.FC = () => {
  const queryClient = useQueryClient();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [keyword, setKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [locationFilter, setLocationFilter] = useState<number | undefined>(undefined);
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingActivity, setEditingActivity] = useState<ActivityResponse | null>(null);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [activityToDelete, setActivityToDelete] = useState<ActivityResponse | null>(null);
  const [statusConfirmOpen, setStatusConfirmOpen] = useState(false);
  const [activityToToggle, setActivityToToggle] = useState<ActivityResponse | null>(null);

  // 防抖搜索
  const debouncedSearch = useCallback(
    debounce((searchKeyword: string) => {
      setKeyword(searchKeyword);
      setPage(1); // 搜索时重置到第一页
    }, 300),
    []
  );

  // 获取活动列表 - 使用RPC客户端
  const { data, isLoading, error } = useQuery({
    queryKey: ['activities', page, pageSize, keyword, typeFilter, locationFilter],
    queryFn: async () => {
      const query: any = {
        page,
        pageSize
      };

      if (keyword) {
        query.keyword = keyword;
      }

      const filters: any = {};
      if (typeFilter !== 'all') {
        filters.type = typeFilter;
      }
      if (locationFilter) {
        filters.venueLocationId = locationFilter;
      }

      if (Object.keys(filters).length > 0) {
        query.filters = JSON.stringify(filters);
      }

      const res = await activityClient.$get({
        query
      });
      if (res.status !== 200) throw new Error('获取活动列表失败');
      return await res.json();
    },
    staleTime: 5 * 60 * 1000,  // 5分钟缓存
  });

  // 创建活动 - 使用RPC客户端
  const createMutation = useMutation({
    mutationFn: async (data: CreateActivityRequest) => {
      await handleOperation(async () => {
        const res = await activityClient.$post({ json: data });
        if (res.status !== 201) throw new Error('创建活动失败');
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['activities'] });
      setIsFormOpen(false);
    },
  });

  // 更新活动 - 使用RPC客户端
  const updateMutation = useMutation({
    mutationFn: async ({ id, data }: { id: number; data: UpdateActivityRequest }) => {
      await handleOperation(async () => {
        const res = await activityClient[':id'].$put({
          param: { id },
          json: data
        });
        if (res.status !== 200) throw new Error('更新活动失败');
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['activities'] });
      setIsFormOpen(false);
      setEditingActivity(null);
    },
  });

  // 启用/禁用活动 - 使用RPC客户端
  const toggleStatusMutation = useMutation({
    mutationFn: async ({ id, isDisabled }: { id: number; isDisabled: number }) => {
      await handleOperation(async () => {
        const res = await activityClient[':id'].$put({
          param: { id },
          json: { isDisabled }
        });
        if (res.status !== 200) throw new Error('更新活动状态失败');
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['activities'] });
    },
  });

  // 删除活动 - 使用RPC客户端
  const deleteMutation = useMutation({
    mutationFn: async (id: number) => {
      await handleOperation(async () => {
        const res = await activityClient[':id'].$delete({
          param: { id }
        });
        if (res.status !== 204) throw new Error('删除活动失败');
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['activities'] });
    },
  });

  // 处理表单提交
  const handleFormSubmit = async (data: CreateActivityInput | UpdateActivityInput) => {
    if (editingActivity) {
      await updateMutation.mutateAsync({
        id: editingActivity.id,
        data: data as UpdateActivityRequest
      });
    } else {
      await createMutation.mutateAsync(data as CreateActivityRequest);
    }
  };

  // 打开创建表单
  const handleCreate = () => {
    setEditingActivity(null);
    setIsFormOpen(true);
  };

  // 打开编辑表单
  const handleEdit = (activity: ActivityResponse) => {
    setEditingActivity(activity);
    setIsFormOpen(true);
  };

  // 关闭表单
  const handleFormClose = () => {
    setIsFormOpen(false);
    setEditingActivity(null);
  };

  // 切换活动状态
  const handleToggleStatus = (activity: ActivityResponse) => {
    setActivityToToggle(activity);
    setStatusConfirmOpen(true);
  };


  if (error) {
    return (
      <div className="p-6">
        <Card>
          <CardContent className="pt-6">
            <div className="text-center text-red-500">
              加载活动数据失败: {error.message}
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold tracking-tight" data-testid="activity-management-title">活动管理</h1>
          <p className="text-muted-foreground">
            管理旅行活动，包括去程和返程活动
          </p>
        </div>
        <Button onClick={handleCreate} data-testid="create-activity-button">
          <Plus className="h-4 w-4 mr-2" />
          新建活动
        </Button>
      </div>

      <Card>
        <CardHeader>
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div>
              <CardTitle>活动列表</CardTitle>
              <CardDescription>
                当前共有 {data?.pagination.total || 0} 个活动
              </CardDescription>
            </div>
            <div className="flex gap-2">
              {/* 搜索框 */}
              <div className="relative w-full sm:w-64">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索活动名称或描述..."
                  className="pl-8"
                  onChange={(e) => debouncedSearch(e.target.value)}
                  data-testid="activity-search-input"
                />
              </div>
              {/* 类型筛选 */}
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger className="w-32" data-testid="activity-type-filter">
                  <Filter className="h-4 w-4 mr-2" />
                  <SelectValue placeholder="类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="departure">去程</SelectItem>
                  <SelectItem value="return">返程</SelectItem>
                </SelectContent>
              </Select>
              {/* 地点筛选 */}
              <LocationSelect
                value={locationFilter}
                onValueChange={setLocationFilter}
                placeholder="选择地点..."
              />
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {/* 筛选标签 */}
          {(keyword || typeFilter !== 'all' || locationFilter) && (
            <div className="flex flex-wrap gap-2 mb-4">
              {keyword && (
                <Badge variant="secondary" className="flex items-center gap-1">
                  搜索: {keyword}
                  <button
                    onClick={() => {
                      setKeyword('');
                      const input = document.querySelector('input[placeholder="搜索活动名称或描述..."]') as HTMLInputElement;
                      if (input) input.value = '';
                    }}
                    className="ml-1 hover:text-red-500"
                  >
                    ×
                  </button>
                </Badge>
              )}
              {typeFilter !== 'all' && (
                <Badge variant="secondary" className="flex items-center gap-1">
                  类型: {typeFilter === 'departure' ? '去程' : '返程'}
                  <button
                    onClick={() => setTypeFilter('all')}
                    className="ml-1 hover:text-red-500"
                  >
                    ×
                  </button>
                </Badge>
              )}
              {locationFilter && (
                <Badge variant="secondary" className="flex items-center gap-1">
                  地点: {data?.data?.find((a: ActivityResponse) => a.venueLocationId === locationFilter)?.venueLocation?.name || '未知地点'}
                  <button
                    onClick={() => setLocationFilter(undefined)}
                    className="ml-1 hover:text-red-500"
                  >
                    ×
                  </button>
                </Badge>
              )}
            </div>
          )}

          <div className="rounded-md border">
            <Table data-testid="activity-table">
              <TableHeader>
                <TableRow>
                  <TableHead>活动名称</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>举办地点</TableHead>
                  <TableHead>开始时间</TableHead>
                  <TableHead>结束时间</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-4">
                      加载中...
                    </TableCell>
                  </TableRow>
                ) : data?.data && data.data.length > 0 ? (
                  data.data.map((activity: ActivityResponse) => (
                    <TableRow key={activity.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <Calendar className="h-4 w-4 text-blue-500" />
                          <span>{activity.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <span className={`px-2 py-1 rounded-full text-xs ${
                          activity.type === 'departure'
                            ? 'bg-blue-100 text-blue-800'
                            : 'bg-green-100 text-green-800'
                        }`}>
                          {activity.type === 'departure' ? '去程' : '返程'}
                        </span>
                      </TableCell>
                      <TableCell>
                        {activity.venueLocation ? (
                          <div className="flex flex-col">
                            <span className="font-medium">{activity.venueLocation.name}</span>
                            <span className="text-xs text-muted-foreground">
                              {activity.venueLocation.address}
                            </span>
                          </div>
                        ) : (
                          <span className="text-muted-foreground">未设置地点</span>
                        )}
                      </TableCell>
                      <TableCell>
                        {new Date(activity.startDate).toLocaleString('zh-CN')}
                      </TableCell>
                      <TableCell>
                        {new Date(activity.endDate).toLocaleString('zh-CN')}
                      </TableCell>
                      <TableCell>
                        <span className={`px-2 py-1 rounded-full text-xs ${
                          activity.isDisabled === 0
                            ? 'bg-green-100 text-green-800'
                            : 'bg-red-100 text-red-800'
                        }`}>
                          {activity.isDisabled === 0 ? '启用' : '禁用'}
                        </span>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant={activity.isDisabled === 0 ? "outline" : "default"}
                            size="sm"
                            onClick={() => handleToggleStatus(activity)}
                            disabled={toggleStatusMutation.isPending}
                            data-testid={`toggle-activity-${activity.id}-status`}
                          >
                            <Power className="h-4 w-4 mr-1" />
                            {activity.isDisabled === 0 ? '禁用' : '启用'}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleEdit(activity)}
                            data-testid={`edit-activity-${activity.id}`}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="destructive"
                            size="sm"
                            onClick={() => {
                              setActivityToDelete(activity);
                              setDeleteConfirmOpen(true);
                            }}
                            data-testid={`delete-activity-${activity.id}`}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={7} className="text-center py-4">
                      暂无活动数据
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
          {data && (
            <DataTablePagination
              currentPage={data.pagination.current}
              totalCount={data.pagination.total}
              pageSize={data.pagination.pageSize}
              onPageChange={(page, pageSize) => {
                setPage(page);
                setPageSize(pageSize);
              }}
            />
          )}
        </CardContent>
      </Card>

      {/* 活动表单对话框 */}
      <Dialog open={isFormOpen} onOpenChange={setIsFormOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingActivity ? '编辑活动' : '创建活动'}
            </DialogTitle>
            <DialogDescription>
              {editingActivity ? '修改活动信息' : '创建新的旅行活动'}
            </DialogDescription>
          </DialogHeader>
          <ActivityForm
            initialData={editingActivity ? {
              id: editingActivity.id,
              name: editingActivity.name,
              description: editingActivity.description,
              type: editingActivity.type,
              startDate: new Date(editingActivity.startDate),
              endDate: new Date(editingActivity.endDate),
              isDisabled: editingActivity.isDisabled
            } : undefined}
            onSubmit={handleFormSubmit}
            onCancel={handleFormClose}
            isLoading={createMutation.isPending || updateMutation.isPending}
          />
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog open={deleteConfirmOpen} onOpenChange={setDeleteConfirmOpen}>
        <AlertDialogContent data-testid="delete-confirm-dialog">
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除活动 "{activityToDelete?.name}" 吗？此操作不可撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                if (activityToDelete) {
                  deleteMutation.mutate(activityToDelete.id);
                }
                setDeleteConfirmOpen(false);
                setActivityToDelete(null);
              }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 启用/禁用确认对话框 */}
      <AlertDialog open={statusConfirmOpen} onOpenChange={setStatusConfirmOpen}>
        <AlertDialogContent data-testid="status-confirm-dialog">
          <AlertDialogHeader>
            <AlertDialogTitle>确认状态切换</AlertDialogTitle>
            <AlertDialogDescription>
              确定要{activityToToggle?.isDisabled === 0 ? '禁用' : '启用'}活动 "{activityToToggle?.name}" 吗？
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                if (activityToToggle) {
                  const newStatus = activityToToggle.isDisabled === 0 ? 1 : 0;
                  toggleStatusMutation.mutate({
                    id: activityToToggle.id,
                    isDisabled: newStatus
                  });
                }
                setStatusConfirmOpen(false);
                setActivityToToggle(null);
              }}
            >
              {activityToToggle?.isDisabled === 0 ? '禁用' : '启用'}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};