import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { useToast } from "@/hooks/use-toast";
import { 
  Eye, 
  DollarSign, 
  CreditCard, 
  CheckCircle2,
  XCircle,
  Clock,
  ArrowUpDown,
  Download,
  Receipt
} from "lucide-react";

interface OrderData {
  id: string;
  order_number: string;
  user_id: string;
  total_amount: number;
  status: string;
  created_at: string;
  updated_at: string;
  profiles?: {
    display_name: string | null;
  } | null;
  order_items: Array<{
    id: string;
    quantity: number;
    unit_price: number;
    products: {
      name: string;
    } | null;
  }>;
}

export function FinanceOrdersView() {
  const [orders, setOrders] = useState<OrderData[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [paymentFilter, setPaymentFilter] = useState("all");
  const [selectedOrder, setSelectedOrder] = useState<OrderData | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [sortConfig, setSortConfig] = useState<{ field: string; direction: 'asc' | 'desc' }>({ 
    field: 'created_at', 
    direction: 'desc' 
  });
  const { toast } = useToast();

  useEffect(() => {
    fetchOrders();
  }, []);

  const fetchOrders = async () => {
    try {
      const { data: ordersData, error: ordersError } = await supabase
        .from("orders")
        .select(`
          *,
          order_items (
            id,
            quantity,
            unit_price,
            products (name)
          )
        `)
        .order("created_at", { ascending: false });

      if (ordersError) throw ordersError;

      const userIds = [...new Set(ordersData?.map(order => order.user_id) || [])];
      const { data: profilesData } = await supabase
        .from("profiles")
        .select("user_id, display_name")
        .in("user_id", userIds);

      const profilesMap = new Map(
        profilesData?.map(profile => [profile.user_id, profile]) || []
      );

      const ordersWithProfiles = ordersData?.map(order => ({
        ...order,
        profiles: profilesMap.get(order.user_id) || null
      })) || [];

      setOrders(ordersWithProfiles);
    } catch (error) {
      console.error("Error fetching orders:", error);
      toast({
        title: "错误",
        description: "获取订单数据失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('zh-CN', {
      style: 'currency',
      currency: 'CNY',
      minimumFractionDigits: 0
    }).format(amount);
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // 财务视角的状态：关注支付和结算
  const getPaymentStatus = (status: string) => {
    switch (status) {
      case "pending":
        return { text: "待支付", variant: "secondary" as const, icon: Clock };
      case "confirmed":
        return { text: "已支付", variant: "default" as const, icon: CheckCircle2 };
      case "shipped":
      case "delivered":
        return { text: "已结算", variant: "outline" as const, icon: CreditCard };
      case "cancelled":
        return { text: "已退款", variant: "destructive" as const, icon: XCircle };
      default:
        return { text: status, variant: "secondary" as const, icon: Clock };
    }
  };

  const sortOrders = (ordersToSort: OrderData[]) => {
    return [...ordersToSort].sort((a, b) => {
      let aVal: any = a[sortConfig.field as keyof OrderData];
      let bVal: any = b[sortConfig.field as keyof OrderData];
      
      if (sortConfig.field === 'created_at') {
        aVal = new Date(aVal).getTime();
        bVal = new Date(bVal).getTime();
      }
      
      if (aVal < bVal) return sortConfig.direction === 'asc' ? -1 : 1;
      if (aVal > bVal) return sortConfig.direction === 'asc' ? 1 : -1;
      return 0;
    });
  };

  const filteredOrders = sortOrders(orders.filter((order) => {
    const matchesSearch = 
      order.order_number.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.profiles?.display_name?.toLowerCase().includes(searchTerm.toLowerCase());
    
    let matchesPayment = true;
    if (paymentFilter === "unpaid") {
      matchesPayment = order.status === "pending";
    } else if (paymentFilter === "paid") {
      matchesPayment = order.status === "confirmed";
    } else if (paymentFilter === "settled") {
      matchesPayment = order.status === "shipped" || order.status === "delivered";
    } else if (paymentFilter === "refunded") {
      matchesPayment = order.status === "cancelled";
    }
    
    return matchesSearch && matchesPayment;
  }));

  const handleSort = (field: string) => {
    setSortConfig(prev => ({
      field,
      direction: prev.field === field && prev.direction === 'desc' ? 'asc' : 'desc'
    }));
  };

  // 财务统计
  const stats = {
    totalRevenue: orders.filter(o => o.status !== 'cancelled').reduce((sum, o) => sum + o.total_amount, 0),
    pendingPayment: orders.filter(o => o.status === 'pending').reduce((sum, o) => sum + o.total_amount, 0),
    confirmedPayment: orders.filter(o => o.status === 'confirmed').reduce((sum, o) => sum + o.total_amount, 0),
    settledAmount: orders.filter(o => ['shipped', 'delivered'].includes(o.status)).reduce((sum, o) => sum + o.total_amount, 0),
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* 财务概览卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">总收入</p>
                <p className="text-xl font-bold text-emerald-600">{formatCurrency(stats.totalRevenue)}</p>
              </div>
              <DollarSign className="h-8 w-8 text-emerald-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">待收款</p>
                <p className="text-xl font-bold text-yellow-600">{formatCurrency(stats.pendingPayment)}</p>
              </div>
              <Clock className="h-8 w-8 text-yellow-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">已收款</p>
                <p className="text-xl font-bold text-blue-600">{formatCurrency(stats.confirmedPayment)}</p>
              </div>
              <CheckCircle2 className="h-8 w-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">已结算</p>
                <p className="text-xl font-bold text-green-600">{formatCurrency(stats.settledAmount)}</p>
              </div>
              <CreditCard className="h-8 w-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 订单列表 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <Receipt className="h-5 w-5" />
              收款明细
            </CardTitle>
            <div className="flex items-center gap-4">
              <Input
                placeholder="搜索订单号或客户..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-64"
              />
              <Select value={paymentFilter} onValueChange={setPaymentFilter}>
                <SelectTrigger className="w-32">
                  <SelectValue placeholder="支付状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="unpaid">待支付</SelectItem>
                  <SelectItem value="paid">已支付</SelectItem>
                  <SelectItem value="settled">已结算</SelectItem>
                  <SelectItem value="refunded">已退款</SelectItem>
                </SelectContent>
              </Select>
              <Button variant="outline" size="sm">
                <Download className="h-4 w-4 mr-2" />
                导出
              </Button>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead 
                  className="cursor-pointer hover:bg-muted/50"
                  onClick={() => handleSort('order_number')}
                >
                  订单号 {sortConfig.field === 'order_number' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
                </TableHead>
                <TableHead>客户</TableHead>
                <TableHead 
                  className="cursor-pointer hover:bg-muted/50 text-right"
                  onClick={() => handleSort('total_amount')}
                >
                  金额 {sortConfig.field === 'total_amount' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
                </TableHead>
                <TableHead>支付状态</TableHead>
                <TableHead 
                  className="cursor-pointer hover:bg-muted/50"
                  onClick={() => handleSort('created_at')}
                >
                  交易时间 {sortConfig.field === 'created_at' && <ArrowUpDown className="inline w-3 h-3 ml-1" />}
                </TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredOrders.map((order) => {
                const paymentStatus = getPaymentStatus(order.status);
                const StatusIcon = paymentStatus.icon;
                return (
                  <TableRow key={order.id}>
                    <TableCell className="font-mono text-sm">{order.order_number}</TableCell>
                    <TableCell>{order.profiles?.display_name || "未知客户"}</TableCell>
                    <TableCell className="text-right font-medium">
                      {formatCurrency(order.total_amount)}
                    </TableCell>
                    <TableCell>
                      <Badge variant={paymentStatus.variant} className="flex items-center gap-1 w-fit">
                        <StatusIcon className="h-3 w-3" />
                        {paymentStatus.text}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-muted-foreground text-sm">
                      {formatDate(order.created_at)}
                    </TableCell>
                    <TableCell>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => {
                          setSelectedOrder(order);
                          setIsDialogOpen(true);
                        }}
                      >
                        <Eye className="w-4 h-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>

          {filteredOrders.length === 0 && (
            <div className="text-center py-8 text-muted-foreground">
              暂无交易记录
            </div>
          )}
        </CardContent>
      </Card>

      {/* 财务详情对话框 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Receipt className="h-5 w-5" />
              交易详情
            </DialogTitle>
            <DialogDescription>
              订单号: {selectedOrder?.order_number}
            </DialogDescription>
          </DialogHeader>
          
          {selectedOrder && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="text-muted-foreground">客户</Label>
                  <p className="font-medium">{selectedOrder.profiles?.display_name || "未知客户"}</p>
                </div>
                <div>
                  <Label className="text-muted-foreground">交易时间</Label>
                  <p className="font-medium">{formatDate(selectedOrder.created_at)}</p>
                </div>
              </div>

              <div className="border rounded-lg p-4 bg-muted/30">
                <Label className="text-muted-foreground">商品明细</Label>
                <div className="mt-2 space-y-2">
                  {selectedOrder.order_items.map((item) => (
                    <div key={item.id} className="flex justify-between text-sm">
                      <span>{item.products?.name || "商品"} × {item.quantity}</span>
                      <span className="font-medium">{formatCurrency(item.quantity * item.unit_price)}</span>
                    </div>
                  ))}
                </div>
                <div className="border-t mt-3 pt-3 flex justify-between font-medium">
                  <span>合计</span>
                  <span className="text-lg text-emerald-600">{formatCurrency(selectedOrder.total_amount)}</span>
                </div>
              </div>

              <div className="flex items-center justify-between p-3 bg-primary/5 rounded-lg">
                <span className="text-sm">支付状态</span>
                <Badge variant={getPaymentStatus(selectedOrder.status).variant}>
                  {getPaymentStatus(selectedOrder.status).text}
                </Badge>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
