/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useEffect } from 'react';
import { Property, Booking, UserAccount } from '../types';
import { TIME_SLOTS } from '../data';
import { X, Calendar, Clock, Car, Tag, Sparkles, ChevronRight, CheckCircle2, IndianRupee } from 'lucide-react';

interface BookingFormProps {
  property: Property;
  onClose: () => void;
  currentUser?: UserAccount | null;
  onConfirmBooking: (bookingData: Omit<Booking, 'id' | 'propertyId' | 'propertyTitle' | 'propertyType' | 'createdAt' | 'paymentMethod' | 'paymentStatus' | 'status'>) => void;
}

export default function BookingForm({
  property,
  onClose,
  currentUser,
  onConfirmBooking,
}: BookingFormProps) {
  const isCharging = property.type === 'charging' || property.type === 'both';
  
  // States
  const [vehicleType, setVehicleType] = useState<'Car' | 'Two-Wheeler'>('Car');
  const [vehicleModel, setVehicleModel] = useState('');
  const [vehicleNumber, setVehicleNumber] = useState('');
  const [userName, setUserName] = useState('');
  const [userEmail, setUserEmail] = useState('');
  
  // Set default booking date as tomorrow or today (YYYY-MM-DD)
  const getTodayDateString = () => {
    const today = new Date();
    const yyyy = today.getFullYear();
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    return `${yyyy}-${mm}-${dd}`;
  };
  
  const [bookingDate, setBookingDate] = useState(getTodayDateString());
  const [selectedSlot, setSelectedSlot] = useState<string>('');
  const [totalHours, setTotalHours] = useState<number>(1);
  const [currentStep, setCurrentStep] = useState<1 | 2>(1);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});

  // Simulated booked slots list based on the date to demonstrate robust validation
  const [bookedSlotsOnDate, setBookedSlotsOnDate] = useState<string[]>([]);

  // Randomly simulate booked slots on date change to make the app interactive and dynamic
  useEffect(() => {
    // Seed booked slots randomly based on the selected date to show realistic state
    const hash = bookingDate.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
    const simulatedBooked: string[] = [];
    TIME_SLOTS.forEach((slot, index) => {
      // Simulate booking 25% of slots
      if ((index + hash) % 4 === 0) {
        simulatedBooked.push(slot);
      }
    });
    setBookedSlotsOnDate(simulatedBooked);
    
    // Auto reset selected slot if it belongs to booked list
    if (simulatedBooked.includes(selectedSlot)) {
      setSelectedSlot('');
    }
  }, [bookingDate]);

  // Validation
  const validateStep1 = () => {
    const newErrors: { [key: string]: string } = {};
    if (!bookingDate) {
      newErrors.bookingDate = 'Please select a booking date.';
    } else {
      const selectedDate = new Date(bookingDate);
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      if (selectedDate < today) {
        newErrors.bookingDate = 'Booking date cannot be in the past.';
      }
    }

    if (!selectedSlot) {
      newErrors.selectedSlot = 'Please select a preferred hourly time slot.';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const validateStep2 = () => {
    const newErrors: { [key: string]: string } = {};
    if (!userName.trim()) {
      newErrors.userName = 'Full Name is required.';
    }
    if (!userEmail.trim()) {
      newErrors.userEmail = 'Email address is required.';
    } else if (!/\S+@\S+\.\S+/.test(userEmail)) {
      newErrors.userEmail = 'Please provide a valid email ID.';
    }
    if (!vehicleNumber.trim()) {
      newErrors.vehicleNumber = 'Vehicle index number is required.';
    } else {
      // Validation for typical Indian format (e.g. MH12AB1234 or DL3C1235)
      const formattedNum = vehicleNumber.toUpperCase().replace(/[^A-Z0-9]/g, '');
      if (formattedNum.length < 6) {
        newErrors.vehicleNumber = 'Please specify a valid vehicle license number.';
      }
    }
    if (!vehicleModel.trim()) {
      newErrors.vehicleModel = 'Vehicle model is required (e.g. Nexon EV, Nexon, Splendor).';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleNextStep = () => {
    if (validateStep1()) {
      setCurrentStep(2);
    }
  };

  const handleConfirmSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (validateStep2()) {
      onConfirmBooking({
        userName,
        userEmail,
        vehicleNumber: vehicleNumber.toUpperCase(),
        vehicleType,
        bookingDate,
        timeSlot: selectedSlot,
        totalHours,
        totalFare
      });
    }
  };

  // Pricing calculations
  const nextDiscountPercent = currentUser?.nextDiscountPercent || 0;
  const basePrice = property.fare * totalHours;
  const convenienceFee = 15; // Flat ₹15 GST and Convenience Charge
  const discountAmount = nextDiscountPercent > 0 ? Math.round((basePrice * nextDiscountPercent) / 100) : 0;
  const totalFare = Math.max(0, basePrice + convenienceFee - discountAmount);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-sm animate-fade-in overflow-y-auto selection:bg-amber-500 selection:text-slate-900">
      <div 
        className="relative bg-slate-900 w-full max-w-lg rounded-2xl shadow-2xl border border-slate-800 overflow-hidden flex flex-col my-8"
        id="booking-modal-outer"
      >
        {/* Header Block */}
        <div className="flex items-center justify-between px-6 py-4 bg-slate-950 text-white select-none shrink-0 border-b border-slate-850">
          <div className="flex items-center gap-2">
            <div className="bg-amber-500 text-slate-950 p-1 rounded-md">
              <Calendar className="w-5 h-5 font-bold" />
            </div>
            <div>
              <h3 className="text-sm font-bold tracking-tight">Reserve Your Slot</h3>
              <p className="text-[10px] text-slate-400 font-medium truncate max-w-[240px]">{property.title}</p>
            </div>
          </div>
          
          <button
            onClick={onClose}
            className="p-1 px-1.5 rounded-full hover:bg-slate-800 text-slate-400 hover:text-white transition-colors"
            id="btn-close-modal"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Dynamic Step Status Bar */}
        <div className="bg-slate-950 px-6 py-3 flex justify-between items-center text-xs text-slate-400 border-b border-slate-850 font-medium select-none shrink-0">
          <div className="flex items-center gap-2">
            <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${currentStep === 1 ? 'bg-amber-500 text-slate-950 font-black' : 'bg-emerald-500 text-slate-950 font-black'}`}>
              {currentStep === 1 ? '1' : '✓'}
            </span>
            <span className={currentStep === 1 ? 'text-slate-200 font-bold' : 'text-slate-550 font-medium'}>Slot & Time Selection</span>
          </div>
          <ChevronRight className="w-4 h-4 text-slate-600" />
          <div className="flex items-center gap-2">
            <span className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] ${currentStep === 2 ? 'bg-amber-500 text-slate-950 font-black' : 'bg-slate-800 text-slate-500 font-bold'}`}>
              2
            </span>
            <span className={currentStep === 2 ? 'text-slate-200 font-bold' : 'text-slate-500 font-medium'}>Vehicle & Contact info</span>
          </div>
        </div>

        {/* Content Form Scroll container */}
        <div className="overflow-y-auto max-h-[70vh] flex-1">
          {currentStep === 1 ? (
            /* ================= STEP 1: TIME AND DATE ================= */
            <div className="p-6 flex flex-col gap-5 bg-slate-900">
              {/* Target Location Card Header */}
              <div className="flex gap-4 p-3 rounded-xl bg-slate-950 border border-slate-850 items-center">
                <img 
                  src={property.photo} 
                  alt={property.title} 
                  referrerPolicy="no-referrer"
                  className="w-14 h-14 rounded-lg object-cover shrink-0 border border-slate-800 shadow-sm opacity-90"
                />
                <div>
                  <h4 className="font-bold text-white text-sm">{property.title}</h4>
                  <p className="text-xs text-amber-500 font-bold mt-0.5">₹{property.fare}/hour base fare</p>
                </div>
              </div>

              {/* Step 1 Form */}
              <div className="space-y-4">
                {/* Booking Date */}
                <div>
                  <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1.5 flex items-center gap-1.5">
                    <Calendar className="w-3.5 h-3.5 text-slate-500" />
                    Select Booking Date
                  </label>
                  <input
                    type="date"
                    id="input-booking-date"
                    min={getTodayDateString()}
                    value={bookingDate}
                    onChange={(e) => setBookingDate(e.target.value)}
                    className="w-full px-3 py-2.5 rounded-lg bg-slate-950 border border-slate-800 text-slate-200 shadow-sm text-sm focus:ring-2 focus:ring-amber-500 outline-none transition-all font-semibold"
                  />
                  {errors.bookingDate && (
                    <p className="text-xs text-rose-400 mt-1 font-semibold">{errors.bookingDate}</p>
                  )}
                </div>

                {/* Grid of Hourly Time Slots */}
                <div>
                  <div className="flex items-center justify-between mb-1.5">
                    <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1.5">
                      <Clock className="w-3.5 h-3.5 text-slate-500" />
                      Select Arrival Time Slot
                    </label>
                    <span className="text-[10px] text-slate-550 font-bold">1 Hour Base Block</span>
                  </div>
                  
                  <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 max-h-48 overflow-y-auto p-2 border border-slate-800 rounded-xl bg-slate-950">
                    {TIME_SLOTS.map((slot) => {
                      const isBooked = bookedSlotsOnDate.includes(slot);
                      const isPicked = selectedSlot === slot;
                      return (
                        <button
                          key={slot}
                          type="button"
                          id={`timeslot-${slot.split(' ')[0]}`}
                          disabled={isBooked}
                          onClick={() => {
                            setSelectedSlot(slot);
                            // Clear error on select
                            if (errors.selectedSlot) {
                              setErrors(prev => ({ ...prev, selectedSlot: '' }));
                            }
                          }}
                          className={`py-2 px-1 text-[11px] text-center font-semibold rounded-lg border leading-tight transition-all
                            ${isBooked 
                              ? 'bg-slate-950 text-slate-650 border-slate-900 cursor-not-allowed line-through' 
                              : isPicked 
                                ? 'bg-amber-400 text-slate-950 border-amber-500 shadow-sm scale-[0.98]' 
                                : 'bg-slate-900 hover:bg-slate-850 text-slate-350 border-slate-800 hover:border-slate-700'}`}
                        >
                          <div>{slot.split(' - ')[0]}</div>
                          <div className={`text-[9px] mt-0.5 uppercase tracking-wide font-bold ${isBooked ? 'text-rose-500' : isPicked ? 'text-slate-950 font-black' : 'text-emerald-400'}`}>
                            {isBooked ? 'Booked' : 'Available'}
                          </div>
                        </button>
                      );
                    })}
                  </div>
                  {errors.selectedSlot && (
                    <p className="text-xs text-rose-450 mt-1 font-semibold">{errors.selectedSlot}</p>
                  )}
                </div>

                {/* Duration Slider or Selection */}
                <div>
                  <div className="flex items-center justify-between mb-1.5">
                    <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1.5 flex items-center gap-1.5">
                      <Clock className="w-3.5 h-3.5 text-slate-500" />
                      Booking Duration (Hours)
                    </label>
                    <span className="text-xs font-bold text-amber-400 bg-amber-955/40 border border-amber-900/30 px-2.5 py-0.5 rounded-full">{totalHours} {totalHours === 1 ? 'Hour' : 'Hours'}</span>
                  </div>
                  <input
                    type="range"
                    min="1"
                    max="10"
                    id="input-booking-duration"
                    value={totalHours}
                    onChange={(e) => setTotalHours(parseInt(e.target.value))}
                    className="w-full h-1.5 bg-slate-855 rounded-lg appearance-none cursor-pointer accent-amber-500 focus:outline-none"
                  />
                  <div className="flex justify-between text-[10px] text-slate-500 font-bold px-0.5 mt-1">
                    <span>1 Hour</span>
                    <span>3 hrs</span>
                    <span>5 hrs</span>
                    <span>8 hrs</span>
                    <span>10 Hours (Max)</span>
                  </div>
                </div>

                {/* Quick Booking Live Price Estimator */}
                <div className="p-4 rounded-xl border border-slate-800 bg-slate-950 flex justify-between items-center shrink-0">
                  <div className="space-y-0.5">
                    <div className="text-xs text-slate-400 font-bold flex items-center gap-1">
                      <Tag className="w-3 h-3 text-amber-500" />
                      Live Price Meter
                    </div>
                    <div className="text-[10px] text-slate-500 font-bold">₹{property.fare} x {totalHours} hour{totalHours > 1 ? 's' : ''} + GST fee</div>
                  </div>
                  <div className="text-right">
                    <div className="text-xs text-slate-500 font-bold line-through">₹{property.fare * totalHours}</div>
                    <div className="text-lg font-black text-amber-400 flex items-center justify-end">
                      <IndianRupee className="w-4 h-4 stroke-[3]" />
                      <span>{totalFare}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          ) : (
            /* ================= STEP 2: VEHICLE AND CONTACTS ================= */
            <form onSubmit={handleConfirmSubmit} className="p-6 flex flex-col gap-4 bg-slate-900">
              
              {/* Selected Slot Summary Details */}
              <div className="bg-amber-955 border border-amber-900/40 p-3.5 rounded-xl text-xs space-y-1">
                <div className="font-extrabold text-amber-400 flex items-center gap-1 text-sm">
                  <Sparkles className="w-4 h-4 text-amber-500 fill-amber-500" />
                  Slot Confirmed
                </div>
                <div className="text-slate-300 font-bold">
                  Date: <strong className="text-white">{new Date(bookingDate).toLocaleDateString('en-IN', { dateStyle: 'medium' })}</strong>
                </div>
                <div className="text-slate-300 font-bold">
                  Time slot: <strong className="text-white">{selectedSlot.split(' - ')[0]}</strong> for <strong className="text-white">{totalHours} hour{totalHours > 1 ? 's' : ''}</strong>
                </div>
              </div>

              {/* Form Input fields */}
              <div className="space-y-3">
                {/* Vehicle Type Choice */}
                <div>
                  <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-2 flex items-center gap-1.5">
                    <Car className="w-3.5 h-3.5 text-slate-500" />
                    Choose Vehicle Category
                  </label>
                  <div className="grid grid-cols-2 gap-3">
                    <button
                      type="button"
                      id="btn-category-car"
                      onClick={() => setVehicleType('Car')}
                      className={`py-2.5 px-3 rounded-xl border text-xs font-bold flex items-center justify-center gap-2 transition-all
                        ${vehicleType === 'Car' 
                          ? 'bg-amber-500 text-slate-950 border-amber-500' 
                          : 'bg-slate-950 text-slate-400 border-slate-800 hover:bg-slate-850'}`}
                    >
                      <Car className="w-4 h-4" />
                      <span>Car / Sedan / SUV</span>
                    </button>
                    
                    <button
                      type="button"
                      id="btn-category-bike"
                      onClick={() => setVehicleType('Two-Wheeler')}
                      className={`py-2.5 px-3 rounded-xl border text-xs font-bold flex items-center justify-center gap-2 transition-all
                        ${vehicleType === 'Two-Wheeler' 
                          ? 'bg-amber-500 text-slate-950 border-amber-500' 
                          : 'bg-slate-950 text-slate-405 border-slate-850 hover:bg-slate-900 hover:text-slate-350'}`}
                    >
                      <div className="font-extrabold text-sm tracking-tighter">🏍</div>
                      <span>2-Wheeler / Bike</span>
                    </button>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  {/* Vehicle Model */}
                  <div>
                    <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">
                      Vehicle Model
                    </label>
                    <input
                      type="text"
                      id="input-vehicle-model"
                      placeholder={vehicleType === 'Car' ? 'e.g. Nexon EV' : 'e.g. Ather 450X'}
                      value={vehicleModel}
                      onChange={(e) => setVehicleModel(e.target.value)}
                      className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 font-medium placeholder-slate-650"
                    />
                    {errors.vehicleModel && (
                      <p className="text-xs text-rose-455 mt-0.5 font-semibold">{errors.vehicleModel}</p>
                    )}
                  </div>

                  {/* Vehicle Number */}
                  <div>
                    <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">
                      Registration / License Plate
                    </label>
                    <input
                      type="text"
                      id="input-vehicle-number"
                      placeholder="e.g. MH12AB5678"
                      value={vehicleNumber}
                      onChange={(e) => setVehicleNumber(e.target.value)}
                      className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm uppercase text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 font-medium placeholder-slate-650"
                    />
                    {errors.vehicleNumber && (
                      <p className="text-xs text-rose-455 mt-0.5 font-semibold">{errors.vehicleNumber}</p>
                    )}
                  </div>
                </div>

                {/* Driver Full Name */}
                <div>
                  <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">
                    Driver Full Name
                  </label>
                  <input
                    type="text"
                    id="input-driver-name"
                    placeholder="Enter full name of driver"
                    value={userName}
                    onChange={(e) => setUserName(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 font-medium placeholder-slate-650"
                  />
                  {errors.userName && (
                    <p className="text-xs text-rose-455 mt-0.5 font-semibold">{errors.userName}</p>
                  )}
                </div>

                {/* Email address */}
                <div>
                  <label className="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-1">
                    Email Address
                  </label>
                  <input
                    type="email"
                    id="input-driver-email"
                    placeholder="Provide email address for invoice receipt"
                    value={userEmail}
                    onChange={(e) => setUserEmail(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-sm text-slate-200 outline-none focus:ring-2 focus:ring-amber-500 font-medium placeholder-slate-650"
                  />
                  {errors.userEmail && (
                    <p className="text-xs text-rose-455 mt-0.5 font-semibold">{errors.userEmail}</p>
                  )}
                </div>

                {/* Invoice Breakdown */}
                <div className="mt-4 border-t border-dashed border-slate-800 pt-4 space-y-1.5 text-xs text-slate-400">
                  <div className="flex justify-between">
                    <span>Base Amount (₹{property.fare} x {totalHours} hr)</span>
                    <span className="font-semibold text-slate-300">₹{basePrice}</span>
                  </div>
                  <div className="flex justify-between">
                    <span>Smart Reservation Fee & GST</span>
                    <span className="font-semibold text-slate-300">₹{convenienceFee}</span>
                  </div>
                  {discountAmount > 0 && (
                    <div className="flex justify-between text-emerald-400 font-semibold items-center">
                      <span className="flex items-center gap-1">
                        <Sparkles className="w-3.5 h-3.5" />
                        Completed Checkin Reward ({nextDiscountPercent}% Off)
                      </span>
                      <span>-₹{discountAmount}</span>
                    </div>
                  )}
                  <div className="flex justify-between border-t border-slate-800 pt-1.5 text-sm font-bold text-slate-200 mt-1">
                    <span className="text-slate-400 uppercase tracking-wider text-xs">Total Fare</span>
                    <span className="text-amber-400 flex items-center text-base font-extrabold">
                      <IndianRupee className="w-3.5 h-3.5" />
                      <span>{totalFare}</span>
                    </span>
                  </div>
                </div>
              </div>
            </form>
          )}
        </div>

        {/* Footer controls */}
        <div className="bg-slate-950 px-6 py-4 border-t border-slate-850 flex gap-3 shrink-0">
          {currentStep === 1 ? (
            <>
              <button
                type="button"
                onClick={onClose}
                className="flex-1 py-2.5 rounded-xl border border-slate-800 bg-slate-950 hover:bg-slate-900 text-slate-300 text-sm font-bold transition-all animate-none"
                id="btn-cancel-step1"
              >
                Cancel
              </button>
              
              <button
                type="button"
                onClick={handleNextStep}
                className="flex-[1.5] py-2.5 rounded-xl bg-amber-500 hover:bg-amber-400 text-slate-950 text-sm font-extrabold shadow-md transition-all flex items-center justify-center gap-1"
                id="btn-next-step"
              >
                <span>Continue Details</span>
                <ChevronRight className="w-4 h-4" />
              </button>
            </>
          ) : (
            <>
              <button
                type="button"
                onClick={() => setCurrentStep(1)}
                className="flex-1 py-2.5 rounded-xl border border-slate-800 bg-slate-950 hover:bg-slate-900 text-slate-300 text-sm font-bold transition-all"
                id="btn-back-step"
              >
                Back
              </button>
              
              <button
                type="button"
                onClick={handleConfirmSubmit}
                className="flex-[1.5] py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white text-sm font-extrabold shadow-md shadow-emerald-900/40 hover:shadow-lg transition-all flex items-center justify-center gap-1.5"
                id="btn-confirm-submit"
              >
                <CheckCircle2 className="w-4 h-4 text-emerald-100" />
                <span>Confirm & Pay ₹{totalFare}</span>
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
