import React, { useState, useMemo, useCallback } from 'react';
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import { Search, Filter, X, Eye } from 'lucide-react';
import { orderClient } from '@/client/api';
import type { InferResponseType } from 'hono/client';
import { Button } from '@/client/components/ui/button';
import { Input } from '@/client/components/ui/input';
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 { DataTablePagination } from '@/client/admin/components/DataTablePagination';
import { Skeleton } from '@/client/components/ui/skeleton';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/client/components/ui/select';
import { OrderStatus, PaymentStatus } from '@d8d/server/share/order.types';

// 使用RPC方式提取类型
type OrderResponse = InferResponseType<typeof orderClient.$get, 200>['data'][0];

export const OrdersPage = () => {
  const [searchParams, setSearchParams] = useState({
    page: 1,
    pageSize: 10,
    search: ''
  });
  const [filters, setFilters] = useState({
    status: undefined as OrderStatus | undefined,
    paymentStatus: undefined as PaymentStatus | undefined
  });
  const [showFilters, setShowFilters] = useState(false);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<OrderResponse | null>(null);

  // 获取订单列表
  const { data: ordersData, isLoading } = useQuery({
    queryKey: ['orders', searchParams, filters],
    queryFn: async () => {
      const res = await orderClient.$get({
        query: {
          page: searchParams.page,
          pageSize: searchParams.pageSize,
          keyword: searchParams.search,
          filters: JSON.stringify({
            status: filters.status,
            paymentStatus: filters.paymentStatus
          })
        }
      });
      if (res.status !== 200) {
        throw new Error('获取订单列表失败');
      }
      return await res.json();
    }
  });

  // 获取订单统计
  const { data: statsData } = useQuery({
    queryKey: ['order-stats'],
    queryFn: async () => {
      const res = await orderClient.stats.$get();
      if (res.status !== 200) {
        throw new Error('获取订单统计失败');
      }
      return await res.json();
    }
  });

  const orders = ordersData?.data || [];
  const totalCount = ordersData?.pagination?.total || 0;
  const stats = statsData || {
    total: 0,
    pendingPayment: 0,
    waitingDeparture: 0,
    inProgress: 0,
    completed: 0,
    cancelled: 0
  };

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

  // 使用useCallback包装防抖搜索
  const debouncedSearch = useCallback(
    debounce((search: string) => {
      setSearchParams(prev => ({ ...prev, search, page: 1 }));
    }, 300),
    []
  );

  // 处理搜索输入变化
  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const search = e.target.value;
    setSearchParams(prev => ({ ...prev, search }));
    debouncedSearch(search);
  };

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

  // 处理分页
  const handlePageChange = (page: number, pageSize: number) => {
    setSearchParams(prev => ({ ...prev, page, pageSize }));
  };

  // 处理过滤条件变化
  const handleFilterChange = (newFilters: Partial<typeof filters>) => {
    setFilters(prev => ({ ...prev, ...newFilters }));
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 重置所有过滤条件
  const resetFilters = () => {
    setFilters({
      status: undefined,
      paymentStatus: undefined
    });
    setSearchParams(prev => ({ ...prev, page: 1 }));
  };

  // 检查是否有活跃的过滤条件
  const hasActiveFilters = useMemo(() => {
    return filters.status !== undefined || filters.paymentStatus !== undefined;
  }, [filters]);

  // 打开订单详情对话框
  const handleViewOrder = (order: OrderResponse) => {
    setSelectedOrder(order);
    setDetailDialogOpen(true);
  };

  // 获取订单状态对应的颜色
  const getStatusColor = (status: OrderStatus) => {
    switch (status) {
      case OrderStatus.PENDING_PAYMENT:
        return 'secondary';
      case OrderStatus.WAITING_DEPARTURE:
        return 'default';
      case OrderStatus.IN_PROGRESS:
        return 'default';
      case OrderStatus.COMPLETED:
        return 'default';
      case OrderStatus.CANCELLED:
        return 'destructive';
      default:
        return 'default';
    }
  };

  // 获取支付状态对应的颜色
  const getPaymentStatusColor = (status: PaymentStatus) => {
    switch (status) {
      case PaymentStatus.PENDING:
        return 'secondary';
      case PaymentStatus.PAID:
        return 'default';
      case PaymentStatus.FAILED:
        return 'destructive';
      case PaymentStatus.REFUNDED:
        return 'secondary';
      default:
        return 'default';
    }
  };

  // 渲染表格部分的骨架屏
  const renderTableSkeleton = () => (
    <div className="space-y-2">
      {Array.from({ length: 5 }).map((_, index) => (
        <div key={index} className="flex space-x-4">
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 flex-1" />
          <Skeleton className="h-4 w-16" />
        </div>
      ))}
    </div>
  );

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h1 className="text-2xl font-bold">订单管理</h1>
      </div>

      {/* 订单统计面板 */}
      <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
        <Card data-testid="total-orders-card">
          <CardHeader className="p-4">
            <CardTitle className="text-sm font-medium">总订单数</CardTitle>
            <CardDescription className="text-2xl font-bold" data-testid="total-orders-count">{stats.total}</CardDescription>
          </CardHeader>
        </Card>
        <Card data-testid="pending-payment-card">
          <CardHeader className="p-4">
            <CardTitle className="text-sm font-medium">待支付</CardTitle>
            <CardDescription className="text-2xl font-bold" data-testid="pending-payment-count">{stats.pendingPayment}</CardDescription>
          </CardHeader>
        </Card>
        <Card data-testid="waiting-departure-card">
          <CardHeader className="p-4">
            <CardTitle className="text-sm font-medium">待出发</CardTitle>
            <CardDescription className="text-2xl font-bold" data-testid="waiting-departure-count">{stats.waitingDeparture}</CardDescription>
          </CardHeader>
        </Card>
        <Card data-testid="in-progress-card">
          <CardHeader className="p-4">
            <CardTitle className="text-sm font-medium">行程中</CardTitle>
            <CardDescription className="text-2xl font-bold" data-testid="in-progress-count">{stats.inProgress}</CardDescription>
          </CardHeader>
        </Card>
        <Card data-testid="completed-card">
          <CardHeader className="p-4">
            <CardTitle className="text-sm font-medium">已完成</CardTitle>
            <CardDescription className="text-2xl font-bold" data-testid="completed-count">{stats.completed}</CardDescription>
          </CardHeader>
        </Card>
        <Card data-testid="cancelled-card">
          <CardHeader className="p-4">
            <CardTitle className="text-sm font-medium">已取消</CardTitle>
            <CardDescription className="text-2xl font-bold" data-testid="cancelled-count">{stats.cancelled}</CardDescription>
          </CardHeader>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle>订单列表</CardTitle>
          <CardDescription>
            管理系统中的所有订单，共 {totalCount} 个订单
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="mb-4 space-y-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={handleSearchChange}
                  className="pl-8"
                />
              </div>
              <Button type="submit" variant="outline">
                搜索
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={() => setShowFilters(!showFilters)}
                className="flex items-center gap-2"
              >
                <Filter className="h-4 w-4" />
                高级筛选
                {hasActiveFilters && (
                  <Badge variant="secondary" className="ml-1">
                    {Object.values(filters).filter(v => v !== undefined).length}
                  </Badge>
                )}
              </Button>
              {hasActiveFilters && (
                <Button
                  type="button"
                  variant="ghost"
                  onClick={resetFilters}
                  className="flex items-center gap-2"
                >
                  <X className="h-4 w-4" />
                  重置
                </Button>
              )}
            </form>

            {showFilters && (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 p-4 border rounded-lg bg-muted/50">
                {/* 订单状态筛选 */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">订单状态</label>
                  <Select
                    value={filters.status || 'all'}
                    onValueChange={(value) =>
                      handleFilterChange({
                        status: value === 'all' ? undefined : value as OrderStatus
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择订单状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">全部状态</SelectItem>
                      <SelectItem value={OrderStatus.PENDING_PAYMENT}>待支付</SelectItem>
                      <SelectItem value={OrderStatus.WAITING_DEPARTURE}>待出发</SelectItem>
                      <SelectItem value={OrderStatus.IN_PROGRESS}>行程中</SelectItem>
                      <SelectItem value={OrderStatus.COMPLETED}>已完成</SelectItem>
                      <SelectItem value={OrderStatus.CANCELLED}>已取消</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                {/* 支付状态筛选 */}
                <div className="space-y-2">
                  <label className="text-sm font-medium">支付状态</label>
                  <Select
                    value={filters.paymentStatus || 'all'}
                    onValueChange={(value) =>
                      handleFilterChange({
                        paymentStatus: value === 'all' ? undefined : value as PaymentStatus
                      })
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择支付状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">全部状态</SelectItem>
                      <SelectItem value={PaymentStatus.PENDING}>待支付</SelectItem>
                      <SelectItem value={PaymentStatus.PAID}>已支付</SelectItem>
                      <SelectItem value={PaymentStatus.FAILED}>支付失败</SelectItem>
                      <SelectItem value={PaymentStatus.REFUNDED}>已退款</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}

            {/* 过滤条件标签 */}
            {hasActiveFilters && (
              <div className="flex flex-wrap gap-2">
                {filters.status && (
                  <Badge variant="secondary" className="flex items-center gap-1">
                    订单状态: {filters.status}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => handleFilterChange({ status: undefined })}
                    />
                  </Badge>
                )}
                {filters.paymentStatus && (
                  <Badge variant="secondary" className="flex items-center gap-1">
                    支付状态: {filters.paymentStatus}
                    <X
                      className="h-3 w-3 cursor-pointer"
                      onClick={() => handleFilterChange({ paymentStatus: undefined })}
                    />
                  </Badge>
                )}
              </div>
            )}
          </div>

          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <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={9} className="p-4">
                      {renderTableSkeleton()}
                    </TableCell>
                  </TableRow>
                ) : (
                  // 显示实际订单数据
                  orders.map((order) => (
                    <TableRow key={order.id}>
                      <TableCell className="font-medium">#{order.id}</TableCell>
                      <TableCell>
                        {order.user?.username || '未知用户'}
                        {order.user?.phone && ` (${order.user.phone})`}
                      </TableCell>
                      <TableCell>{order.route?.name || '未知路线'}</TableCell>
                      <TableCell>{order.passengerCount}</TableCell>
                      <TableCell>¥{order.totalAmount}</TableCell>
                      <TableCell>
                        <Badge variant={getStatusColor(order.status)}>
                          {order.status}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant={getPaymentStatusColor(order.paymentStatus)}>
                          {order.paymentStatus}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {format(new Date(order.createdAt), 'yyyy-MM-dd HH:mm')}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end gap-2">
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => handleViewOrder(order)}
                          >
                            <Eye className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>

          <DataTablePagination
            currentPage={searchParams.page}
            totalCount={totalCount}
            pageSize={searchParams.pageSize}
            onPageChange={handlePageChange}
          />
        </CardContent>
      </Card>

      {/* 订单详情对话框 */}
      <Dialog open={detailDialogOpen} onOpenChange={setDetailDialogOpen}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>订单详情</DialogTitle>
            <DialogDescription>
              查看订单的详细信息
            </DialogDescription>
          </DialogHeader>

          {selectedOrder && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <h4 className="font-medium">订单信息</h4>
                  <div className="text-sm text-muted-foreground space-y-1 mt-2">
                    <div>订单号: #{selectedOrder.id}</div>
                    <div>订单状态: {selectedOrder.status}</div>
                    <div>支付状态: {selectedOrder.paymentStatus}</div>
                    <div>创建时间: {format(new Date(selectedOrder.createdAt), 'yyyy-MM-dd HH:mm:ss')}</div>
                  </div>
                </div>
                <div>
                  <h4 className="font-medium">用户信息</h4>
                  <div className="text-sm text-muted-foreground space-y-1 mt-2">
                    <div>用户名: {selectedOrder.user?.username || '未知'}</div>
                    <div>手机号: {selectedOrder.user?.phone || '未知'}</div>
                  </div>
                </div>
              </div>

              <div>
                <h4 className="font-medium">路线信息</h4>
                <div className="text-sm text-muted-foreground space-y-1 mt-2">
                  <div>路线名称: {selectedOrder.route?.name || '未知'}</div>
                  <div>路线描述: {selectedOrder.route?.description || '无描述'}</div>
                </div>
              </div>

              <div>
                <h4 className="font-medium">订单详情</h4>
                <div className="text-sm text-muted-foreground space-y-1 mt-2">
                  <div>乘客数量: {selectedOrder.passengerCount}</div>
                  <div>订单金额: ¥{selectedOrder.totalAmount}</div>
                </div>
              </div>

              {selectedOrder.passengerSnapshots && selectedOrder.passengerSnapshots.length > 0 && (
                <div>
                  <h4 className="font-medium">乘客信息</h4>
                  <div className="text-sm text-muted-foreground space-y-1 mt-2">
                    {selectedOrder.passengerSnapshots.map((passenger: any, index: number) => (
                      <div key={index} className="border-b pb-2">
                        <div>乘客 {index + 1}: {passenger.name || '未知'}</div>
                        <div>身份证: {passenger.idNumber || '未知'}</div>
                        <div>手机号: {passenger.phone || '未知'}</div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          <DialogFooter>
            <Button onClick={() => setDetailDialogOpen(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};