import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { 
  Search, 
  Filter, 
  Eye, 
  CheckCircle, 
  XCircle, 
  Clock, 
  Package,
  RefreshCw,
  MessageSquare
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { supabase } from "@/integrations/supabase/client";

interface AfterSalesRequest {
  id: string;
  user_id: string;
  order_id: string;
  product_id: string;
  type: string;
  status: string;
  reason: string;
  description: string;
  images?: string[];
  admin_notes?: string;
  tracking_number?: string;
  refund_amount?: number;
  processed_by?: string;
  processed_at?: string;
  created_at: string;
  updated_at: string;
  profiles?: {
    display_name?: string;
  } | null;
  orders?: {
    order_number?: string;
  } | null;
  products?: {
    name?: string;
    image_url?: string;
  } | null;
}

export function AfterSalesManager() {
  const [requests, setRequests] = useState<AfterSalesRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [typeFilter, setTypeFilter] = useState("all");
  const [selectedRequest, setSelectedRequest] = useState<AfterSalesRequest | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [adminNotes, setAdminNotes] = useState("");
  const [trackingNumber, setTrackingNumber] = useState("");
  const [refundAmount, setRefundAmount] = useState("");
  const { toast } = useToast();

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

  const fetchAfterSalesRequests = async () => {
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('after_sales_requests')
        .select(`
          *,
          profiles!after_sales_requests_user_id_fkey (display_name),
          orders!after_sales_requests_order_id_fkey (order_number),
          products!after_sales_requests_product_id_fkey (name, image_url)
        `)
        .order('created_at', { ascending: false });

      if (error) {
        console.error('数据库查询错误:', error);
        // 如果外键关联有问题，尝试简化查询
        const { data: simpleData, error: simpleError } = await supabase
          .from('after_sales_requests')
          .select('*')
          .order('created_at', { ascending: false });
        
        if (simpleError) throw simpleError;
        
        // 手动获取关联数据
        const requestsWithDetails = await Promise.all(
          (simpleData || []).map(async (request) => {
            const [userProfile, order, product] = await Promise.all([
              supabase.from('profiles').select('display_name').eq('user_id', request.user_id).single(),
              supabase.from('orders').select('order_number').eq('id', request.order_id).single(),
              supabase.from('products').select('name, image_url').eq('id', request.product_id).single()
            ]);
            
            return {
              ...request,
              profiles: userProfile.data || { display_name: '未知用户' },
              orders: order.data || { order_number: '未知订单' },
              products: product.data || { name: '未知商品', image_url: null }
            } as AfterSalesRequest;
          })
        );
        
        setRequests(requestsWithDetails);
      } else {
        setRequests((data as any[]) || []);
      }
    } catch (error) {
      console.error('获取售后申请失败:', error);
      toast({
        title: "获取失败",
        description: "无法获取售后申请列表",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  const handleViewRequest = (request: AfterSalesRequest) => {
    setSelectedRequest(request);
    setAdminNotes(request.admin_notes || "");
    setTrackingNumber(request.tracking_number || "");
    setRefundAmount(request.refund_amount?.toString() || "");
    setIsDialogOpen(true);
  };

  const handleUpdateRequest = async (status: string) => {
    if (!selectedRequest) return;

    try {
      const updateData: any = {
        status,
        admin_notes: adminNotes,
        tracking_number: trackingNumber || null,
        refund_amount: refundAmount ? parseFloat(refundAmount) : null,
        processed_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };

      const { error } = await supabase
        .from('after_sales_requests')
        .update(updateData)
        .eq('id', selectedRequest.id);

      if (error) throw error;

      toast({
        title: "更新成功",
        description: `售后申请已更新为${getStatusText(status)}`
      });

      setIsDialogOpen(false);
      fetchAfterSalesRequests();
    } catch (error) {
      console.error('更新失败:', error);
      toast({
        title: "更新失败",
        description: "无法更新售后申请状态",
        variant: "destructive"
      });
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case "pending": return "待审核";
      case "approved": return "已审核";
      case "processing": return "处理中";
      case "completed": return "已完成";
      case "rejected": return "已拒绝";
      default: return status;
    }
  };

  const getTypeText = (type: string) => {
    switch (type) {
      case "return": return "退货";
      case "exchange": return "换货";
      case "repair": return "维修";
      default: return type;
    }
  };

  const getReasonText = (reason: string) => {
    switch (reason) {
      case "quality_issue": return "质量问题";
      case "wrong_item": return "商品错误";
      case "not_as_described": return "与描述不符";
      case "damaged": return "运输损坏";
      case "personal_reason": return "个人原因";
      default: return reason;
    }
  };

  const getStatusBadgeVariant = (status: string) => {
    switch (status) {
      case "pending": return "secondary";
      case "approved": return "default";
      case "processing": return "outline";
      case "completed": return "default";
      case "rejected": return "destructive";
      default: return "secondary";
    }
  };

  const filteredRequests = requests.filter(request => {
    const matchesSearch = 
      request.orders?.order_number?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      request.products?.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      request.profiles?.display_name?.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === "all" || request.status === statusFilter;
    const matchesType = typeFilter === "all" || request.type === typeFilter;
    return matchesSearch && matchesStatus && matchesType;
  });

  const getStatusStats = () => {
    const stats = {
      total: requests.length,
      pending: requests.filter(r => r.status === 'pending').length,
      approved: requests.filter(r => r.status === 'approved').length,
      processing: requests.filter(r => r.status === 'processing').length,
      completed: requests.filter(r => r.status === 'completed').length,
      rejected: requests.filter(r => r.status === 'rejected').length
    };
    return stats;
  };

  const stats = getStatusStats();

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <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="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-medium">售后管理</h3>
          <p className="text-sm text-muted-foreground">管理用户的售后申请和处理流程</p>
        </div>
        <Button onClick={fetchAfterSalesRequests} variant="outline" size="sm">
          <RefreshCw className="w-4 h-4 mr-2" />
          刷新数据
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
        <Card>
          <CardContent className="flex items-center p-4">
            <Package className="h-8 w-8 text-blue-600" />
            <div className="ml-4">
              <p className="text-sm font-medium text-muted-foreground">总申请</p>
              <p className="text-2xl font-bold">{stats.total}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center p-4">
            <Clock className="h-8 w-8 text-yellow-600" />
            <div className="ml-4">
              <p className="text-sm font-medium text-muted-foreground">待审核</p>
              <p className="text-2xl font-bold">{stats.pending}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center p-4">
            <CheckCircle className="h-8 w-8 text-blue-600" />
            <div className="ml-4">
              <p className="text-sm font-medium text-muted-foreground">已审核</p>
              <p className="text-2xl font-bold">{stats.approved}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center p-4">
            <RefreshCw className="h-8 w-8 text-orange-600" />
            <div className="ml-4">
              <p className="text-sm font-medium text-muted-foreground">处理中</p>
              <p className="text-2xl font-bold">{stats.processing}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center p-4">
            <CheckCircle className="h-8 w-8 text-green-600" />
            <div className="ml-4">
              <p className="text-sm font-medium text-muted-foreground">已完成</p>
              <p className="text-2xl font-bold">{stats.completed}</p>
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="flex items-center p-4">
            <XCircle className="h-8 w-8 text-red-600" />
            <div className="ml-4">
              <p className="text-sm font-medium text-muted-foreground">已拒绝</p>
              <p className="text-2xl font-bold">{stats.rejected}</p>
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <div className="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
            <CardTitle>售后申请列表</CardTitle>
            <div className="flex flex-col md:flex-row gap-2 w-full md:w-auto">
              <div className="relative">
                <Search className="absolute left-3 top-3 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="搜索订单号、商品或用户..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10 w-full md:w-64"
                />
              </div>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-full md:w-32">
                  <SelectValue placeholder="状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="pending">待审核</SelectItem>
                  <SelectItem value="approved">已审核</SelectItem>
                  <SelectItem value="processing">处理中</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                  <SelectItem value="rejected">已拒绝</SelectItem>
                </SelectContent>
              </Select>
              <Select value={typeFilter} onValueChange={setTypeFilter}>
                <SelectTrigger className="w-full md:w-32">
                  <SelectValue placeholder="类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="return">退货</SelectItem>
                  <SelectItem value="exchange">换货</SelectItem>
                  <SelectItem value="repair">维修</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>订单信息</TableHead>
                  <TableHead>用户</TableHead>
                  <TableHead>商品</TableHead>
                  <TableHead>类型</TableHead>
                  <TableHead>状态</TableHead>
                  <TableHead>申请时间</TableHead>
                  <TableHead>操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredRequests.map((request) => (
                  <TableRow key={request.id}>
                    <TableCell>
                      <div>
                        <p className="font-medium">{request.orders?.order_number}</p>
                        <p className="text-sm text-muted-foreground">{getReasonText(request.reason)}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <p className="font-medium">{request.profiles?.display_name || '未知用户'}</p>
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-3">
                        {request.products?.image_url && (
                          <img 
                            src={request.products.image_url} 
                            alt={request.products.name}
                            className="w-10 h-10 rounded object-cover"
                          />
                        )}
                        <p className="font-medium">{request.products?.name}</p>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{getTypeText(request.type)}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant={getStatusBadgeVariant(request.status)}>
                        {getStatusText(request.status)}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      {new Date(request.created_at).toLocaleDateString('zh-CN')}
                    </TableCell>
                    <TableCell>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleViewRequest(request)}
                      >
                        <Eye className="w-4 h-4 mr-2" />
                        查看
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {filteredRequests.length === 0 && (
            <div className="text-center py-8">
              <Package className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-medium text-foreground mb-2">暂无售后申请</h3>
              <p className="text-muted-foreground">还没有用户提交售后申请</p>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 售后申请详情对话框 */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh]">
          <DialogHeader>
            <DialogTitle>售后申请详情</DialogTitle>
            <DialogDescription>
              处理用户的售后申请，更新状态和备注信息
            </DialogDescription>
          </DialogHeader>

          {selectedRequest && (
            <ScrollArea className="max-h-[60vh]">
              <div className="space-y-6">
                {/* 基础信息 */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label className="text-sm font-medium">订单号</Label>
                    <p className="text-sm text-muted-foreground mt-1">{selectedRequest.orders?.order_number}</p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium">用户</Label>
                    <p className="text-sm text-muted-foreground mt-1">{selectedRequest.profiles?.display_name}</p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium">商品</Label>
                    <p className="text-sm text-muted-foreground mt-1">{selectedRequest.products?.name}</p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium">申请类型</Label>
                    <p className="text-sm text-muted-foreground mt-1">{getTypeText(selectedRequest.type)}</p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium">申请原因</Label>
                    <p className="text-sm text-muted-foreground mt-1">{getReasonText(selectedRequest.reason)}</p>
                  </div>
                  <div>
                    <Label className="text-sm font-medium">当前状态</Label>
                    <div className="mt-1">
                      <Badge variant={getStatusBadgeVariant(selectedRequest.status)}>
                        {getStatusText(selectedRequest.status)}
                      </Badge>
                    </div>
                  </div>
                </div>

                <Separator />

                {/* 详细描述 */}
                <div>
                  <Label className="text-sm font-medium">问题描述</Label>
                  <p className="text-sm text-muted-foreground mt-1 bg-muted p-3 rounded-md">
                    {selectedRequest.description}
                  </p>
                </div>

                <Separator />

                {/* 管理员操作 */}
                <Tabs defaultValue="notes" className="w-full">
                  <TabsList className="grid w-full grid-cols-3">
                    <TabsTrigger value="notes">备注信息</TabsTrigger>
                    <TabsTrigger value="tracking">物流信息</TabsTrigger>
                    <TabsTrigger value="refund">退款信息</TabsTrigger>
                  </TabsList>
                  
                  <TabsContent value="notes" className="space-y-4">
                    <div>
                      <Label htmlFor="admin-notes">管理员备注</Label>
                      <Textarea
                        id="admin-notes"
                        placeholder="添加处理备注..."
                        value={adminNotes}
                        onChange={(e) => setAdminNotes(e.target.value)}
                        className="mt-1"
                        rows={4}
                      />
                    </div>
                  </TabsContent>
                  
                  <TabsContent value="tracking" className="space-y-4">
                    <div>
                      <Label htmlFor="tracking-number">物流单号</Label>
                      <Input
                        id="tracking-number"
                        placeholder="输入物流追踪号..."
                        value={trackingNumber}
                        onChange={(e) => setTrackingNumber(e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </TabsContent>
                  
                  <TabsContent value="refund" className="space-y-4">
                    <div>
                      <Label htmlFor="refund-amount">退款金额</Label>
                      <Input
                        id="refund-amount"
                        type="number"
                        placeholder="输入退款金额..."
                        value={refundAmount}
                        onChange={(e) => setRefundAmount(e.target.value)}
                        className="mt-1"
                      />
                    </div>
                  </TabsContent>
                </Tabs>
              </div>
            </ScrollArea>
          )}

          <DialogFooter>
            <div className="flex gap-2 w-full">
              <Button variant="outline" onClick={() => setIsDialogOpen(false)}>
                取消
              </Button>
              {selectedRequest?.status === 'pending' && (
                <>
                  <Button 
                    variant="destructive" 
                    onClick={() => handleUpdateRequest('rejected')}
                  >
                    拒绝申请
                  </Button>
                  <Button onClick={() => handleUpdateRequest('approved')}>
                    审核通过
                  </Button>
                </>
              )}
              {selectedRequest?.status === 'approved' && (
                <Button onClick={() => handleUpdateRequest('processing')}>
                  开始处理
                </Button>
              )}
              {selectedRequest?.status === 'processing' && (
                <Button onClick={() => handleUpdateRequest('completed')}>
                  标记完成
                </Button>
              )}
              <Button variant="outline" onClick={() => handleUpdateRequest(selectedRequest?.status || 'pending')}>
                更新信息
              </Button>
            </div>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}