import { useState, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, 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 { 
  MessageSquare, 
  Clock, 
  CheckCircle, 
  XCircle, 
  Package,
  Truck,
  Phone,
  Mail,
  AlertCircle,
  Lightbulb,
  Star
} from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/contexts/AuthContext";
import { toast } from "sonner";

interface AfterSalesAssistantProps {
  orderId: string;
  orderNumber: string;
  customerName: string;
  onResponse?: (response: string) => void;
}

const QUICK_RESPONSES = [
  {
    category: "审核回复",
    responses: [
      "您的售后申请已通过审核，我们将在1-2个工作日内安排处理。",
      "感谢您的申请，我们正在仔细审核您的情况，请耐心等待。",
      "经审核，您的申请符合我们的售后政策，正在安排相关处理。"
    ]
  },
  {
    category: "处理进度",
    responses: [
      "您的商品已安排退货处理，请按照以下地址寄回商品。",
      "换货商品已为您安排发出，预计2-3天内到达。",
      "维修已完成，商品正在质检中，很快会寄回给您。"
    ]
  },
  {
    category: "客户关怀",
    responses: [
      "非常抱歉给您带来了不便，我们会认真处理您的问题。",
      "感谢您对我们的信任，我们一定会给您一个满意的解决方案。",
      "如有任何疑问，随时联系我们的客服团队，我们随时为您服务。"
    ]
  }
];

const STATUS_SUGGESTIONS = {
  pending: {
    icon: Clock,
    color: "text-yellow-600",
    suggestions: [
      "建议在24小时内完成初审",
      "可先联系客户了解详细情况",
      "检查是否符合退换货政策"
    ]
  },
  approved: {
    icon: CheckCircle,
    color: "text-blue-600",
    suggestions: [
      "安排物流上门取件",
      "准备换货商品库存",
      "更新客户处理进度"
    ]
  },
  processing: {
    icon: Package,
    color: "text-orange-600",
    suggestions: [
      "定期更新处理进度",
      "确保处理时效性",
      "主动与客户沟通"
    ]
  }
};

export function AfterSalesAssistant({
  orderId,
  orderNumber,
  customerName,
  onResponse
}: AfterSalesAssistantProps) {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState<"quick" | "custom" | "ai">("quick");
  const [customMessage, setCustomMessage] = useState("");
  const [selectedResponse, setSelectedResponse] = useState("");
  const [aiPrompt, setAiPrompt] = useState("");
  const [isGenerating, setIsGenerating] = useState(false);

  const handleQuickResponse = useCallback((response: string) => {
    onResponse?.(response);
    toast.success("快速回复已发送");
  }, [onResponse]);

  const handleCustomResponse = useCallback(() => {
    if (!customMessage.trim()) {
      toast.error("请输入回复内容");
      return;
    }
    onResponse?.(customMessage);
    setCustomMessage("");
    toast.success("自定义回复已发送");
  }, [customMessage, onResponse]);

  const generateAIResponse = useCallback(async () => {
    if (!aiPrompt.trim()) {
      toast.error("请输入AI生成提示");
      return;
    }

    setIsGenerating(true);
    try {
      // 这里可以集成AI服务来生成回复
      // 暂时使用模拟的智能回复
      const aiResponse = `基于您的要求"${aiPrompt}"，我建议：\n\n尊敬的${customerName}，您好！\n\n感谢您选择我们的服务。关于您订单${orderNumber}的售后申请，我们已经认真审核了您的情况。\n\n${aiPrompt.includes("退款") ? "我们将在3-5个工作日内为您处理退款，款项将原路返回到您的支付账户。" : ""}\n${aiPrompt.includes("换货") ? "我们已为您安排换货，新商品将在2-3个工作日内发出。" : ""}\n${aiPrompt.includes("维修") ? "我们的技术团队将为您提供专业的维修服务，预计5-7个工作日完成。" : ""}\n\n如有任何疑问，请随时联系我们。再次为给您带来的不便深表歉意。\n\n祝您生活愉快！`;
      
      onResponse?.(aiResponse);
      setAiPrompt("");
      toast.success("AI回复已生成并发送");
    } catch (error) {
      console.error("AI生成失败:", error);
      toast.error("AI生成失败，请稍后重试");
    } finally {
      setIsGenerating(false);
    }
  }, [aiPrompt, customerName, orderNumber, onResponse]);

  return (
    <Card className="mt-4">
      <CardHeader>
        <CardTitle className="flex items-center space-x-2">
          <MessageSquare className="h-5 w-5" />
          <span>智能客服助手</span>
        </CardTitle>
      </CardHeader>
      
      <CardContent className="space-y-4">
        {/* 状态建议 */}
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
          <div className="flex items-center space-x-2 mb-2">
            <Lightbulb className="h-4 w-4 text-blue-600" />
            <span className="text-sm font-medium text-blue-900">处理建议</span>
          </div>
          <ul className="text-sm text-blue-700 space-y-1">
            <li>• 建议在24小时内完成初审</li>
            <li>• 可先联系客户了解详细情况</li>
            <li>• 检查是否符合退换货政策</li>
          </ul>
        </div>

        {/* Tab切换 */}
        <div className="flex space-x-1 bg-muted p-1 rounded-lg">
          <Button
            variant={activeTab === "quick" ? "default" : "ghost"}
            size="sm"
            onClick={() => setActiveTab("quick")}
            className="flex-1"
          >
            快速回复
          </Button>
          <Button
            variant={activeTab === "custom" ? "default" : "ghost"}
            size="sm"
            onClick={() => setActiveTab("custom")}
            className="flex-1"
          >
            自定义回复
          </Button>
          <Button
            variant={activeTab === "ai" ? "default" : "ghost"}
            size="sm"
            onClick={() => setActiveTab("ai")}
            className="flex-1"
          >
            AI生成
          </Button>
        </div>

        {/* 快速回复 */}
        {activeTab === "quick" && (
          <div className="space-y-3">
            {QUICK_RESPONSES.map((category) => (
              <div key={category.category}>
                <Label className="text-sm font-medium">{category.category}</Label>
                <div className="mt-2 space-y-2">
                  {category.responses.map((response, index) => (
                    <Button
                      key={index}
                      variant="outline"
                      className="w-full text-left h-auto p-3 justify-start"
                      onClick={() => handleQuickResponse(response)}
                    >
                      <div className="text-sm">{response}</div>
                    </Button>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 自定义回复 */}
        {activeTab === "custom" && (
          <div className="space-y-3">
            <div>
              <Label htmlFor="custom-message">自定义回复内容</Label>
              <Textarea
                id="custom-message"
                value={customMessage}
                onChange={(e) => setCustomMessage(e.target.value)}
                placeholder={`尊敬的${customerName}，您好！\n\n关于您订单${orderNumber}的售后申请...`}
                className="mt-2 min-h-[120px]"
              />
            </div>
            <Button onClick={handleCustomResponse} className="w-full">
              发送自定义回复
            </Button>
          </div>
        )}

        {/* AI生成回复 */}
        {activeTab === "ai" && (
          <div className="space-y-3">
            <div>
              <Label htmlFor="ai-prompt">AI生成提示</Label>
              <Input
                id="ai-prompt"
                value={aiPrompt}
                onChange={(e) => setAiPrompt(e.target.value)}
                placeholder="例如：同意退款并道歉"
                className="mt-2"
              />
            </div>
            <Button 
              onClick={generateAIResponse} 
              disabled={isGenerating}
              className="w-full"
            >
              {isGenerating ? "生成中..." : "生成AI回复"}
            </Button>
            
            <div className="bg-amber-50 border border-amber-200 rounded-lg p-3">
              <div className="flex items-center space-x-2">
                <Star className="h-4 w-4 text-amber-600" />
                <span className="text-sm font-medium text-amber-900">AI提示示例</span>
              </div>
              <div className="mt-2 text-sm text-amber-700 space-y-1">
                <div>• "同意退款并表示歉意"</div>
                <div>• "安排换货并说明流程"</div>
                <div>• "解释维修进度和时效"</div>
                <div>• "询问更多详细信息"</div>
              </div>
            </div>
          </div>
        )}

        {/* 联系信息快捷操作 */}
        <div className="border-t pt-4">
          <div className="flex space-x-2">
            <Button variant="outline" size="sm" className="flex-1">
              <Phone className="h-4 w-4 mr-1" />
              致电客户
            </Button>
            <Button variant="outline" size="sm" className="flex-1">
              <Mail className="h-4 w-4 mr-1" />
              发送邮件
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}