import { useState, useEffect } from "react";
import { MessageSquare, Bot, Send, X, ShieldCheck, UserCheck, RefreshCw, Sparkles, CheckCircle2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { toast } from "sonner";

export type ChatChannel = "admin-buyer" | "vendor-admin";

interface TawkChatWidgetProps {
  channel: ChatChannel;
  autoOpen?: boolean;
  onClose?: () => void;
}

export function TawkChatWidget({ channel, autoOpen = false, onClose }: TawkChatWidgetProps) {
  const [open, setOpen] = useState(autoOpen);
  const [tawkPropertyId, setTawkPropertyId] = useState("");
  const [tawkWidgetId, setTawkWidgetId] = useState("");
  const [isScriptLoaded, setIsScriptLoaded] = useState(false);
  
  // Interactive Chat State for fallback AI Assistant
  const [messages, setMessages] = useState<Array<{ sender: "user" | "bot" | "admin" | "vendor"; text: string; time: string }>>([
    {
      sender: "bot",
      text: channel === "admin-buyer"
        ? "Hello! Welcome to SulejaMarket Support AI. How can we help you with your order, shipping, or vendor inquiries today?"
        : "Welcome Vendor Partner! This is the Admin & Vendor Support Channel. How can we assist you with payouts, verification, or inventory management?",
      time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
    }
  ]);
  const [inputMsg, setInputMsg] = useState("");

  const channelTitle = channel === "admin-buyer" ? "Buyer & Admin Live AI Support" : "Vendor & Admin Partner Chat";
  const channelSub = channel === "admin-buyer" ? "Powered by Tawk.to AI Engine" : "Direct Vendor Hub Support (Tawk.to)";

  // Dynamically attempt to load Tawk.to script if property/widget IDs are supplied in localStorage
  useEffect(() => {
    const propId = localStorage.getItem(`tawk_property_${channel}`) || "";
    const widgetId = localStorage.getItem(`tawk_widget_${channel}`) || "";
    setTawkPropertyId(propId);
    setTawkWidgetId(widgetId);

    if (propId && widgetId) {
      try {
        const s1 = document.createElement("script");
        s1.async = true;
        s1.src = `https://embed.tawk.to/${propId}/${widgetId}`;
        s1.charset = "UTF-8";
        s1.setAttribute("crossorigin", "*");
        s1.onload = () => setIsScriptLoaded(true);
        document.head.appendChild(s1);
      } catch (err) {
        console.error("Tawk.to script load error", err);
      }
    }
  }, [channel]);

  const handleSendMessage = (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputMsg.trim()) return;

    const userText = inputMsg.trim();
    const now = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    
    setMessages((prev) => [...prev, { sender: "user", text: userText, time: now }]);
    setInputMsg("");

    // Generate intelligent AI response
    setTimeout(() => {
      let replyText = "Thank you for reaching out! An administrator will review your message shortly.";
      const lower = userText.toLowerCase();

      if (channel === "admin-buyer") {
        if (lower.includes("track") || lower.includes("order") || lower.includes("package")) {
          replyText = "You can track your package anytime on our Live Order Map Tracking page! Go to your account profile or click 'Track Order' in the header for real-time driver updates.";
        } else if (lower.includes("pay") || lower.includes("paystack")) {
          replyText = "We accept secure payments via Paystack (Debit Cards, Bank Transfer, USSD). All transactions are encrypted and verified instantly!";
        } else if (lower.includes("review") || lower.includes("video")) {
          replyText = "Once your product status updates to 'Delivered', you can upload or record a video review directly on your Order details page to share your experience with other buyers!";
        } else {
          replyText = `Thanks for your inquiry about "${userText}". Our Admin support team is online and monitoring Tawk.to chat messages.`;
        }
      } else {
        // Vendor <-> Admin channel
        if (lower.includes("payout") || lower.includes("withdraw") || lower.includes("money")) {
          replyText = "Withdrawal requests are processed within 24 hours directly to your registered bank account. You can request a payout from your Vendor Dashboard overview.";
        } else if (lower.includes("product") || lower.includes("add") || lower.includes("listing")) {
          replyText = "You can list new products anytime using the 'Add Product' button in your Vendor Portal. Make sure to upload high quality product images!";
        } else if (lower.includes("verified") || lower.includes("badge")) {
          replyText = "Verification badges are granted by the Super Admin upon business review. Verified stores receive higher search ranking and buyer trust!";
        } else {
          replyText = `Admin message received. We are processing your vendor request regarding "${userText}".`;
        }
      }

      setMessages((prev) => [...prev, { sender: "bot", text: replyText, time: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }]);
    }, 800);
  };

  const handleSaveTawkConfig = (pId: string, wId: string) => {
    localStorage.setItem(`tawk_property_${channel}`, pId);
    localStorage.setItem(`tawk_widget_${channel}`, wId);
    setTawkPropertyId(pId);
    setTawkWidgetId(wId);
    toast.success("Tawk.to property credentials updated!");
  };

  return (
    <div className="fixed bottom-6 right-6 z-50">
      {!open ? (
        <button
          onClick={() => setOpen(true)}
          className={`flex items-center gap-2 px-4 py-3 rounded-full text-white font-semibold shadow-xl transition-all transform hover:scale-105 ${
            channel === "admin-buyer"
              ? "bg-gradient-to-r from-orange-500 to-amber-600 hover:from-orange-600 hover:to-amber-700"
              : "bg-gradient-to-r from-blue-600 to-indigo-700 hover:from-blue-700 hover:to-indigo-800"
          }`}
        >
          <div className="relative">
            <MessageSquare className="w-5 h-5" />
            <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-emerald-400 rounded-full animate-ping" />
            <span className="absolute -top-1 -right-1 w-2.5 h-2.5 bg-emerald-400 rounded-full" />
          </div>
          <span className="text-sm">
            {channel === "admin-buyer" ? "Live AI Chat (Buyer)" : "Vendor Admin Chat"}
          </span>
        </button>
      ) : (
        <div className="w-[360px] sm:w-[400px] h-[520px] bg-white rounded-2xl shadow-2xl border border-neutral-200 flex flex-col overflow-hidden animate-in fade-in slide-in-from-bottom-5">
          {/* Header */}
          <div className={`p-4 text-white flex items-center justify-between ${
            channel === "admin-buyer"
              ? "bg-gradient-to-r from-orange-500 to-amber-600"
              : "bg-gradient-to-r from-blue-600 to-indigo-700"
          }`}>
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-white/20 flex items-center justify-center backdrop-blur-sm">
                {channel === "admin-buyer" ? <Bot className="w-6 h-6 text-white" /> : <UserCheck className="w-6 h-6 text-white" />}
              </div>
              <div>
                <h3 className="font-bold text-sm leading-tight flex items-center gap-1.5">
                  {channelTitle}
                  <Sparkles className="w-3.5 h-3.5 text-amber-200" />
                </h3>
                <p className="text-[11px] text-white/80">{channelSub}</p>
              </div>
            </div>
            <button
              onClick={() => {
                setOpen(false);
                if (onClose) onClose();
              }}
              className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition"
            >
              <X className="w-4 h-4 text-white" />
            </button>
          </div>

          {/* Badge & Tawk.to Status Banner */}
          <div className="bg-neutral-100 border-b px-3 py-1.5 text-[11px] flex items-center justify-between text-neutral-600">
            <span className="flex items-center gap-1">
              <ShieldCheck className="w-3.5 h-3.5 text-emerald-600" />
              {isScriptLoaded ? "Tawk.to Script Active" : "Tawk.to AI Live Assistant"}
            </span>
            <span className="text-[10px] bg-emerald-100 text-emerald-800 font-medium px-2 py-0.5 rounded-full">
              Online
            </span>
          </div>

          {/* Messages */}
          <div className="flex-1 overflow-y-auto p-4 space-y-3 bg-neutral-50/50">
            {messages.map((m, i) => (
              <div
                key={i}
                className={`flex flex-col ${m.sender === "user" ? "items-end" : "items-start"}`}
              >
                <div
                  className={`max-w-[82%] px-3.5 py-2.5 rounded-2xl text-xs leading-relaxed shadow-sm ${
                    m.sender === "user"
                      ? channel === "admin-buyer"
                        ? "bg-orange-500 text-white rounded-br-none"
                        : "bg-blue-600 text-white rounded-br-none"
                      : "bg-white text-neutral-800 border border-neutral-200 rounded-bl-none"
                  }`}
                >
                  {m.text}
                </div>
                <span className="text-[10px] text-neutral-400 mt-1 px-1">{m.time}</span>
              </div>
            ))}
          </div>

          {/* Input Form */}
          <form onSubmit={handleSendMessage} className="p-3 bg-white border-t flex items-center gap-2">
            <Input
              value={inputMsg}
              onChange={(e) => setInputMsg(e.target.value)}
              placeholder="Type your message..."
              className="flex-1 text-xs h-10 border-neutral-300 focus-visible:ring-orange-500"
            />
            <Button
              type="submit"
              size="icon"
              className={`h-10 w-10 shrink-0 ${
                channel === "admin-buyer"
                  ? "bg-orange-500 hover:bg-orange-600"
                  : "bg-blue-600 hover:bg-blue-700"
              }`}
            >
              <Send className="w-4 h-4" />
            </Button>
          </form>
        </div>
      )}
    </div>
  );
}
