import React, { useState } from 'react';
import { 
  CHARTER_PACKAGES, 
  ADD_ON_OPTIONS 
} from '../data/yachtData';
import { 
  Calendar, 
  Users, 
  Sparkles, 
  Check, 
  Plus, 
  Minus, 
  Clock, 
  Anchor, 
  MapPin, 
  Share2, 
  MessageSquare, 
  ShieldCheck, 
  ArrowRight,
  Info,
  DollarSign
} from 'lucide-react';

interface BookingCalculatorProps {
  onCompleteBooking: (bookingSummary: any) => void;
  onOpenSplitModalWithDetails: (partyDetails: any) => void;
  initialPackageId?: string;
  initialGuests?: number;
  initialDate?: string;
}

export const BookingCalculator: React.FC<BookingCalculatorProps> = ({
  onCompleteBooking,
  onOpenSplitModalWithDetails,
  initialPackageId = 'day-charter',
  initialGuests = 30,
  initialDate
}) => {
  const [selectedPkgId, setSelectedPkgId] = useState<string>(initialPackageId);
  const [guestCount, setGuestCount] = useState<number>(initialGuests);
  const [charterDate, setCharterDate] = useState<string>(() => {
    if (initialDate) return initialDate;
    const d = new Date();
    d.setDate(d.getDate() + 14);
    return d.toISOString().split('T')[0];
  });
  const [selectedDeparture, setSelectedDeparture] = useState<string>('Aberdeen Praya Road Landing No. 4 (Primary Homeport)');
  const [selectedAddOns, setSelectedAddOns] = useState<Record<string, boolean>>({
    'free-flow-champagne': true,
    'live-teak-bbq': true
  });
  const [specialRequests, setSpecialRequests] = useState<string>('');

  const currentPkg = CHARTER_PACKAGES.find(p => p.id === selectedPkgId) || CHARTER_PACKAGES[0];

  const departurePiers = [
    'Aberdeen Praya Road Landing No. 4 (Primary Homeport)',
    'Central Pier 9',
    'Central Pier 10',
    'Causeway Bay Typhoon Shelter',
    'Sai Kung Public Pier',
    'Tsim Sha Tsui Public Pier'
  ];

  const toggleAddOn = (addonId: string) => {
    setSelectedAddOns(prev => ({
      ...prev,
      [addonId]: !prev[addonId]
    }));
  };

  // Pricing calculation
  const extraGuests = Math.max(0, guestCount - currentPkg.baseGuests);
  const extraGuestTotal = extraGuests * currentPkg.extraGuestHKD;
  const baseCharterTotal = currentPkg.basePriceHKD + extraGuestTotal;

  let addOnsTotal = 0;
  const activeAddOnsList: any[] = [];

  ADD_ON_OPTIONS.forEach(addon => {
    if (selectedAddOns[addon.id]) {
      const isPerPerson = addon.pricingType === 'per-person';
      const cost = isPerPerson ? addon.priceHKD * guestCount : addon.priceHKD;
      addOnsTotal += cost;
      activeAddOnsList.push({
        ...addon,
        calculatedCost: cost
      });
    }
  });

  const grandTotal = baseCharterTotal + addOnsTotal;
  const perPersonTotal = Math.round(grandTotal / Math.max(1, guestCount));

  const handleBookNow = () => {
    const summary = {
      package: currentPkg,
      guests: guestCount,
      date: charterDate,
      departure: selectedDeparture,
      addOns: activeAddOnsList,
      baseTotal: baseCharterTotal,
      addOnsTotal,
      grandTotal,
      perPersonTotal,
      specialRequests
    };
    onCompleteBooking(summary);
  };

  const handleOpenSplit = () => {
    const partyDetails = {
      packageName: currentPkg.title,
      guests: guestCount,
      date: charterDate,
      totalCost: grandTotal,
      perPersonShare: perPersonTotal
    };
    onOpenSplitModalWithDetails(partyDetails);
  };

  return (
    <section id="packages" className="py-24 bg-[#080d17] border-t border-white/5 relative">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        
        {/* Dynamic Interactive Booking Configuration Console */}
        <div className="rounded-3xl border border-white/15 bg-slate-900 shadow-2xl p-6 sm:p-10">
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-10">
            
            {/* Left: Customization Parameters */}
            <div className="lg:col-span-7 space-y-8">
              
              <div>
                <h3 className="text-xl font-bold text-white mb-1">
                  Configure Your Charter Details
                </h3>
                <p className="text-xs text-slate-400">
                  Customizing: <strong className="text-amber-400">{currentPkg.title}</strong> ({currentPkg.duration})
                </p>
              </div>

              {/* Guest Count & Departure Pier */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
                
                {/* Guest Stepper */}
                <div className="space-y-2">
                  <label className="block text-xs font-semibold text-slate-300 uppercase tracking-wider font-mono">
                    Total Guests: {guestCount}
                  </label>
                  <div className="flex items-center gap-3">
                    <button
                      type="button"
                      onClick={() => setGuestCount(Math.max(10, guestCount - 1))}
                      className="w-10 h-10 rounded-xl bg-slate-950 border border-white/10 text-white flex items-center justify-center hover:bg-slate-800 transition-colors"
                    >
                      <Minus className="w-4 h-4" />
                    </button>
                    <div className="flex-1 text-center py-2 bg-slate-950 rounded-xl border border-white/10 text-sm font-bold font-mono text-white">
                      {guestCount} Guests
                    </div>
                    <button
                      type="button"
                      onClick={() => setGuestCount(Math.min(currentPkg.maxGuests, guestCount + 1))}
                      className="w-10 h-10 rounded-xl bg-slate-950 border border-white/10 text-white flex items-center justify-center hover:bg-slate-800 transition-colors"
                    >
                      <Plus className="w-4 h-4" />
                    </button>
                  </div>
                </div>

                {/* Date Picker */}
                <div className="space-y-2">
                  <label className="block text-xs font-semibold text-slate-300 uppercase tracking-wider font-mono">
                    Charter Date
                  </label>
                  <div className="relative">
                    <Calendar className="w-4 h-4 text-amber-400 absolute left-3.5 top-3" />
                    <input
                      type="date"
                      value={charterDate}
                      onChange={(e) => setCharterDate(e.target.value)}
                      className="w-full bg-slate-950 border border-white/10 rounded-xl pl-10 pr-4 py-2.5 text-xs text-white focus:outline-none focus:border-amber-400 font-mono"
                    />
                  </div>
                </div>

              </div>

              {/* Boarding Pier */}
              <div className="space-y-2">
                <label className="block text-xs font-semibold text-slate-300 uppercase tracking-wider font-mono">
                  Boarding & Drop-Off Pier
                </label>
                <select
                  value={selectedDeparture}
                  onChange={(e) => setSelectedDeparture(e.target.value)}
                  className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-3 text-xs text-slate-200 focus:outline-none focus:border-amber-400"
                >
                  {departurePiers.map((pier, idx) => (
                    <option key={idx} value={pier}>{pier}</option>
                  ))}
                </select>
              </div>

              {/* Bespoke Add-Ons Toggle Grid */}
              <div className="space-y-3">
                <label className="block text-xs font-semibold text-slate-300 uppercase tracking-wider font-mono">
                  Enhance Your Charter (Food, Beverage & Entertainment)
                </label>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {ADD_ON_OPTIONS.map((addon) => {
                    const isChecked = !!selectedAddOns[addon.id];
                    const isPerPerson = addon.pricingType === 'per-person';
                    const displayPrice = isPerPerson 
                      ? `+HK$ ${addon.priceHKD}/pp`
                      : `+HK$ ${addon.priceHKD.toLocaleString()} flat`;

                    return (
                      <div
                        key={addon.id}
                        onClick={() => toggleAddOn(addon.id)}
                        className={`p-3.5 rounded-2xl border transition-all cursor-pointer flex items-start justify-between gap-3 ${
                          isChecked
                            ? 'bg-slate-950 border-amber-400/80 text-white'
                            : 'bg-slate-950/40 border-white/10 text-slate-400 hover:border-white/20'
                        }`}
                      >
                        <div className="space-y-1">
                          <div className="text-xs font-bold text-slate-200">
                            {addon.name}
                          </div>
                          <p className="text-[11px] text-slate-400 line-clamp-2 leading-relaxed font-light">
                            {addon.description}
                          </p>
                          <div className="text-xs font-mono font-semibold text-amber-400">
                            {displayPrice}
                          </div>
                        </div>

                        <div className={`w-5 h-5 rounded-md border flex items-center justify-center shrink-0 mt-0.5 ${
                          isChecked 
                            ? 'bg-amber-400 border-amber-400 text-slate-950' 
                            : 'border-white/20 bg-slate-900'
                        }`}>
                          {isChecked && <Check className="w-3.5 h-3.5 stroke-[3]" />}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>

            </div>

            {/* Right: Sober Price Breakdown & Booking Action */}
            <div className="lg:col-span-5 bg-slate-950 rounded-3xl p-6 sm:p-8 border border-white/10 flex flex-col justify-between space-y-6">
              
              <div className="space-y-5">
                <div className="border-b border-white/10 pb-4">
                  <span className="text-[10px] font-mono text-amber-400 uppercase tracking-wider block">
                    Investment Summary
                  </span>
                  <h4 className="text-lg font-bold text-white">
                    {currentPkg.title}
                  </h4>
                  <div className="text-xs text-slate-400 mt-1">
                    {charterDate} • {guestCount} Guests • {selectedDeparture}
                  </div>
                </div>

                {/* Itemized lines */}
                <div className="space-y-2.5 text-xs text-slate-300">
                  <div className="flex justify-between">
                    <span>Base Charter Rate ({currentPkg.baseGuests} guests):</span>
                    <span className="font-mono text-white">HK$ {currentPkg.basePriceHKD.toLocaleString()}</span>
                  </div>

                  {extraGuests > 0 && (
                    <div className="flex justify-between text-slate-400">
                      <span>{extraGuests} Extra Guests (+HK${currentPkg.extraGuestHKD}/ea):</span>
                      <span className="font-mono text-white">HK$ {extraGuestTotal.toLocaleString()}</span>
                    </div>
                  )}

                  {activeAddOnsList.map((addon) => (
                    <div key={addon.id} className="flex justify-between text-slate-400">
                      <span className="truncate pr-2">{addon.name}:</span>
                      <span className="font-mono text-white shrink-0">HK$ {addon.calculatedCost.toLocaleString()}</span>
                    </div>
                  ))}
                </div>

                {/* Grand Total Highlight */}
                <div className="pt-4 border-t border-white/10 space-y-2">
                  <div className="flex items-baseline justify-between">
                    <span className="text-sm font-semibold text-white">Total Vessel Charter:</span>
                    <span className="text-2xl font-extrabold text-white font-mono">
                      HK$ {grandTotal.toLocaleString()}
                    </span>
                  </div>

                  <div className="p-3 rounded-xl bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-between">
                    <span className="text-xs font-medium text-emerald-400">Per Person Split:</span>
                    <span className="text-sm font-bold text-emerald-400 font-mono">
                      ~ HK$ {perPersonTotal.toLocaleString()} / guest
                    </span>
                  </div>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="space-y-3 pt-2">
                <button
                  type="button"
                  onClick={handleBookNow}
                  className="w-full py-4 rounded-xl bg-amber-400 hover:bg-amber-300 text-slate-950 font-bold text-xs uppercase tracking-wider shadow-lg hover:shadow-amber-400/20 transition-all flex items-center justify-center gap-2"
                >
                  <span>Proceed to Reserve Vessel</span>
                  <ArrowRight className="w-4 h-4 text-slate-950" />
                </button>

                <button
                  type="button"
                  onClick={handleOpenSplit}
                  className="w-full py-3 rounded-xl bg-slate-900 hover:bg-slate-800 text-sky-400 border border-sky-500/30 font-semibold text-xs tracking-wider uppercase transition-colors flex items-center justify-center gap-2"
                >
                  <Users className="w-3.5 h-3.5" />
                  <span>Generate Group Payment Split Link</span>
                </button>
              </div>

            </div>

          </div>
        </div>

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