import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Progress } from "@/components/ui/progress";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { supabase } from "@/integrations/supabase/client";
import { useToast } from "@/hooks/use-toast";
import { 
  Package, 
  Clock, 
  CheckCircle, 
  Truck, 
  Star, 
  MapPin, 
  CreditCard, 
  MessageSquare, 
  Phone, 
  User,
  FileText,
  AlertCircle,
  Calendar,
  DollarSign
} from "lucide-react";
import { PLACEHOLDER_PRODUCT } from "@/utils/placeholderImage";

interface TimelineStep {
  step: string;
  status: 'completed' | 'current' | 'pending';
  time?: string;
  description: string;
}

interface RefundInfo {
  method: string;
  account: string;
  amount: number;
  status: string;
}

interface ShippingInfo {
  address: string;
  method: string;
  trackingNumber: string;
  company: string;
}

interface AfterSalesDetailInfo {
  id: string;
  orderNumber: string;
  productName: string;
  productImage: string;
  type: 'return' | 'exchange' | 'repair';
  status: 'pending' | 'approved' | 'processing' | 'completed' | 'rejected';
  progress: number;
  currentStep: string;
  createdAt: string;
  updatedAt: string;
  estimatedCompletion?: string;
  trackingNumber?: string;
  amount: number;
  reason: string;
  description: string;
  images?: string[];
  timeline: TimelineStep[];
  refundInfo?: RefundInfo;
  shippingInfo?: ShippingInfo;
}

interface AfterSalesDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  afterSalesId: string | null;
  onContactService?: (afterSalesId: string) => void;
}

// 获取售后详情数据
const getAfterSalesDetail = async (id: string): Promise<AfterSalesDetailInfo | null> => {
  try {
    const { data, error } = await supabase
      .from('after_sales_requests')
      .select(`
        *,
        orders!order_id (order_number),
        products!product_id (name, image_url)
      `)
      .eq('id', id)
      .single();

    if (error) throw error;
    if (!data) return null;

    // 构建时间线
    const timeline: TimelineStep[] = [
      {
        step: "提交申请",
        status: "completed",
        time: new Date(data.created_at).toLocaleString('zh-CN'),
        description: "您提交了售后申请"
      }
    ];

    // 根据状态添加时间线步骤
    if (data.status !== 'pending') {
      timeline.push({
        step: "申请审核",
        status: "completed",
        time: data.processed_at ? new Date(data.processed_at).toLocaleString('zh-CN') : undefined,
        description: data.status === 'rejected' ? "申请已被拒绝" : "申请已通过审核"
      });
    }

    if (data.status === 'processing') {
      timeline.push({
        step: "处理中",
        status: "current",
        description: data.admin_notes || "正在处理您的申请"
      });
    }

    if (data.status === 'completed') {
      timeline.push({
        step: "处理中",
        status: "completed",
        description: "申请处理中"
      });
      timeline.push({
        step: "处理完成",
        status: "completed",
        time: new Date(data.updated_at).toLocaleString('zh-CN'),
        description: "售后申请已完成处理"
      });
    }

    // 计算进度
    let progress = 25; // 默认提交申请
    if (data.status === 'approved') progress = 50;
    if (data.status === 'processing') progress = 75;
    if (data.status === 'completed') progress = 100;
    if (data.status === 'rejected') progress = 100;

    // 获取当前步骤描述
    let currentStep = "申请已提交";
    if (data.status === 'approved') currentStep = "申请已审核通过";
    if (data.status === 'processing') currentStep = data.admin_notes || "正在处理中";
    if (data.status === 'completed') currentStep = "处理完成";
    if (data.status === 'rejected') currentStep = "申请已被拒绝";

    return {
      id: data.id,
      orderNumber: data.orders?.order_number || '',
      productName: data.products?.name || '',
      productImage: data.products?.image_url || PLACEHOLDER_PRODUCT,
      type: data.type as 'return' | 'exchange' | 'repair',
      status: data.status as 'pending' | 'approved' | 'processing' | 'completed' | 'rejected',
      progress,
      currentStep,
      createdAt: new Date(data.created_at).toLocaleString('zh-CN'),
      updatedAt: new Date(data.updated_at).toLocaleString('zh-CN'),
      trackingNumber: data.tracking_number,
      amount: data.refund_amount || 0,
      reason: data.reason,
      description: data.description,
      images: data.images || [],
      timeline,
      refundInfo: data.refund_amount ? {
        method: "原路退回",
        account: "***",
        amount: data.refund_amount,
        status: data.status === 'completed' ? "已退款" : "待退款"
      } : undefined,
      shippingInfo: data.tracking_number ? {
        address: "收货地址",
        method: "快递",
        trackingNumber: data.tracking_number,
        company: "快递公司"
      } : undefined
    };
  } catch (error) {
    console.error('获取售后详情失败:', error);
    return null;
  }
};

export function AfterSalesDetailDialog({ open, onOpenChange, afterSalesId, onContactService }: AfterSalesDetailDialogProps) {
  const [detail, setDetail] = useState<AfterSalesDetailInfo | null>(null);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    if (afterSalesId && open) {
      fetchDetail();
    }
  }, [afterSalesId, open]);

  const fetchDetail = async () => {
    if (!afterSalesId) return;
    
    setLoading(true);
    try {
      const data = await getAfterSalesDetail(afterSalesId);
      setDetail(data);
    } catch (error) {
      toast({
        title: "获取失败",
        description: "无法获取售后详情",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  if (!detail && !loading) return null;

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'bg-yellow-100 text-yellow-800 border-yellow-200';
      case 'approved': return 'bg-blue-100 text-blue-800 border-blue-200';
      case 'processing': return 'bg-orange-100 text-orange-800 border-orange-200';
      case 'completed': return 'bg-green-100 text-green-800 border-green-200';
      case 'rejected': return 'bg-red-100 text-red-800 border-red-200';
      default: return 'bg-muted text-foreground border-border';
    }
  };

  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 getTimelineIcon = (status: string) => {
    switch (status) {
      case 'completed': return <CheckCircle className="w-5 h-5 text-green-600" />;
      case 'current': return <Clock className="w-5 h-5 text-blue-600" />;
      default: return <div className="w-5 h-5 rounded-full border-2 border-border bg-background" />;
    }
  };

  const handleContactService = () => {
    if (afterSalesId && onContactService) {
      onContactService(afterSalesId);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-3">
            <Package className="w-6 h-6 text-primary" />
            售后详情
          </DialogTitle>
        </DialogHeader>

        {loading ? (
          <div className="flex justify-center items-center py-12">
            <div className="text-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-2"></div>
              <p className="text-muted-foreground">加载中...</p>
            </div>
          </div>
        ) : detail && (
          <ScrollArea className="flex-1">
            <div className="space-y-6 pr-4">
              {/* 基本信息 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <FileText className="w-5 h-5" />
                    基本信息
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex gap-4">
                    <img 
                      src={detail.productImage} 
                      alt={detail.productName}
                      className="w-20 h-20 object-cover rounded-lg"
                    />
                    <div className="flex-1">
                      <h3 className="font-semibold text-lg">{detail.productName}</h3>
                      <p className="text-muted-foreground">订单号: {detail.orderNumber}</p>
                      <div className="flex gap-2 mt-2">
                        <Badge variant="outline" className="bg-primary/10 text-primary border-primary/20">
                          {getTypeText(detail.type)}
                        </Badge>
                        <Badge className={getStatusColor(detail.status)}>
                          {getStatusText(detail.status)}
                        </Badge>
                      </div>
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">申请时间:</span>
                      <span className="ml-2">{detail.createdAt}</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">更新时间:</span>
                      <span className="ml-2">{detail.updatedAt}</span>
                    </div>
                    {detail.trackingNumber && (
                      <div>
                        <span className="text-muted-foreground">物流单号:</span>
                        <span className="ml-2">{detail.trackingNumber}</span>
                      </div>
                    )}
                    {detail.amount > 0 && (
                      <div>
                        <span className="text-muted-foreground">金额:</span>
                        <span className="ml-2 font-medium">¥{detail.amount.toFixed(2)}</span>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>

              {/* 进度跟踪 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Truck className="w-5 h-5" />
                    进度跟踪
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <div className="flex justify-between items-center mb-2">
                      <span className="text-sm font-medium">当前进度</span>
                      <span className="text-sm text-muted-foreground">{detail.progress}%</span>
                    </div>
                    <Progress value={detail.progress} className="w-full" />
                    <p className="text-sm text-muted-foreground mt-2">{detail.currentStep}</p>
                  </div>

                  <div className="space-y-4">
                    {detail.timeline.map((step, index) => (
                      <div key={index} className="flex gap-3">
                        <div className="flex flex-col items-center">
                          {getTimelineIcon(step.status)}
                          {index < detail.timeline.length - 1 && (
                            <div className="w-px h-8 bg-muted mt-2" />
                          )}
                        </div>
                        <div className="flex-1 pb-4">
                          <div className="flex items-center gap-2">
                            <h4 className="font-medium">{step.step}</h4>
                            {step.time && (
                              <span className="text-xs text-muted-foreground">{step.time}</span>
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground mt-1">{step.description}</p>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>

              {/* 申请详情 */}
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <AlertCircle className="w-5 h-5" />
                    申请详情
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div>
                    <h4 className="font-medium mb-2">申请原因: {getReasonText(detail.reason)}</h4>
                    <p className="text-sm text-muted-foreground">{detail.description}</p>
                  </div>
                  
                  {detail.images && detail.images.length > 0 && (
                    <div>
                      <h4 className="font-medium mb-2">相关图片</h4>
                      <div className="grid grid-cols-2 gap-2">
                        {detail.images.map((image, index) => (
                          <img 
                            key={index}
                            src={image} 
                            alt={`问题图片 ${index + 1}`}
                            className="w-full h-32 object-cover rounded-lg"
                          />
                        ))}
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 退款信息 */}
              {detail.refundInfo && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <CreditCard className="w-5 h-5" />
                      退款信息
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="grid grid-cols-2 gap-4 text-sm">
                      <div>
                        <span className="text-muted-foreground">退款方式:</span>
                        <span className="ml-2">{detail.refundInfo.method}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">退款状态:</span>
                        <span className="ml-2">{detail.refundInfo.status}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">退款账户:</span>
                        <span className="ml-2">{detail.refundInfo.account}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">退款金额:</span>
                        <span className="ml-2 font-medium">¥{detail.refundInfo.amount.toFixed(2)}</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 物流信息 */}
              {detail.shippingInfo && (
                <Card>
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <MapPin className="w-5 h-5" />
                      物流信息
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="grid grid-cols-1 gap-3 text-sm">
                      <div>
                        <span className="text-muted-foreground">收货地址:</span>
                        <span className="ml-2">{detail.shippingInfo.address}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">物流方式:</span>
                        <span className="ml-2">{detail.shippingInfo.method}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">物流公司:</span>
                        <span className="ml-2">{detail.shippingInfo.company}</span>
                      </div>
                      <div>
                        <span className="text-muted-foreground">物流单号:</span>
                        <span className="ml-2 font-mono">{detail.shippingInfo.trackingNumber}</span>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}

              {/* 操作按钮 */}
              <div className="flex gap-3 pt-4">
                <Button 
                  onClick={handleContactService}
                  className="flex items-center gap-2"
                >
                  <MessageSquare className="w-4 h-4" />
                  联系客服
                </Button>
                <Button variant="outline" className="flex items-center gap-2">
                  <Phone className="w-4 h-4" />
                  电话咨询
                </Button>
              </div>
            </div>
          </ScrollArea>
        )}
      </DialogContent>
    </Dialog>
  );
}