"use client";

import React, { useState, useEffect } from "react";
import { Property } from "@/data/portalData";
import { X, Calendar, Clock, Video, MapPin, CheckCircle2, ShieldCheck, User, Loader2, AlertCircle } from "lucide-react";
import { useAuth } from "@/context/AuthContext";
import { fetchBookedTourSlots, schedulePropertyTour } from "@/services/inquiryService";

interface TourModalProps {
  property: Property | null;
  isOpen: boolean;
  onClose: () => void;
}

const AVAILABLE_SLOTS = [
  "09:30 AM",
  "11:00 AM",
  "01:30 PM",
  "03:00 PM",
  "04:30 PM (Sunset View)",
  "06:00 PM (Twilight Tour)",
];

export default function TourModal({ property, isOpen, onClose }: TourModalProps) {
  const { user, isLoggedIn } = useAuth();

  const [tourType, setTourType] = useState<"in-person" | "video">("in-person");
  const [selectedDate, setSelectedDate] = useState(() => {
    const d = new Date();
    d.setDate(d.getDate() + 1);
    return d.toISOString().split("T")[0];
  });
  const [selectedTime, setSelectedTime] = useState("11:00 AM");
  const [bookedSlots, setBookedSlots] = useState<string[]>([]);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [notes, setNotes] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isLoadingSlots, setIsLoadingSlots] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [bookingRef, setBookingRef] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);

  useEffect(() => {
    if (user?.name) setName(user.name);
    if (user?.email) setEmail(user.email);
    if (user?.phone) setPhone(user.phone);
  }, [user, isOpen]);

  // Load booked slots whenever property or selectedDate changes
  useEffect(() => {
    if (!isOpen || !property || !selectedDate) return;
    let active = true;

    async function loadSlots() {
      setIsLoadingSlots(true);
      const propId = String(property?.id || property?.slug || "");
      const booked = await fetchBookedTourSlots(propId, selectedDate);
      if (active) {
        setBookedSlots(booked);
        setIsLoadingSlots(false);

        // If currently selected time is booked, switch to first available
        if (booked.includes(selectedTime)) {
          const firstAvailable = AVAILABLE_SLOTS.find(s => !booked.includes(s));
          if (firstAvailable) setSelectedTime(firstAvailable);
        }
      }
    }

    loadSlots();
    return () => { active = false; };
  }, [isOpen, property, selectedDate]);

  if (!isOpen || !property) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setErrorMsg(null);

    const token = typeof window !== "undefined" ? localStorage.getItem("customer_token") : null;
    const propId = String(property.id || property.slug || "");

    const res = await schedulePropertyTour(
      propId,
      {
        tour_format: tourType,
        tour_date: selectedDate,
        tour_time_slot: selectedTime,
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim(),
        message: notes.trim() || undefined,
      },
      token
    );

    setIsSubmitting(false);

    if (!res.success) {
      if (res.conflict) {
        setErrorMsg("This time slot was just booked by another client. Please select another available slot below.");
        // Refresh booked slots list
        const booked = await fetchBookedTourSlots(propId, selectedDate);
        setBookedSlots(booked);
      } else {
        setErrorMsg(res.message || "Failed to schedule viewing. Please check your contact information.");
      }
      return;
    }

    setBookingRef(res.data?.order_number || `TOUR-${Date.now().toString().slice(-6)}`);
    setSubmitted(true);
  };

  const handleResetAndClose = () => {
    setSubmitted(false);
    setErrorMsg(null);
    onClose();
  };

  const minDate = new Date().toISOString().split("T")[0];

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-black/80 backdrop-blur-md flex items-center justify-center p-4">
      <div className="bg-[#0e0e10] rounded-3xl max-w-lg w-full overflow-hidden shadow-2xl border border-[#FFE259]/30 relative animate-in fade-in zoom-in-95 duration-200 text-white max-h-[95vh] flex flex-col">
        
        {/* Close Button */}
        <button
          onClick={handleResetAndClose}
          className="absolute top-4 right-4 z-10 w-9 h-9 rounded-full bg-white/10 hover:bg-white/20 text-slate-300 hover:text-white flex items-center justify-center transition-colors cursor-pointer"
        >
          <X className="w-5 h-5" />
        </button>

        {submitted ? (
          <div className="p-8 text-center space-y-4 overflow-y-auto">
            <div className="w-16 h-16 rounded-full bg-[#059669]/20 text-[#10b981] border border-[#059669]/40 flex items-center justify-center mx-auto">
              <CheckCircle2 className="w-10 h-10" />
            </div>
            <h3 className="text-2xl font-extrabold text-white font-display-lg">
              Property Viewing Confirmed!
            </h3>
            <p className="text-sm text-slate-300">
              Your appointment for <strong>{property.title}</strong> on <strong>{selectedDate}</strong> at <strong>{selectedTime}</strong> has been secured without conflicts.
            </p>
            <div className="p-4 bg-[#18181b] rounded-2xl border border-zinc-800 text-xs text-left space-y-1.5">
              <p><strong>Booking Ref:</strong> <span className="font-mono text-[#FFE259]">{bookingRef}</span></p>
              <p><strong>Tour Format:</strong> {tourType === "in-person" ? "Private In-Person Tour" : "Live Guided 360 Video Call"}</p>
              <p><strong>Assigned Advisor:</strong> {property.agent?.name || "DreamHomes Senior Agent"} ({property.agent?.phone || "+94 11 234 5678"})</p>
              <p className="text-slate-400 text-[11px] pt-1 border-t border-zinc-800">Your viewing has been added to Inquiry Management. Our team will contact you for instant arrival coordination.</p>
            </div>
            <button
              onClick={handleResetAndClose}
              className="w-full bg-[#059669] hover:bg-[#047857] text-white font-bold py-3 rounded-full text-sm transition-all cursor-pointer shadow-lg shadow-emerald-900/30"
            >
              Done &amp; Return
            </button>
          </div>
        ) : (
          <div className="overflow-y-auto">
            {/* Header Preview */}
            <div className="relative h-28 bg-zinc-900 overflow-hidden shrink-0">
              <img
                src={property.heroImage}
                alt={property.title}
                className="w-full h-full object-cover opacity-50"
              />
              <div className="absolute inset-0 bg-gradient-to-t from-[#0e0e10] via-[#0e0e10]/40 to-transparent" />
              <div className="absolute bottom-3 left-5 right-12">
                <span className="text-[10px] font-bold uppercase tracking-widest text-[#FFE259] block">
                  Schedule Exclusive Viewing
                </span>
                <h4 className="text-white font-bold text-sm truncate">
                  {property.title}
                </h4>
                <p className="text-slate-300 text-[11px]">
                  {property.location} • LKR {property.priceLKR}M
                </p>
              </div>
            </div>

            {/* Error Banner */}
            {errorMsg && (
              <div className="m-4 mb-0 p-3 rounded-2xl bg-rose-500/10 border border-rose-500/30 text-rose-300 text-xs flex items-start gap-2.5">
                <AlertCircle className="w-4 h-4 shrink-0 mt-0.5 text-rose-400" />
                <span>{errorMsg}</span>
              </div>
            )}

            {/* Form */}
            <form onSubmit={handleSubmit} className="p-5 space-y-3.5">
              
              {/* Tour Type Selector */}
              <div>
                <label className="block text-[11px] font-semibold text-slate-300 uppercase tracking-wider mb-1.5">
                  Tour Format
                </label>
                <div className="grid grid-cols-2 gap-2">
                  <button
                    type="button"
                    onClick={() => setTourType("in-person")}
                    className={`py-2 px-3 rounded-xl text-xs font-bold flex items-center justify-center gap-2 border transition-all cursor-pointer ${
                      tourType === "in-person"
                        ? "bg-[#059669] text-white border-[#059669] shadow-sm"
                        : "bg-[#18181b] text-slate-300 border-zinc-700 hover:bg-zinc-800"
                    }`}
                  >
                    <MapPin className="w-3.5 h-3.5" />
                    <span>In-Person Tour</span>
                  </button>
                  <button
                    type="button"
                    onClick={() => setTourType("video")}
                    className={`py-2 px-3 rounded-xl text-xs font-bold flex items-center justify-center gap-2 border transition-all cursor-pointer ${
                      tourType === "video"
                        ? "bg-[#059669] text-white border-[#059669] shadow-sm"
                        : "bg-[#18181b] text-slate-300 border-zinc-700 hover:bg-zinc-800"
                    }`}
                  >
                    <Video className="w-3.5 h-3.5" />
                    <span>Live 360 Video</span>
                  </button>
                </div>
              </div>

              {/* Date & Time Slot (Collision-Free) */}
              <div className="space-y-2">
                <div className="flex items-center justify-between">
                  <label className="text-[11px] font-semibold text-slate-300 uppercase tracking-wider">
                    Viewing Date &amp; Available Time Slot
                  </label>
                  {isLoadingSlots && (
                    <span className="text-[10px] text-amber-400 flex items-center gap-1">
                      <Loader2 className="w-3 h-3 animate-spin" /> Checking Slots...
                    </span>
                  )}
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                  <div className="sm:col-span-1">
                    <input
                      type="date"
                      required
                      min={minDate}
                      value={selectedDate}
                      onChange={(e) => setSelectedDate(e.target.value)}
                      className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-[#FFE259]"
                    />
                  </div>

                  <div className="sm:col-span-2">
                    <select
                      value={selectedTime}
                      onChange={(e) => setSelectedTime(e.target.value)}
                      className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-[#FFE259] cursor-pointer"
                    >
                      {AVAILABLE_SLOTS.map((slot) => {
                        const isBooked = bookedSlots.includes(slot);
                        return (
                          <option key={slot} value={slot} disabled={isBooked}>
                            {slot} {isBooked ? "(Occupied / Booked)" : "(Available)"}
                          </option>
                        );
                      })}
                    </select>
                  </div>
                </div>
              </div>

              {/* Client Info */}
              <div className="space-y-2">
                <input
                  type="text"
                  required
                  placeholder="Your Full Name *"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#FFE259]"
                />

                <div className="grid grid-cols-2 gap-2">
                  <input
                    type="email"
                    required
                    placeholder="Email Address *"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#FFE259]"
                  />
                  <input
                    type="tel"
                    required
                    placeholder="Mobile / WhatsApp *"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#FFE259]"
                  />
                </div>

                <textarea
                  rows={2}
                  placeholder="Special instructions or questions for the agent (optional)..."
                  value={notes}
                  onChange={(e) => setNotes(e.target.value)}
                  className="w-full bg-[#18181b] border border-zinc-700 rounded-xl px-3.5 py-2 text-xs text-white focus:outline-none focus:border-[#FFE259] resize-none"
                />
              </div>

              {/* Agent Note */}
              <div className="flex items-center gap-3 p-2.5 bg-[#18181b] rounded-2xl border border-zinc-800">
                <img
                  src={property.agent?.image || "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=100&q=80"}
                  alt={property.agent?.name || "Agent"}
                  className="w-9 h-9 rounded-full object-cover border border-zinc-700 shrink-0"
                />
                <div className="text-xs min-w-0">
                  <span className="font-bold text-white block truncate">{property.agent?.name || "DreamHomes Agent"}</span>
                  <span className="text-slate-400 text-[11px] block truncate">{property.agent?.role || "Certified Property Consultant"}</span>
                </div>
              </div>

              <button
                type="submit"
                disabled={isSubmitting}
                className="w-full bg-[#059669] hover:bg-[#047857] disabled:opacity-50 text-white font-bold py-3 rounded-full text-xs uppercase tracking-wider shadow-lg shadow-[#059669]/20 transition-all cursor-pointer flex items-center justify-center gap-2"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    <span>Locking Slot &amp; Scheduling...</span>
                  </>
                ) : (
                  <span>Confirm Viewing Request</span>
                )}
              </button>
            </form>
          </div>
        )}

      </div>
    </div>
  );
}
