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, MapPin, DollarSign, Users, Search, Filter, Power } from 'lucide-react';
import { useState, useCallback } from 'react';
import { routeClient } 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 { RouteForm } from '../components/RouteForm';
import type { CreateRouteInput, UpdateRouteInput } from '@/server/modules/routes/route.schema';

// 类型提取规范
type RouteResponse = InferResponseType<typeof routeClient.$get, 200>['data'][0];
type CreateRouteRequest = InferRequestType<typeof routeClient.$post>['json'];
type UpdateRouteRequest = InferRequestType<typeof routeClient[':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 RoutesPage: React.FC = () => {
  const queryClient = useQueryClient();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [keyword, setKeyword] = useState('');
  const [vehicleTypeFilter, setVehicleTypeFilter] = useState<string>('all');
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingRoute, setEditingRoute] = useState<RouteResponse | null>(null);

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

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

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

      if (vehicleTypeFilter !== 'all') {
        query.filters = JSON.stringify({ vehicleType: vehicleTypeFilter });
      }

      const res = await routeClient.$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: CreateRouteRequest) => {
      await handleOperation(async () => {
        const res = await routeClient.$post({ json: data });
        if (res.status !== 201) throw new Error('创建路线失败');
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['routes'] });
      setIsFormOpen(false);
    },
  });

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

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

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

  // 处理表单提交
  const handleFormSubmit = async (data: CreateRouteInput | UpdateRouteInput) => {
    if (editingRoute) {
      await updateMutation.mutateAsync({
        id: editingRoute.id,
        data: data as UpdateRouteRequest
      });
    } else {
      await createMutation.mutateAsync(data as CreateRouteRequest);
    }
  };

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

  // 打开编辑表单
  const handleEdit = (route: RouteResponse) => {
    setEditingRoute(route);
    setIsFormOpen(true);
  };

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

  // 切换路线状态
  const handleToggleStatus = (route: RouteResponse) => {
    const newStatus = route.isDisabled === 0 ? 1 : 0;
    const statusText = newStatus === 0 ? '启用' : '禁用';

    if (confirm(`确定要${statusText}这条路线吗？`)) {
      toggleStatusMutation.mutate({
        id: route.id,
        isDisabled: newStatus
      });
    }
  };


  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="route-management-title">路线管理</h1>
          <p className="text-muted-foreground">
            管理旅行路线，包括出发地、目的地、车型和价格等信息
          </p>
        </div>
        <Button onClick={handleCreate} data-testid="create-route-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="route-search-input"
                />
              </div>
              {/* 车型筛选 */}
              <Select value={vehicleTypeFilter} onValueChange={setVehicleTypeFilter}>
                <SelectTrigger className="w-32" data-testid="route-vehicle-type-filter">
                  <Filter className="h-4 w-4 mr-2" />
                  <SelectValue placeholder="车型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部车型</SelectItem>
                  <SelectItem value="bus">大巴</SelectItem>
                  <SelectItem value="minibus">中巴</SelectItem>
                  <SelectItem value="car">小车</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          {/* 筛选标签 */}
          {(keyword || vehicleTypeFilter !== 'all') && (
            <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>
              )}
              {vehicleTypeFilter !== 'all' && (
                <Badge variant="secondary" className="flex items-center gap-1">
                  车型: {vehicleTypeFilter === 'bus' ? '大巴' : vehicleTypeFilter === 'minibus' ? '中巴' : '小车'}
                  <button
                    onClick={() => setVehicleTypeFilter('all')}
                    className="ml-1 hover:text-red-500"
                  >
                    ×
                  </button>
                </Badge>
              )}
            </div>
          )}

          <div className="rounded-md border">
            <Table data-testid="route-table">
              <TableHeader>
                <TableRow>
                  <TableHead>路线名称</TableHead>
                  <TableHead>出发地</TableHead>
                  <TableHead>目的地</TableHead>
                  <TableHead>车型</TableHead>
                  <TableHead>价格</TableHead>
                  <TableHead>可用座位</TableHead>
                  <TableHead>出发时间</TableHead>
                  <TableHead>关联活动</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={10} className="text-center py-4">
                      加载中...
                    </TableCell>
                  </TableRow>
                ) : data?.data && data.data.length > 0 ? (
                  data.data.map((route: RouteResponse) => (
                    <TableRow key={route.id}>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          <MapPin className="h-4 w-4 text-blue-500" />
                          <span>{route.name}</span>
                        </div>
                      </TableCell>
                      <TableCell>{route.startPoint}</TableCell>
                      <TableCell>{route.endPoint}</TableCell>
                      <TableCell>
                        <span className="px-2 py-1 rounded-full text-xs bg-blue-100 text-blue-800">
                          {route.vehicleType}
                        </span>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <DollarSign className="h-3 w-3 text-green-600" />
                          <span>¥{route.price}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-1">
                          <Users className="h-3 w-3 text-blue-600" />
                          <span>
                            {route.availableSeats}/{route.seatCount}
                          </span>
                        </div>
                      </TableCell>
                      <TableCell>
                        {new Date(route.departureTime).toLocaleString('zh-CN')}
                      </TableCell>
                      <TableCell>
                        {route.activity ? (
                          <span className="text-sm text-muted-foreground">
                            {route.activity.name}
                          </span>
                        ) : (
                          <span className="text-sm text-gray-400">未关联</span>
                        )}
                      </TableCell>
                      <TableCell>
                        <span className={`px-2 py-1 rounded-full text-xs ${
                          route.isDisabled === 0
                            ? 'bg-green-100 text-green-800'
                            : 'bg-red-100 text-red-800'
                        }`}>
                          {route.isDisabled === 0 ? '启用' : '禁用'}
                        </span>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant={route.isDisabled === 0 ? "outline" : "default"}
                            size="sm"
                            onClick={() => handleToggleStatus(route)}
                            disabled={toggleStatusMutation.isPending}
                            data-testid={`toggle-route-${route.id}-status`}
                          >
                            <Power className="h-4 w-4 mr-1" />
                            {route.isDisabled === 0 ? '禁用' : '启用'}
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleEdit(route)}
                            data-testid={`edit-route-${route.id}`}
                          >
                            <Edit className="h-4 w-4" />
                          </Button>
                          <Button
                            variant="destructive"
                            size="sm"
                            onClick={() => {
                              if (confirm('确定要删除这条路线吗？')) {
                                deleteMutation.mutate(route.id);
                              }
                            }}
                            data-testid={`delete-route-${route.id}`}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={9} 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>
              {editingRoute ? '编辑路线' : '创建路线'}
            </DialogTitle>
            <DialogDescription>
              {editingRoute ? '修改路线信息' : '创建新的旅行路线'}
            </DialogDescription>
          </DialogHeader>
          <RouteForm
            initialData={editingRoute ? {
              id: editingRoute.id,
              name: editingRoute.name,
              description: editingRoute.description,
              startPoint: editingRoute.startPoint,
              endPoint: editingRoute.endPoint,
              pickupPoint: editingRoute.pickupPoint,
              dropoffPoint: editingRoute.dropoffPoint,
              departureTime: editingRoute.departureTime,
              vehicleType: editingRoute.vehicleType,
              price: editingRoute.price,
              seatCount: editingRoute.seatCount,
              availableSeats: editingRoute.availableSeats,
              activityId: editingRoute.activityId,
              isDisabled: editingRoute.isDisabled
            } : undefined}
            onSubmit={handleFormSubmit}
            onCancel={handleFormClose}
            isLoading={createMutation.isPending || updateMutation.isPending}
          />
        </DialogContent>
      </Dialog>
    </div>
  );
};