import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { 
  Package, 
  Truck, 
  MapPin, 
  Phone, 
  MessageCircle, 
  Calendar, 
  CreditCard,
  AlertCircle,
  CheckCircle2,
  Clock,
  Star,
  ShoppingCart,
  Send
} from "lucide-react";

interface OrderData {
  id: string;
  orderNumber: string;
  status: string;
  items: Array<{
    name: string;
    quantity: number;
    price: string;
    productId: string;
  }>;
  total: string;
  orderDate: string;
  shippingAddress?: string;
  trackingNumber?: string;
  estimatedDelivery?: string;
}

interface OrderAssistantProps {
  order: OrderData;
  onClose: () => void;
  onUpdateOrder?: (orderId: string, updates: any) => void;
  onCancelOrder?: (orderId: string, reason: string) => void;
  onContactService?: (orderId: string, message: string) => void;
  onRateOrder?: (orderId: string, rating: number, comment: string) => void;
}

const statusConfig = {
  'pending': { label: '待处理', color: 'bg-yellow-100 text-yellow-800', icon: Clock },
  'confirmed': { label: '已确认', color: 'bg-blue-100 text-blue-800', icon: CheckCircle2 },
  'shipped': { label: '已发货', color: 'bg-green-100 text-green-800', icon: Truck },
  'delivered': { label: '已送达', color: 'bg-emerald-100 text-emerald-800', icon: Package },
  'cancelled': { label: '已取消', color: 'bg-red-100 text-red-800', icon: AlertCircle },
};

export function OrderAssistant({ 
  order, 
  onClose, 
  onUpdateOrder, 
  onCancelOrder, 
  onContactService, 
  onRateOrder 
}: OrderAssistantProps) {
  const [activeTab, setActiveTab] = useState<'details' | 'tracking' | 'service' | 'rate'>('details');
  const [contactMessage, setContactMessage] = useState("");
  const [cancelReason, setCancelReason] = useState("");
  const [showCancelDialog, setShowCancelDialog] = useState(false);
  const [rating, setRating] = useState(5);
  const [ratingComment, setRatingComment] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const { toast } = useToast();

  const currentStatus = statusConfig[order.status as keyof typeof statusConfig] || statusConfig.pending;
  const StatusIcon = currentStatus.icon;

  const handleCancelOrder = async () => {
    if (!cancelReason.trim()) {
      toast({
        title: "请填写取消原因",
        description: "为了改善服务质量，请告诉我们取消订单的原因",
        variant: "destructive"
      });
      return;
    }

    setIsSubmitting(true);
    try {
      await onCancelOrder?.(order.id, cancelReason);
      toast({
        title: "订单取消成功",
        description: "您的订单已成功取消，退款将在3-5个工作日内到账"
      });
      setShowCancelDialog(false);
      onClose();
    } catch (error) {
      toast({
        title: "取消失败",
        description: "订单取消失败，请联系客服处理",
        variant: "destructive"
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleContactService = async () => {
    if (!contactMessage.trim()) {
      toast({
        title: "请输入留言内容",
        description: "请告诉我们您需要咨询的问题",
        variant: "destructive"
      });
      return;
    }

    setIsSubmitting(true);
    try {
      await onContactService?.(order.id, contactMessage);
      toast({
        title: "留言发送成功",
        description: "客服将在24小时内回复您的问题"
      });
      setContactMessage("");
    } catch (error) {
      toast({
        title: "发送失败",
        description: "留言发送失败，请稍后重试",
        variant: "destructive"
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleRateOrder = async () => {
    setIsSubmitting(true);
    try {
      await onRateOrder?.(order.id, rating, ratingComment);
      toast({
        title: "评价提交成功",
        description: "感谢您的评价，这将帮助我们提供更好的服务"
      });
      setActiveTab('details');
    } catch (error) {
      toast({
        title: "评价失败",
        description: "评价提交失败，请稍后重试",
        variant: "destructive"
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const renderTabContent = () => {
    switch (activeTab) {
      case 'details':
        return (
          <div className="space-y-6">
            {/* 订单状态 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <StatusIcon className="h-5 w-5" />
                  订单状态
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex items-center justify-between">
                  <Badge className={currentStatus.color}>
                    {currentStatus.label}
                  </Badge>
                  <span className="text-sm text-muted-foreground">
                    下单时间：{order.orderDate}
                  </span>
                </div>
                {order.estimatedDelivery && (
                  <p className="text-sm text-muted-foreground mt-2">
                    预计送达：{order.estimatedDelivery}
                  </p>
                )}
              </CardContent>
            </Card>

            {/* 商品信息 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <ShoppingCart className="h-5 w-5" />
                  商品清单
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-3">
                {order.items.map((item, index) => (
                  <div key={index} className="flex justify-between items-center p-3 bg-muted/50 rounded-lg">
                    <div>
                      <p className="font-medium">{item.name}</p>
                      <p className="text-sm text-muted-foreground">数量：{item.quantity}</p>
                    </div>
                    <p className="font-semibold">{item.price}</p>
                  </div>
                ))}
                <div className="border-t pt-3 flex justify-between font-semibold text-lg">
                  <span>订单总计</span>
                  <span className="text-primary">{order.total}</span>
                </div>
              </CardContent>
            </Card>

            {/* 配送信息 */}
            {order.shippingAddress && (
              <Card>
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <MapPin className="h-5 w-5" />
                    配送信息
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-sm">{order.shippingAddress}</p>
                  {order.trackingNumber && (
                    <div className="mt-3 p-3 bg-primary/10 rounded-lg">
                      <p className="text-sm font-medium">快递单号：{order.trackingNumber}</p>
                      <Button variant="outline" size="sm" className="mt-2">
                        查看物流详情
                      </Button>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* 操作按钮 */}
            <div className="flex gap-3">
              {order.status === 'pending' && (
                <Button 
                  variant="destructive" 
                  onClick={() => setShowCancelDialog(true)}
                  className="flex-1"
                >
                  取消订单
                </Button>
              )}
              <Button 
                variant="outline" 
                onClick={() => setActiveTab('service')}
                className="flex-1"
              >
                <MessageCircle className="w-4 h-4 mr-2" />
                联系客服
              </Button>
              {order.status === 'delivered' && (
                <Button 
                  onClick={() => setActiveTab('rate')}
                  className="flex-1"
                >
                  <Star className="w-4 h-4 mr-2" />
                  评价订单
                </Button>
              )}
            </div>
          </div>
        );

      case 'tracking':
        return (
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Truck className="h-5 w-5" />
                  物流跟踪
                </CardTitle>
              </CardHeader>
              <CardContent>
                {order.trackingNumber ? (
                  <div className="space-y-4">
                    <div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg">
                      <span>快递单号</span>
                      <Badge variant="outline">{order.trackingNumber}</Badge>
                    </div>
                    
                    {/* 物流进度 */}
                    <div className="space-y-3">
                      <div className="flex items-center gap-3">
                        <div className="w-3 h-3 bg-primary rounded-full"></div>
                        <div>
                          <p className="text-sm font-medium">包裹已签收</p>
                          <p className="text-xs text-muted-foreground">2024-01-22 14:30</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-3">
                        <div className="w-3 h-3 bg-muted rounded-full"></div>
                        <div>
                          <p className="text-sm">正在派送中</p>
                          <p className="text-xs text-muted-foreground">2024-01-22 08:00</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-3">
                        <div className="w-3 h-3 bg-muted rounded-full"></div>
                        <div>
                          <p className="text-sm">包裹已到达配送站</p>
                          <p className="text-xs text-muted-foreground">2024-01-21 18:20</p>
                        </div>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="text-center py-8 text-muted-foreground">
                    <Truck className="h-12 w-12 mx-auto mb-3 opacity-50" />
                    <p>订单尚未发货</p>
                    <p className="text-sm">发货后可以在这里查看物流信息</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        );

      case 'service':
        return (
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <MessageCircle className="h-5 w-5" />
                  联系客服
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label htmlFor="message">您的问题或建议</Label>
                  <Textarea
                    id="message"
                    placeholder="请描述您遇到的问题或需要咨询的内容..."
                    value={contactMessage}
                    onChange={(e) => setContactMessage(e.target.value)}
                    className="mt-2 min-h-[120px]"
                  />
                </div>
                
                <div className="flex gap-3">
                  <Button onClick={handleContactService} disabled={isSubmitting} className="flex-1">
                    <Send className="w-4 h-4 mr-2" />
                    {isSubmitting ? "发送中..." : "发送留言"}
                  </Button>
                </div>

                <div className="mt-6 p-4 bg-muted/50 rounded-lg">
                  <h4 className="font-medium mb-2">客服联系方式</h4>
                  <div className="space-y-2 text-sm">
                    <div className="flex items-center gap-2">
                      <Phone className="h-4 w-4" />
                      <span>客服热线：400-888-9999</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <Clock className="h-4 w-4" />
                      <span>服务时间：9:00-21:00</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        );

      case 'rate':
        return (
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Star className="h-5 w-5" />
                  订单评价
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label>整体满意度</Label>
                  <div className="flex gap-1 mt-2">
                    {[1, 2, 3, 4, 5].map((star) => (
                      <Button
                        key={star}
                        variant="ghost"
                        size="sm"
                        onClick={() => setRating(star)}
                        className="p-1"
                      >
                        <Star 
                          className={`h-6 w-6 ${
                            star <= rating ? 'fill-yellow-400 text-yellow-400' : 'text-muted-foreground'
                          }`} 
                        />
                      </Button>
                    ))}
                  </div>
                </div>

                <div>
                  <Label htmlFor="comment">评价内容（可选）</Label>
                  <Textarea
                    id="comment"
                    placeholder="分享您的购物体验，帮助其他用户..."
                    value={ratingComment}
                    onChange={(e) => setRatingComment(e.target.value)}
                    className="mt-2 min-h-[100px]"
                  />
                </div>

                <Button onClick={handleRateOrder} disabled={isSubmitting} className="w-full">
                  {isSubmitting ? "提交中..." : "提交评价"}
                </Button>
              </CardContent>
            </Card>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <>
      <Dialog open={true} onOpenChange={onClose}>
        <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Package className="h-5 w-5" />
              订单助手 - {order.orderNumber}
            </DialogTitle>
          </DialogHeader>

          {/* Tab Navigation */}
          <div className="flex border-b">
            {[
              { key: 'details', label: '订单详情', icon: Package },
              { key: 'tracking', label: '物流跟踪', icon: Truck },
              { key: 'service', label: '客服咨询', icon: MessageCircle },
              ...(order.status === 'delivered' ? [{ key: 'rate' as const, label: '订单评价', icon: Star }] : [])
            ].map((tab) => (
              <Button
                key={tab.key}
                variant={activeTab === tab.key ? "default" : "ghost"}
                size="sm"
                  onClick={() => setActiveTab(tab.key as any)}
                  className="flex-1 rounded-none border-b-2 border-transparent data-[state=active]:border-primary"
              >
                <tab.icon className="w-4 h-4 mr-2" />
                {tab.label}
              </Button>
            ))}
          </div>

          {/* Tab Content */}
          <div className="py-4">
            {renderTabContent()}
          </div>
        </DialogContent>
      </Dialog>

      {/* Cancel Order Dialog */}
      <Dialog open={showCancelDialog} onOpenChange={setShowCancelDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-destructive" />
              确认取消订单
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              取消订单后将无法恢复，请确认您的操作。
            </p>
            <div>
              <Label htmlFor="cancel-reason">取消原因</Label>
              <Select value={cancelReason} onValueChange={setCancelReason}>
                <SelectTrigger className="mt-2">
                  <SelectValue placeholder="请选择取消原因" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="change_mind">不想要了</SelectItem>
                  <SelectItem value="wrong_item">选错商品</SelectItem>
                  <SelectItem value="better_price">找到更优惠的价格</SelectItem>
                  <SelectItem value="delivery_time">配送时间太长</SelectItem>
                  <SelectItem value="other">其他原因</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="flex gap-3">
              <Button variant="outline" onClick={() => setShowCancelDialog(false)} className="flex-1">
                保留订单
              </Button>
              <Button 
                variant="destructive" 
                onClick={handleCancelOrder}
                disabled={isSubmitting}
                className="flex-1"
              >
                {isSubmitting ? "取消中..." : "确认取消"}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}