import React, { useState } from 'react';
import { 
  Sparkles, 
  Send, 
  Bot, 
  User, 
  X, 
  CheckCircle2, 
  Calendar, 
  Wine, 
  Music, 
  Anchor,
  ArrowRight
} from 'lucide-react';

interface AiConciergeProps {
  isOpen: boolean;
  onClose: () => void;
  onApplyPlanToBooking: (plan: any) => void;
}

interface Message {
  role: 'assistant' | 'user';
  text: string;
  recommendedPkg?: string;
  recommendedGuests?: number;
}

export const AiConcierge: React.FC<AiConciergeProps> = ({
  isOpen,
  onClose,
  onApplyPlanToBooking
}) => {
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [messages, setMessages] = useState<Message[]>([
    {
      role: 'assistant',
      text: "Welcome to Entourage.hk! I'm your AI Yacht Charter Concierge. Whether you're planning a 40-person birthday junk party in Sai Kung, an executive sunset cocktail cruise in Victoria Harbour, or need beverage & catering calculations, how can I tailor your voyage today?"
    }
  ]);

  const quickPrompts = [
    {
      label: "🎉 35-Guest 30th Birthday Junk",
      prompt: "I want to host a 35-person 30th birthday party with DJ and free-flow champagne in Sai Kung. What's the best package and timeline?"
    },
    {
      label: "🌆 Corporate Skyline Mixer (Symphony of Lights)",
      prompt: "We are planning an evening corporate networking event for 40 VIP clients during the Symphony of Lights. What do you recommend?"
    },
    {
      label: "🌊 Wakeboard & Water Sports Day",
      prompt: "Our group wants an active day with the giant slide, speedboat wakeboarding, and a live teak BBQ. Suggest the ideal setup."
    },
    {
      label: "🥂 Champagne & Beverage Calculation",
      prompt: "How much champagne, wine, and beer do we need for 30 guests over an 8-hour day charter?"
    }
  ];

  const handleSend = async (userText: string) => {
    if (!userText.trim() || loading) return;

    const newMessages: Message[] = [...messages, { role: 'user', text: userText }];
    setMessages(newMessages);
    setInput('');
    setLoading(true);

    try {
      // Intelligent custom charter planner reasoning
      const textLower = userText.toLowerCase();
      let replyText = "";
      let recPkg = "day-charter";
      let recGuests = 30;

      if (textLower.includes('corporate') || textLower.includes('symphony') || textLower.includes('evening') || textLower.includes('client')) {
        recPkg = "sunset-symphony";
        recGuests = 35;
        replyText = "For corporate entertaining, our **Sunset & Harbour Lights** (6:00 PM – 10:00 PM) is magnificent. Boarding at Central Pier 9 provides effortless access for executive guests. You'll cruise past the Wan Chai & IFC skyline, positioning front-row for the 8:00 PM Symphony of Lights laser show. We recommend our **VIP Canapés & Artisan Grazing Board** combined with the **Illuminated Marble Bar Open Cocktail Service** inside the air-conditioned saloon for seamless executive mingling.";
      } else if (textLower.includes('birthday') || textLower.includes('party') || textLower.includes('dj') || textLower.includes('sai kung')) {
        recPkg = "day-charter";
        recGuests = 35;
        replyText = "For an unforgettable birthday celebration, **The Ultimate Day Odyssey** (10:00 AM – 6:00 PM) to Sai Kung's Millionaire's Beach is perfection! Here is our recommended timeline:\n\n• 10:00 AM: Boarding at Central Pier 9 with welcome chilled Prosecco\n• 11:30 AM: Anchor at secluded turquoise cove; launch giant inflatable slide & paddleboards\n• 1:30 PM: Aft-deck live Surf & Turf Teak BBQ feast (Prime ribeye & tiger prawns)\n• 3:30 PM: DJ kicks off deep house sunset set on the flybridge daybeds\n• 5:30 PM: Golden hour cruise back to Victoria Harbour with champagne flutes in hand.\n\nWith 35 guests, the total charter splits to approximately **HK$760 per person** including full open bar and BBQ!";
      } else if (textLower.includes('drink') || textLower.includes('beverage') || textLower.includes('champagne') || textLower.includes('calculate')) {
        replyText = "For an 8-hour yacht charter with 30 guests, typical consumption is:\n\n• **Champagne/Prosecco**: 18–24 bottles (approx. 4–5 glasses per guest)\n• **White & Rosé Wine**: 15–20 bottles (Whispering Angel & Sauvignon Blanc)\n• **Craft Beers & Seltzers**: 90–120 cans chilled on ice\n• **Mixers & Juices**: 40 cans of premium tonic, club soda, and fresh coconut water.\n\nAlternatively, our **VIP Free-Flow Veuve Clicquot & Open Bar Package** (HK$480/guest) handles all ice, chilling, glassware, and dedicated onboard bartenders with zero logistics hassle for the host!";
      } else {
        recPkg = "day-charter";
        replyText = "Aboard Entourage.hk, we customize every detail to match your vision. Our 75ft vessel accommodates up to 45 guests across 3 distinct zones: the upper flybridge sunbed lounge, the air-conditioned saloon with backlit marble bar, and the aft teak dining deck. Would you like me to pre-fill a tailored quote in the booking calculator for your preferred date?";
      }

      setMessages([...newMessages, { 
        role: 'assistant', 
        text: replyText,
        recommendedPkg: recPkg,
        recommendedGuests: recGuests
      }]);
    } catch (err) {
      setMessages([...newMessages, { 
        role: 'assistant', 
        text: "I'd be thrilled to help design your Entourage charter! Our 75ft superyacht is ready for day cruises, sunset cocktail evenings, and island expeditions across Hong Kong." 
      }]);
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/85 backdrop-blur-md">
      <div className="bg-slate-900 border border-purple-500/30 rounded-3xl max-w-2xl w-full h-[620px] shadow-2xl flex flex-col overflow-hidden relative">
        
        {/* Glow */}
        <div className="absolute top-0 right-0 w-64 h-64 bg-purple-500/10 rounded-full blur-3xl pointer-events-none" />

        {/* Header */}
        <div className="p-4 sm:p-5 border-b border-white/10 flex items-center justify-between bg-slate-950/70">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-purple-500/20 border border-purple-500/40 flex items-center justify-center text-purple-400">
              <Sparkles className="w-5 h-5 animate-pulse" />
            </div>
            <div>
              <div className="text-sm font-bold text-white flex items-center gap-2">
                <span>Entourage AI Charter Concierge</span>
                <span className="text-[10px] px-2 py-0.5 rounded-full bg-purple-500/20 text-purple-300 font-semibold border border-purple-500/30">
                  Instant Assistant
                </span>
              </div>
              <p className="text-xs text-slate-400">
                Itineraries, catering recommendations & guest calculators
              </p>
            </div>
          </div>

          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 text-slate-300 hover:text-white flex items-center justify-center"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Messages Body */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-4">
          {messages.map((msg, idx) => (
            <div
              key={idx}
              className={`flex gap-3 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
            >
              {msg.role === 'assistant' && (
                <div className="w-8 h-8 rounded-full bg-purple-500/20 text-purple-400 flex items-center justify-center shrink-0 border border-purple-500/30">
                  <Bot className="w-4 h-4" />
                </div>
              )}

              <div
                className={`max-w-[85%] rounded-2xl p-4 text-xs sm:text-sm leading-relaxed ${
                  msg.role === 'user'
                    ? 'bg-amber-500 text-slate-950 font-medium ml-auto'
                    : 'bg-slate-950/80 border border-white/10 text-slate-200'
                }`}
              >
                <div className="whitespace-pre-line">{msg.text}</div>

                {msg.recommendedPkg && (
                  <div className="mt-3 pt-3 border-t border-white/10 flex items-center justify-between">
                    <span className="text-[11px] text-amber-300 font-semibold">
                      Suggested: {msg.recommendedPkg.replace('-', ' ').toUpperCase()}
                    </span>
                    <button
                      onClick={() => {
                        onApplyPlanToBooking({
                          packageId: msg.recommendedPkg,
                          guests: msg.recommendedGuests || 30
                        });
                        onClose();
                      }}
                      className="px-3 py-1 rounded-lg bg-amber-400 text-slate-950 text-xs font-bold hover:bg-amber-300 transition-colors flex items-center gap-1"
                    >
                      <span>Apply to Calculator</span>
                      <ArrowRight className="w-3 h-3" />
                    </button>
                  </div>
                )}
              </div>

              {msg.role === 'user' && (
                <div className="w-8 h-8 rounded-full bg-amber-500/20 text-amber-400 flex items-center justify-center shrink-0 border border-amber-500/30">
                  <User className="w-4 h-4" />
                </div>
              )}
            </div>
          ))}

          {loading && (
            <div className="flex items-center gap-2 text-xs text-purple-400 p-2">
              <Sparkles className="w-4 h-4 animate-spin" />
              <span>Tailoring your luxury itinerary...</span>
            </div>
          )}
        </div>

        {/* Quick Suggestion Chips */}
        <div className="px-4 py-2 bg-slate-950/40 border-t border-white/5 flex gap-2 overflow-x-auto scrollbar-none">
          {quickPrompts.map((qp, i) => (
            <button
              key={i}
              onClick={() => handleSend(qp.prompt)}
              className="px-2.5 py-1 rounded-full bg-white/5 hover:bg-purple-500/20 text-slate-300 hover:text-purple-200 border border-white/10 hover:border-purple-500/30 text-[11px] whitespace-nowrap transition-colors"
            >
              {qp.label}
            </button>
          ))}
        </div>

        {/* Input Bar */}
        <div className="p-4 border-t border-white/10 bg-slate-950">
          <form
            onSubmit={(e) => {
              e.preventDefault();
              handleSend(input);
            }}
            className="flex gap-2"
          >
            <input
              type="text"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder="Ask about charter routes, open-bar packages, DJ setup, capacity..."
              className="flex-1 bg-slate-900 border border-white/15 rounded-xl px-4 py-2.5 text-xs text-white focus:outline-none focus:border-purple-400"
            />
            <button
              type="submit"
              disabled={!input.trim() || loading}
              className="px-4 py-2.5 rounded-xl bg-purple-500 hover:bg-purple-400 text-white font-bold text-xs disabled:opacity-50 transition-colors flex items-center gap-1.5"
            >
              <Send className="w-3.5 h-3.5" />
              <span>Ask</span>
            </button>
          </form>
        </div>

      </div>
    </div>
  );
};
