import React, { useState, useRef, useEffect } from "react";
import DateTimePicker from "./DateTimePicker";
import {
  User, UserPlus, Car, Calendar, CreditCard, Tag, FileText, Camera, Save, X, Info, Gauge,
  Fuel, ArrowLeft, Trash2, Printer, ChevronDown, ChevronUp, Package, DollarSign, Shield,
  CheckCircle, Percent, AlertCircle, MapPin, Video, Edit2,Flag
} from 'lucide-react';
import api from "../api";
import { useSearchParams, useLocation, useNavigate } from "react-router-dom";
import AddCustomer from "./AddCustomer";
import FinalSummary from "./FinalSummary";
import aedIcon from "../assets/download5.png";
import "./font.css";

const BookingPage = () => {
  const navigate = useNavigate();

  const [booking, setBooking] = useState({
    cus_id: "", car_id: "",
    car_brand: "", car_model: "", car_year: "", car_km: "",
    status: "pending", booking_mode: "",
    km_limit: "",
    customer_name: "", customer_email: "", customer_phone: "", customer_address: "",
    customer_license: "", customer_license_expiry: "", customer_id_expiry: "", start_date: "", end_date: "",
    base_price: "", discount_code: "", discount_percent: "0.00", discount_amount: "0.00", total_price: "",
    tax_amount: "5", advance_paid: "", deposit: "", payment_method: "Cash",
    payment_status: "Unpaid", booking_date: "", starting_kms: "", ending_kms: "", fuel_level: "", return_fuel_level: "", deposit_remarks: "",
    advance_remarks: "", invoice_remarks: "", notes: "", pickup_location: "", drop_location: "", trip_package: "Weekly"
  });

  const location = useLocation();
  const [customerResults, setCustomerResults] = useState([]);
  const [showSummaryModal, setShowSummaryModal] = useState(false);
  const [carImages, setCarImages] = useState([]);
  const [showCamera, setShowCamera] = useState(false);
  const videoRef = useRef(null);
  const canvasRef = useRef(null);
  const [stream, setStream] = useState(null);
  const [searchParams] = useSearchParams();
  const [modeOptions, setModeOptions] = useState([]);
  const [isNewCustomer, setIsNewCustomer] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [isRecording, setIsRecording] = useState(false);
  const [carVideos, setCarVideos] = useState([]);
  const mediaRecorderRef = useRef(null);
  const [existingCarImages, setExistingCarImages] = useState([]);
  const [existingCarVideos, setExistingCarVideos] = useState([]);
  const [recordingTime, setRecordingTime] = useState(0);
  const [selectedVideo, setSelectedVideo] = useState(null);
  const [selectedImage, setSelectedImage] = useState(null);
  const [activeInvoiceTab, setActiveInvoiceTab] = useState(0);

  // New States for Dropdown Update Feature
  const [selectedChargeDropdown, setSelectedChargeDropdown] = useState("");
  const [chargeInputValue, setChargeInputValue] = useState("");
  const [isAddingExtraCharge, setIsAddingExtraCharge] = useState(false);
  const [newExtraCharge, setNewExtraCharge] = useState({ name: "", amount: "" });

  const [sectionCharges, setSectionCharges] = useState([
    { cleaning: 0, damage: 0, excess_km: 0, salik: 0 },
    { cleaning: 0, damage: 0, excess_km: 0, salik: 0 }
  ]);
  const [additionalCharges, setAdditionalCharges] = useState([[]]);
  const [isCollapsed, setIsCollapsed] = useState({
    customer: false,
    car: false,
    customerExtra: true,
    inspection: false,
    logistics: false,
    payment: false,
    invoice: false,
    remarks: false
  });

  // Helper function to build correct media URL based on your API configuration
  const getMediaUrl = (filename) => {
    if (!filename) return "";
    const baseUrl = (api.defaults?.baseURL || "http://localhost:5000/api").replace(/\/api\/?$/, "");
    return `${baseUrl}/uploads/${filename}`;
  };

  const toggleCollapse = (section) => {
    setIsCollapsed(prev => ({ ...prev, [section]: !prev[section] }));
  };

  const addAdditionalCharge = (sectionIdx) => {
    setAdditionalCharges(prev => {
      const updated = [...prev];
      const sectionData = updated[sectionIdx] || [];
      updated[sectionIdx] = [...sectionData, { name: "", amount: 0 }];
      return updated;
    });
  };

  const handleAdditionalChargeChange = (sectionIdx, idx, field, value) => {
    if (field === "amount" && value !== "" && parseFloat(value) < 0) return;
    setAdditionalCharges(prev => {
      const updated = [...prev];
      updated[sectionIdx][idx][field] = field === "amount" ? (value === "" ? "" : parseFloat(value) || 0) : value;
      return updated;
    });
  };

  const removeAdditionalCharge = (sectionIdx, idx) => {
    setAdditionalCharges(prev => {
      const updated = [...prev];
      updated[sectionIdx] = updated[sectionIdx].filter((_, i) => i !== idx);
      return updated;
    });
  };

  const totalDays = booking.start_date && booking.end_date
    ? Math.ceil(Math.abs(new Date(booking.end_date) - new Date(booking.start_date)) / (1000 * 60 * 60 * 24))
    : 0;

  const numberOfSections = Math.ceil(totalDays / 30);

  useEffect(() => {
    if (numberOfSections === 0) return;
    const tabStr = searchParams.get("tab");
    if (tabStr !== null) {
      const tab = parseInt(tabStr, 10);
      const validTab = isNaN(tab) ? 0 : tab;
      setActiveInvoiceTab(validTab < numberOfSections ? validTab : 0);
    }
  }, [searchParams, numberOfSections]);

  const getDays = (start, end) => {
    if (!start || !end) return 1;
    const s = new Date(start);
    const e = new Date(end);
    const diff = Math.ceil((e - s) / (1000 * 60 * 60 * 24));
    return diff <= 0 ? 1 : diff;
  };

  const handleSectionChargeChange = (sectionIdx, field, value) => {
    if (value !== "" && parseFloat(value) < 0) return;
    const newVal = parseFloat(value) || 0;
    setSectionCharges(prev => {
      const updated = [...prev];
      updated[sectionIdx] = { ...updated[sectionIdx], [field]: value === "" ? "" : newVal };
      return updated;
    });
  };

  const handleUpdateDropdownCharge = () => {
    if (!selectedChargeDropdown || chargeInputValue === "") return;

    if (selectedChargeDropdown.startsWith('add_')) {
      const idx = parseInt(selectedChargeDropdown.split('_')[1]);
      handleAdditionalChargeChange(activeInvoiceTab, idx, "amount", chargeInputValue);
    } else {
      handleSectionChargeChange(activeInvoiceTab, selectedChargeDropdown, chargeInputValue);
    }

    // Clear selection after update
    setChargeInputValue("");
    setSelectedChargeDropdown("");
  };

  useEffect(() => {
    setSectionCharges(prev => {
      const newCharges = [...prev];
      while (newCharges.length < numberOfSections) {
        newCharges.push({ cleaning: 0, damage: 0, excess_km: 0, salik: 0 });
      }
      return newCharges;
    });
  }, [numberOfSections]);

  useEffect(() => {
    setAdditionalCharges(prev => {
      const newAdd = [...prev];
      while (newAdd.length < numberOfSections) {
        newAdd.push([]);
      }
      return newAdd;
    });
  }, [numberOfSections]);

  useEffect(() => {
    const baseRate = parseFloat(booking.base_price) || 0;
    const gstPercent = parseFloat(booking.tax_amount) || 0;
    const totalBaseRent = baseRate * totalDays;

    const additionalChargesTotal = additionalCharges.reduce((acc, section) => {
      if (!section) return acc;
      return acc + section.reduce((sum, item) => sum + (parseFloat(item?.amount) || 0), 0);
    }, 0);

    const allExtraCharges = sectionCharges.reduce((acc, sec) =>
      acc + (parseFloat(sec?.cleaning) || 0) + (parseFloat(sec?.damage) || 0) + (parseFloat(sec?.excess_km) || 0) + (parseFloat(sec?.salik) || 0), 0)
      + additionalChargesTotal;

    const subTotal = totalBaseRent + allExtraCharges;
    const gstAmount = (subTotal * gstPercent) / 100;
    const finalGrandTotal = subTotal + gstAmount;

    setBooking(prev => ({
      ...prev,
      total_price: finalGrandTotal.toFixed(2)
    }));
  }, [booking.base_price, booking.tax_amount, booking.start_date, booking.end_date, sectionCharges, additionalCharges]);

  // AUTOSAVE EFFECT
  useEffect(() => {
    if (!booking.id) return;

    const timer = setTimeout(async () => {
      try {
        const totalCleaning = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.cleaning) || 0), 0);
        const totalDamage = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.damage) || 0), 0);
        const totalExcessKm = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.excess_km) || 0), 0);
        const totalSalik = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.salik) || 0), 0);

        const payload = {
          cleaning_charges: totalCleaning,
          damage_charges: totalDamage,
          excess_km_charges: totalExcessKm,
          salik_charges: totalSalik,
          section_charges: sectionCharges,
          additional_charges: additionalCharges,
          total_price: booking.total_price
        };

        await api.put(`/bookings/${booking.id}/charges`, payload);
      } catch (err) {
        console.error("Auto-save charges error:", err);
      }
    }, 1000);

    return () => clearTimeout(timer);
  }, [sectionCharges, additionalCharges, booking.total_price, booking.id]);

  useEffect(() => {
    window.scrollTo(0, 0);
  }, []);

  useEffect(() => {
    const initPage = async () => {
      const bookingId = searchParams.get("id");
      const carIdFromUrl = searchParams.get("car_id");

      if (bookingId) {
        try {
          const res = await api.get(`/bookings/${bookingId}`);
          const data = res.data;

          if (data.section_charges) {
            try {
              const parsed = typeof data.section_charges === "string" ? JSON.parse(data.section_charges) : data.section_charges;
              if (Array.isArray(parsed) && parsed.length > 0) {
                setSectionCharges(parsed);
              }
            } catch (e) {
              console.error("Error parsing section_charges:", e);
            }
          } else if (data.cleaning_charges !== undefined) {
            setSectionCharges(prev => {
              const newCharges = [...prev];
              newCharges[0] = {
                cleaning: parseFloat(data.cleaning_charges) || 0,
                damage: parseFloat(data.damage_charges) || 0,
                excess_km: parseFloat(data.excess_km_charges) || 0,
                salik: parseFloat(data.salik_charges) || 0
              };
              return newCharges;
            });
          }

          setBooking(prev => ({
            ...prev,
            id: data.id || data.booking_id,
            status: data.status || "pending",
            booking_mode: data.booking_mode || "",
            cus_id: data.cus_id || "",
            customer_name: data.full_name || "",
            customer_email: data.email || "",
            customer_phone: data.mobile || "",
            customer_license: data.license_number || "",
            customer_license_expiry: data.license_expiry_date ? data.license_expiry_date.split('T')[0] : "",
            customer_id_expiry: data.id_expiry_date ? data.id_expiry_date.split('T')[0] : "",
            car_id: data.car_id || "",
            car_brand: data.brand || "",
            car_model: data.model || "",
            car_year: data.year || "",
            starting_kms: data.starting_kms || "",
            fuel_level: data.fuel_level || "",
            start_date: data.start_date || "",
            end_date: data.end_date || "",
            booking_date: data.booking_date || "",
            ending_kms: data.ending_kms || "",
            return_fuel_level: data.return_fuel_level || "",
            notes: data.notes || "",
            base_price: data.base_price || "",
            tax_amount: data.tax_amount || "0.00",
            deposit: (data.deposit && parseFloat(data.deposit) >= 0) ? data.deposit : "",
            advance_paid: (data.advance_paid && parseFloat(data.advance_paid) >= 0) ? data.advance_paid : "",
            total_price: (data.total_price && parseFloat(data.total_price) >= 0) ? data.total_price : "",
            payment_status: data.payment_status || "Unpaid",
            amount_collected: (data.amount_collected && parseFloat(data.amount_collected) >= 0) ? data.amount_collected : "",
            payment_method: data.payment_type || data.payment_method || "Cash",
            deposit_remarks: data.deposit_remarks || "",
            advance_remarks: data.advance_remarks || "",
            invoice_remarks: data.invoice_remarks || "",
            pickup_location: data.pickup_location || "",
            drop_location: data.drop_location || "",
            trip_package: data.trip_package || ""
          }));

          const imagesData = typeof data.car_images === 'string' ? JSON.parse(data.car_images) : data.car_images;
          const videosData = typeof data.car_videos === 'string' ? JSON.parse(data.car_videos) : data.car_videos;
          setExistingCarImages(imagesData || []);
          setExistingCarVideos(videosData || []);

          if (data.additional_charges) {
            try {
              const parsed = typeof data.additional_charges === 'string' ? JSON.parse(data.additional_charges) : data.additional_charges;
              setAdditionalCharges(parsed || []);
            } catch (e) {
              setAdditionalCharges([]);
            }
          } else {
            setAdditionalCharges([]);
          }

        } catch (err) {
          console.error("Booking Fetch Error:", err);
        }
      } else if (carIdFromUrl || location.state?.car) {
        const carData = location.state?.car;

        if (carData) {
          setBooking(prev => ({
            ...prev,
            car_id: carData.id,
            car_brand: carData.brand,
            car_model: carData.model,
            car_year: carData.year,
            starting_kms: carData.current_km || carData.kilometers,
            fuel_level: carData.current_fuel || ""
          }));
        } else if (carIdFromUrl) {
          try {
            const res = await api.get(`/cars/${carIdFromUrl}`);
            const car = res.data;
            setBooking(prev => ({
              ...prev,
              car_id: car.id,
              car_brand: car.brand,
              car_model: car.model,
              car_year: car.year,
              starting_kms: car.current_km || car.kilometers,
              fuel_level: car.current_fuel || ""
            }));
          } catch (err) { }
        }
      }
    };

    initPage();
  }, [searchParams, location.state]);

  const saveBookingData = async () => {
    const formData = new FormData();

    const excludeFromBackend = [
      'customer_name', 'customer_email', 'customer_phone', 'customer_address',
      'customer_license', 'customer_license_expiry', 'customer_id_expiry',
      'car_brand', 'car_model', 'car_year', 'car_km'
    ];

    formData.append("additional_charges", JSON.stringify(additionalCharges));
    const totalCleaning = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.cleaning) || 0), 0);
    const totalDamage = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.damage) || 0), 0);
    const totalExcessKm = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.excess_km) || 0), 0);
    const totalSalik = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.salik) || 0), 0);

    formData.append("cleaning_charges", totalCleaning);
    formData.append("damage_charges", totalDamage);
    formData.append("excess_km_charges", totalExcessKm);
    formData.append("salik_charges", totalSalik);
    formData.append("section_charges", JSON.stringify(sectionCharges));

    Object.keys(booking).forEach((key) => {
      if (!excludeFromBackend.includes(key) && booking[key] !== null && booking[key] !== undefined && booking[key] !== "") {
        // Skip empty start_date and end_date
        if ((key === 'start_date' || key === 'end_date') && booking[key] === '') {
          return;
        }
        formData.append(key, booking[key]);
      }
    });

    carImages.forEach((file) => formData.append("car_images", file));
    carVideos.forEach((file) => formData.append("car_videos", file));
    formData.append("existing_images", JSON.stringify(existingCarImages));
    formData.append("existing_videos", JSON.stringify(existingCarVideos));

    try {
      let response;
      if (booking.id) {
        response = await api.put(`/bookings/${booking.id}`, formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
      } else {
        response = await api.post("/bookings", formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
      }

      const updatedData = response.data;
      const newId = updatedData.id || updatedData.booking_id;

      setBooking(prev => ({
        ...prev,
        id: newId,
        tax_amount: updatedData.tax_amount || prev.tax_amount,
        total_price: updatedData.total_price || prev.total_price
      }));

      setExistingCarImages(typeof updatedData.car_images === 'string' ? JSON.parse(updatedData.car_images) : updatedData.car_images || []);
      setExistingCarVideos(typeof updatedData.car_videos === 'string' ? JSON.parse(updatedData.car_videos) : updatedData.car_videos || []);
      setCarImages([]);
      setCarVideos([]);

      if (booking.car_id && booking.ending_kms && booking.return_fuel_level) {
        try {
          await api.put(`/cars/${booking.car_id}`, {
            current_km: booking.ending_kms,
            current_fuel: booking.return_fuel_level
          });
        } catch (fleetErr) { }
      }

      return newId;
    } catch (err) {
      alert("Error saving: " + (err.response?.data?.message || err.message));
      return null;
    }
  };

  const handlePrint = async (type, sectionIndex = null) => {
    const savedId = await saveBookingData();

    if (!savedId) {
      alert("Failed to save booking before printing! Please check the details.");
      return;
    }

    let url = `${window.location.origin}/car/print/${type}/${savedId}`;
    if (type === "invoice" && sectionIndex !== null) {
      url += `?tab=${sectionIndex}`;
    }
    window.open(url, "_blank");
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // Check if security deposit or advance amount is presented, update status to confirmed
    if (booking.status === 'pending' && (parseFloat(booking.deposit) > 0 || parseFloat(booking.advance_paid) > 0)) {
      booking.status = 'confirmed';
      setBooking(prev => ({ ...prev, status: 'confirmed' }));
    }

    const savedId = await saveBookingData();
    if (!booking.cus_id) {
      alert('❌ Please select a customer');
      return;
    }

    // Only check if car is selected
    if (!booking.car_id) {
      alert('❌ Please select a car');
      return;
    }
    if (savedId) {
      alert(booking.id ? "Booking Updated Successfully! ✅" : "Booking Registered Successfully! ");
    }
  };

  const handleSuccess = (newCustomer) => {
    setBooking(prev => ({
      ...prev,
      cus_id: newCustomer.cus_id,
      customer_name: newCustomer.full_name,
      customer_email: newCustomer.email,
      customer_phone: newCustomer.mobile,
      customer_license: newCustomer.license_number,
      customer_license_expiry: newCustomer.license_expiry_date ? newCustomer.license_expiry_date.split('T')[0] : "",
      customer_id_expiry: newCustomer.id_expiry_date ? newCustomer.id_expiry_date.split('T')[0] : ""
    }));
    setIsNewCustomer(false);
    setShowModal(false);
  };

  useEffect(() => {
    const carId = searchParams.get("car_id");
    if (carId) setBooking(prev => ({ ...prev, car_id: carId }));
  }, [searchParams]);

  useEffect(() => {
    if (location.state?.car) {
      const car = location.state.car;
      setBooking(prev => ({
        ...prev,
        car_id: car.id, car_brand: car.brand, car_model: car.model, car_year: car.year, car_km: car.kilometers
      }));
    }
  }, [location]);

  useEffect(() => {
    if (!booking.car_id) return;
    const fetchModes = async () => {
      try {
        const res = await api.get(`/cars/${booking.car_id}/pricing`);
        console.log("Modes from API:", res.data);

        const formatted = res.data.map(o => ({
          mode: o.mode || o.category,
          label: o.label || o.category,
          km: o.km,
          price: o.price
        }));
        setModeOptions(formatted);
      } catch (err) { console.error(err); }
    };
    fetchModes();
  }, [booking.car_id]);

  const handleModeChange = (e) => {
    const selectedFullText = e.target.value;

    if (!selectedFullText) {
      setBooking(prev => ({
        ...prev,
        booking_mode: "",
        base_price: "",
        total_price: "",
        km_limit: ""
      }));
      return;
    }

    // Find the selected option from modeOptions
    const selected = modeOptions.find(m => `${m.label} - ${m.km} KM - AED ${m.price}` === selectedFullText);

    if (selected) {
      // Extract the numeric price from the string (remove "AED" and trim)
      const priceValue = parseFloat(selected.price) || 0;

      setBooking(prev => ({
        ...prev,
        booking_mode: selectedFullText,
        km_limit: selected.km,
        base_price: priceValue, // Set the base price
        total_price: priceValue  // Initially set total price same as base
      }));
    }
  };

  useEffect(() => {
    let interval;
    if (isRecording) {
      setRecordingTime(0);
      interval = setInterval(() => {
        setRecordingTime((prev) => prev + 1);
      }, 1000);
    } else {
      clearInterval(interval);
    }
    return () => clearInterval(interval);
  }, [isRecording]);

  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const startRecording = () => {
    if (!stream) {
      alert("Please open the camera first!");
      return;
    }
    const mimeType = MediaRecorder.isTypeSupported("video/webm") ? "video/webm" : "video/mp4";
    const mediaRecorder = new MediaRecorder(stream, { mimeType });
    mediaRecorderRef.current = mediaRecorder;

    const localChunks = [];
    mediaRecorder.ondataavailable = (event) => {
      if (event.data && event.data.size > 0) {
        localChunks.push(event.data);
      }
    };

    mediaRecorder.onstop = () => {
      const blob = new Blob(localChunks, { type: mimeType });
      const file = new File([blob], `car_video_${Date.now()}.${mimeType.split('/')[1]}`, { type: mimeType });
      setCarVideos(prev => [...prev, file]);
      setIsRecording(false);
    };

    mediaRecorder.start();
    setIsRecording(true);
  };

  const stopRecording = () => {
    if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") {
      mediaRecorderRef.current.stop();
    }
  };

  const handleInputChange = (e) => {
    let { name, value, type } = e.target;
    if (type === "number" && value !== "" && parseFloat(value) < 0) return;
    setBooking(prev => ({ ...prev, [name]: value }));
  };

  const openCamera = async () => {
    try {
      const s = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
      setStream(s); setShowCamera(true);
      setTimeout(() => { if (videoRef.current) videoRef.current.srcObject = s; }, 100);
    } catch (err) { alert("Camera access denied"); }
  };

  const capturePhoto = () => {
    const canvas = canvasRef.current;
    const video = videoRef.current;
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    const ctx = canvas.getContext("2d");
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
    canvas.toBlob((blob) => {
      const file = new File([blob], `car_${Date.now()}.jpg`, { type: "image/jpeg" });
      setCarImages(prev => [...prev, file]);
    }, "image/jpeg");
  };

  const selectCustomer = (c) => {
    setBooking(prev => ({
      ...prev,
      cus_id: c.cus_id || "",
      customer_name: c.full_name || "",
      customer_email: c.email || "",
      customer_phone: c.mobile || "",
      customer_license: c.license_number || "",
      customer_license_expiry: c.license_expiry_date ? c.license_expiry_date.split('T')[0] : "",
      customer_id_expiry: c.id_expiry_date ? c.id_expiry_date.split('T')[0] : ""
    }));
    setIsNewCustomer(false);
    setCustomerResults([]);
  };

  const grandTotal = parseFloat(booking.total_price || 0);
  const collectedAmount = booking.payment_status === 'Paid'
    ? grandTotal
    : (parseFloat(booking.amount_collected) || parseFloat(booking.advance_paid) || 0);
  const balanceToPay = Math.max(0, grandTotal - collectedAmount);

  const now = new Date();
  const todayString = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;

  return (
    <div className="glass-page-bg container-fluid">
      <div className="compact-container">
        <form className="row g-2" onSubmit={handleSubmit}>

          <div className="d-flex justify-content-between align-items-center mb-4">
            <div className="d-flex align-items-center gap-2">
              <h4 className="booking-title m-0">
                <Car size={20} className="me-2 text-primary" />
                {booking.id ? "Edit Booking" : "New Booking"}
              </h4>
              {booking.id && (
                <span className="booking-id-badge ms-2">
                  # {booking.id}
                </span>
              )}
            </div>

            <button
              type="button"
              className="btn btn-outline-light btn-sm"
              onClick={() => navigate(-1)}
            >
              <ArrowLeft size={14} className="me-1" />
              Back
            </button>
          </div>

          {/* Left Column */}
          <div className="col-12 col-xl-6">

            {/* Customer Section */}
            <div className="glass-panel" style={{ paddingTop: "10px" }}>
              <div className="d-flex justify-content-between align-items-start mb-1" style={{ flexWrap: 'wrap', gap: '8px' }}>
                <div className="d-flex align-items-center" style={{ marginTop: "10px" }}>
                  <h4 className="panel-title" style={{ fontSize: '13px', whiteSpace: 'nowrap', marginBottom: '0' }}>
                    <User size={16} className="me-1" />
                    {booking.cus_id && (
                      <>
                        ID :
                        <span className="ms-2 customer-id-badge" style={{ fontSize: '12px' }}>
                          {booking.cus_id}
                        </span>
                      </>
                    )}
                  </h4>
                </div>
                <div style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '10px',
                  flexWrap: 'wrap',
                  flex: '1 1 auto',
                  maxWidth: '100%',
                  marginLeft: 'auto',
                    justifyContent: 'flex-end'
                }}>

                  {!isNewCustomer && !booking.cus_id && (
                    <div style={{
                      position: 'relative',
                      flex: '1 1 200px',
                      minWidth: '150px',
                      maxWidth: '280px',
                      marginBottom:"13px",
                      marginLeft: 'auto'
                    }}>
                      <input
                        className="form-control glass-input"
                        placeholder="Search by name / phone / email..."
                        style={{
                          height: '32px',
                          fontSize: '12px',
                          width: '100%',
                          padding: '2px 10px',

                        }}
                        onChange={async (e) => {
                          const text = e.target.value;
                          if (text.length < 2) { setCustomerResults([]); return; }
                          try {
                            const res = await api.get(`/customers/search?q=${text}`);
                            setCustomerResults(res.data);
                          } catch (err) { }
                        }}
                      />
                      {customerResults.length > 0 && (
                        <div className="search-dropdown shadow-lg" style={{
                          position: 'absolute',
                          marginTop: "4px",
                          zIndex: 1050,
                          width: '100%',
                          maxHeight: '200px',
                          overflowY: 'auto',
                          background: '#1e293b',
                          borderRadius: '8px',
                          marginRight: "160px",
                          border: '1px solid rgba(255,255,255,0.1)'
                        }}>
                          {customerResults.map((c, index) => (
                            <div key={c.cus_id || index} className="search-item" onClick={() => selectCustomer(c)}>
                              <div className="cus-info">
                                <span className="cus-name" style={{ fontSize: '13px' }}>{c.full_name}</span>
                                <span className="cus-meta" style={{ fontSize: '10px' }}>{c.mobile} • ID: {c.cus_id}</span>
                              </div>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  )}

                  <div  style={{
                      marginLeft: 'auto',
                      display: 'flex',
                      alignItems: 'center',
                      marginBottom: '13px'
                    }}>
                    {!isNewCustomer ? (
                      booking.cus_id ? (
                        <button
                          type="button"
                          className="btn btn-primary add-customer-btn"
                        style={{ minWidth: '60px', display: 'flex', justifyContent: 'flex-end' }}
                          onClick={() => setBooking(prev => ({
                            ...prev,
                            cus_id: "",
                            customer_name: "",
                            customer_phone: "",
                            customer_email: "",
                            customer_license: "",
                            customer_license_expiry: "",
                            customer_id_expiry: ""
                          }))}
                        >
                          <X size={12} /> Change
                        </button>
                      ) : (
                        <button
                          type="button"
                          className="btn btn-primary add-customer-btn"
                          style={{
                            height: '32px',
                            padding: '2px 14px',
                            fontSize: '12px',
                            whiteSpace: 'nowrap',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '4px',

                          }}
                          onClick={() => { setShowModal(true); setIsNewCustomer(true); }}
                        >
                          <UserPlus size={14} /> New Customer
                        </button>
                      )
                    ) : (
                      <button
                        type="button"
                        className="btn btn-outline-light"
                        style={{
                          height: '32px',
                          padding: '0 14px',
                          fontSize: '12px',
                          whiteSpace: 'nowrap',
                          display: 'flex',
                          alignItems: 'center',
                          gap: '4px'
                        }}
                        onClick={() => setIsNewCustomer(false)}
                      >
                        <ArrowLeft size={12} /> Search Existing
                      </button>
                    )}
                  </div>
                </div>
              </div>

              <div className="row g-2">
                {isNewCustomer && <div className="new-cus-status-box col-12">Please register the customer in the popup window.</div>}
                {!isNewCustomer && (
                  <>
                    <div className="col-md-6">
                      <label className="field-label">Full Name</label>
                      <input className="form-control glass-input" name="customer_name" value={booking.customer_name} onChange={handleInputChange} placeholder="XXX.." readOnly />
                    </div>
                    <div className="col-md-6">
                      <label className="field-label">Phone</label>
                      <input className="form-control glass-input" name="customer_phone" value={booking.customer_phone} onChange={handleInputChange} placeholder="+971" readOnly />
                    </div>
                  </>
                )}
              </div>

              <div
                className="d-flex justify-content-between align-items-center mt-2 pt-2"
                style={{ borderTop: '1px solid rgba(255,255,255,0.06)', cursor: 'pointer' }}
                onClick={() => toggleCollapse('customerExtra')}
              >
                <span style={{ fontSize: '11px', color: '#94a3b8', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                  <Info size={14} className="me-1" /> Additional Details
                </span>
                <span style={{ color: '#94a3b8' }}>
                  {isCollapsed.customerExtra ? <ChevronDown size={16} /> : <ChevronUp size={16} />}
                </span>
              </div>
              {!isCollapsed.customerExtra && !isNewCustomer && (
                <div className="row g-2 mt-2" style={{ animation: 'slideDown 0.25s ease' }}>
                  <div className="col-md-6">
                    <label className="field-label">Email</label>
                    <input className="form-control glass-input" name="customer_email" value={booking.customer_email} onChange={handleInputChange} placeholder="XXX@gmail.com" readOnly />
                  </div>
                  <div className="col-md-6 ">
                    <label className="field-label">Driver License No</label>
                    <input className="form-control glass-input " name="customer_license" value={booking.customer_license} onChange={handleInputChange} placeholder="1234567890" readOnly />
                  </div>
                  <div className="col-md-6 ">
                    <label className="field-label mt-2">License Expiry Date</label>
                    <input type="date" className="form-control glass-input" name="customer_license_expiry" value={booking.customer_license_expiry} onChange={handleInputChange} readOnly />
                  </div>
                  <div className="col-md-6">
                    <label className="field-label mt-2">Emirates ID Expiry Date</label>
                    <input type="date" className="form-control glass-input" name="customer_id_expiry" value={booking.customer_id_expiry} onChange={handleInputChange} readOnly />
                  </div>
                </div>
              )}
            </div>

            {/* Vehicle Details Section */}
            <div className="booking-card">
              <div className="section-header d-flex justify-content-between align-items-center" onClick={() => toggleCollapse('car')}>
                <div className="d-flex align-items-center gap-2">
                  <Car size={18} className="text-warning" />
                  <h4 className="panel-title m-0">Vehicle Details</h4>
                  {booking.car_id ? (
                    <span className="badge bg-success ms-2">Selected</span>
                  ) : (
                    <span className="badge bg-warning ms-2">Required</span>
                  )}
                </div>
                <div className="d-flex align-items-center gap-2">
                  {isCollapsed.car ? <ChevronDown size={18} /> : <ChevronUp size={18} />}
                </div>
              </div>
              {!isCollapsed.car && (
                <div className="section-body">
                  <div className="row g-2">
                    <div className="col-md-2">
                      <label className="field-label">Car ID</label>
                      <input className="form-control glass-input" value={booking.car_id || "Not selected"} readOnly />
                    </div>
                    <div className="col-md-3">
                      <label className="field-label">Brand</label>
                      <input className="form-control glass-input" value={booking.car_brand || "-"} readOnly />
                    </div>
                    <div className="col-md-5 mt-2">
                      <label className="field-label">Model</label>
                      <input className="form-control glass-input" value={booking.car_model || "-"} readOnly />
                    </div>
                    <div className="col-md-2 mb-0">
                      <label className="field-label">Year</label>
                      <input className="form-control glass-input" value={booking.car_year || "-"} readOnly />
                    </div>
                  </div>
                </div>
              )}
            </div>

{/* Inspection Section */}
            <div className="booking-card">
              <div className="section-header d-flex justify-content-between align-items-center" onClick={() => toggleCollapse('inspection')}>
                <div className="d-flex align-items-center gap-2">
                  <Camera size={18} className="text-info" />
                  <h4 className="panel-title m-0">Inspection & Media</h4>
                </div>
                <div className="d-flex align-items-center gap-2">
                  {isCollapsed.inspection ? <ChevronDown size={18} /> : <ChevronUp size={18} />}
                </div>
              </div>
              {!isCollapsed.inspection && (
                <div className="section-body">
                  <div className="camera-controls d-flex gap-2 flex-wrap mb-3">
                    {!showCamera ? (
                      <button type="button" onClick={openCamera} className="mini-cam-btn btn-open-camera" style={{ flex: 1 }}>
                        <Camera size={16} className="me-1" /> Open Camera
                      </button>
                    ) : (
                      <>
                        <button
                          type="button"
                          onClick={isRecording ? stopRecording : startRecording}
                          className="mini-cam-btn"
                          style={{
                            flex: 1,
                            height: "36px",
                            padding: "4px 12px",
                            ...(isRecording
                              ? {
                                background: "linear-gradient(135deg, #bf6d6d, #ee5757)",
                                color: "#f8f2f2",
                                border: "1px solid #bd8282",
                              }
                              : {
                                background:
                                  "linear-gradient(135deg, rgba(34, 197, 94, 0.15), rgba(34, 197, 94, 0.05))",
                                color: "#22c55e",
                                border: "1px solid rgba(34, 197, 94, 0.15)",
                              })
                          }}
                        >
                          {isRecording ? <X size={16} /> : <Video size={16} />} {isRecording ? "Stop Video" : "Record Video"}
                        </button>
                        <button type="button" onClick={capturePhoto} className="btn-capture" style={{ flex: 1, height: "36px", padding: "4px 12px", }}>
                          <Camera size={16} /> Capture
                        </button>
                        <button type="button" className="btn-close-camera" onClick={() => { if (isRecording) stopRecording(); stream.getTracks().forEach(t => t.stop()); setShowCamera(false); }} style={{ flex: 1, height: "36px", padding: "4px 12px", }}>
                          <X size={16} /> Close Camera
                        </button>
                      </>
                    )}
                  </div>

                  {showCamera && (
                    <div className="camera-preview mb-3 position-relative" style={{ height: '200px', borderRadius: '12px', overflow: 'hidden' }}>
                      <video ref={videoRef} autoPlay muted playsInline className="w-100 h-100" style={{ objectFit: 'cover' }} />
                      {isRecording && (
                        <div className="recording-indicator">
                          <div className="blink-dot" /> <span>{formatTime(recordingTime)}</span>
                        </div>
                      )}
                      <canvas ref={canvasRef} hidden />
                    </div>
                  )}

                  <div className="media-grid d-flex flex-wrap gap-2">
                    {existingCarImages.map((imgName, i) => (
                      <div key={`ex-img-${i}`} className="mini-thumb" onClick={() => setSelectedImage(getMediaUrl(imgName))}>
                        <img src={getMediaUrl(imgName)} alt="car" />
                        <button type="button" className="delete-icon-btn" onClick={(e) => { e.stopPropagation(); setExistingCarImages(existingCarImages.filter((_, idx) => idx !== i)); }}><Trash2 size={12} color="white" strokeWidth={3} /></button>
                      </div>
                    ))}
                    {carImages.map((file, i) => (
                      <div key={`new-img-${i}`} className="mini-thumb new-border" onClick={() => setSelectedImage(URL.createObjectURL(file))}>
                        <img src={URL.createObjectURL(file)} alt="new" />
                        <span className="new-badge">NEW</span>
                        <button type="button" className="delete-icon-btn" onClick={(e) => { e.stopPropagation(); setCarImages(carImages.filter((_, idx) => idx !== i)); }}><Trash2 size={12} color="white" strokeWidth={3} /></button>
                      </div>
                    ))}
                    {existingCarVideos.map((vidName, i) => (
                      <div key={`ex-vid-${i}`} className="mini-thumb video-thumb" onClick={() => setSelectedVideo(getMediaUrl(vidName))}>
                        <video src={getMediaUrl(vidName)} />
                        <div className="play-icon">▶</div>
                        <button type="button" className="delete-icon-btn" onClick={(e) => { e.stopPropagation(); setExistingCarVideos(existingCarVideos.filter((_, idx) => idx !== i)); }}><Trash2 size={12} color="white" strokeWidth={3} /></button>
                      </div>
                    ))}
                    {carVideos.map((file, i) => (
                      <div key={`new-vid-${i}`} className="mini-thumb video-thumb new-border" onClick={() => setSelectedVideo(URL.createObjectURL(file))}>
                        <video src={URL.createObjectURL(file)} />
                        <div className="play-icon">▶</div>
                        <span className="new-badge">NEW</span>
                        <button type="button" className="delete-icon-btn" onClick={(e) => { e.stopPropagation(); setCarVideos(carVideos.filter((_, idx) => idx !== i)); }}><Trash2 size={12} color="white" strokeWidth={3} /></button>
                      </div>
                    ))}
                  </div>

                  <div className="mt-3">
                    <label className="field-label">Notes</label>
                    <textarea className="form-control glass-input" name="notes" rows={2} value={booking.notes} onChange={handleInputChange} placeholder="Dents, scratches, damages, etc..." />
                  </div>
                </div>
              )}
            </div>


            {/* Remarks Section */}
            <div className="glass-panel mb-3">
              <h4 className="panel-title m-0 mb-3"><FileText size={18} className="me-2" /> Remarks & Specific Notes</h4>
              <div className="row g-2">
                <div className="col-12"><label className="field-label">Deposit Remarks</label><textarea className="form-control glass-input remark-textarea" name="deposit_remarks" rows={1} value={booking.deposit_remarks} onChange={handleInputChange} placeholder="E.g., Fully refundable..." /></div>
                <div className="col-12"><label className="field-label">Advance Remarks</label><textarea className="form-control glass-input remark-textarea" name="advance_remarks" rows={1} value={booking.advance_remarks} onChange={handleInputChange} placeholder="E.g., Non-refundable..." /></div>
                <div className="col-12"><label className="field-label">Invoice Remarks</label><textarea className="form-control glass-input remark-textarea" name="invoice_remarks" rows={1} value={booking.invoice_remarks} onChange={handleInputChange} placeholder="E.g., Discount applied..." /></div>
              </div>
            </div>

          </div>

          {/* Right Column */}
          <div className="col-12 col-xl-6">

            {/* Trip Logistics Section */}
            <div className="booking-card">
              <div className="section-header d-flex justify-content-between align-items-center" onClick={() => toggleCollapse('logistics')}>
                <div className="d-flex align-items-center gap-2">
                  <Calendar size={18} className="text-success" />
                  <h4 className="panel-title m-0">Trip Logistics</h4>
                </div>
                <div className="d-flex align-items-center gap-2">
                  {/*<span className="badge bg-purple-subtle text-purple" style={{ fontSize: '10px', fontWeight: 500 }}>
                    {booking.status || 'Draft'}
                  </span>*/}
                  {isCollapsed.logistics ? <ChevronDown size={18} /> : <ChevronUp size={18} />}
                </div>
              </div>

              {!isCollapsed.logistics && (
                <div className="d-flex flex-wrap">
                  <div className="col-md-6">
                    <div className="section-body">

                      <div className="row g-2 mt-2">
                        <div className="col-md-6">
                          <label className="field-label"><Gauge size={12} /> Starting KMs</label>
                          <input type="number" className="form-control glass-input bg-dark-soft" name="starting_kms" value={booking.starting_kms} style={{ opacity: 0.8, cursor: 'not-allowed' }} />
                        </div>
                        <div className="col-md-6">
                          <label className="field-label"><Gauge size={12} /> Ending KMs</label>
                          <input type="number" className="form-control glass-input" name="ending_kms" value={booking.ending_kms} onChange={handleInputChange} placeholder="Return KMs" />
                        </div>
                      </div>

                      <div className="row g-2 mt-2">
                        <div className="col-md-6">
                          <label className="field-label"><Fuel size={12} /> Start Fuel</label>
                          <select className="form-control glass-input" name="fuel_level" value={booking.fuel_level} onChange={handleInputChange}>
                            <option value="">Select</option>
                            <option value="Full Tank">Full Tank</option><option value="7/8">7/8</option><option value="3/4">3/4</option><option value="1/2">1/2</option><option value="1/4">1/4</option><option value="1/8">1/8</option><option value="Empty">Empty</option>
                          </select>
                        </div>
                        <div className="col-md-6">
                          <label className="field-label"><Fuel size={12} /> Return Fuel</label>
                          <select className="form-control glass-input" name="return_fuel_level" value={booking.return_fuel_level} onChange={handleInputChange}>
                            <option value="">Select</option>
                            <option value="Full Tank">Full Tank</option><option value="7/8">7/8</option><option value="3/4">3/4</option><option value="1/2">1/2</option><option value="1/4">1/4</option><option value="1/8">1/8</option><option value="Empty">Empty</option>
                          </select>
                        </div>
                      </div>
                      {/* TRIP TYPE - Daily / Weekly / Monthly */}
                      <div className="row g-2" style={{ marginTop: '8px' }}>

                        <div className="col-md-12">
                          <label className="field-label d-flex align-items-center gap-1" style={{ textTransform: 'uppercase' }}>
                            <Calendar size={14} color="#94a3b8" /> TRIP TYPE
                          </label>
                          <div className="input-icon-wrapper position-relative">
                            <select
                              className="glass-input"
                              name="trip_package"
                              value={booking.trip_package || ""}
                              onChange={(e) => {
                                const selectedTrip = e.target.value;

                                // Find the FIRST matching package for the selected trip type
                                const filteredModes = modeOptions.filter(mode => {
                                  const modeLabel = mode.label.toLowerCase();
                                  const trip = selectedTrip.toLowerCase();

                                  if (trip === 'Hourly') return modeLabel.includes('Hour') || modeLabel.includes('Hourly');
                                  if (trip === 'daily') return modeLabel.includes('day') || modeLabel.includes('daily');
                                  if (trip === 'weekly') return modeLabel.includes('week') || modeLabel.includes('weekly');
                                  if (trip === 'monthly') return modeLabel.includes('month') || modeLabel.includes('monthly');
                                  return false;
                                });

                                // Auto-select the FIRST matching package
                                if (filteredModes.length > 0) {
                                  const mode = filteredModes[0]; // First matching package
                                  const packageValue = `${mode.label} - ${mode.km} KM - AED ${mode.price}`;

                                  setBooking(prev => ({
                                    ...prev,
                                    trip_package: selectedTrip,
                                    booking_mode: packageValue,
                                    km_limit: mode.km,
                                    base_price: parseFloat(mode.price) || 0,
                                    total_price: parseFloat(mode.price) || 0
                                  }));
                                } else {
                                  // No package found, just set trip type
                                  setBooking(prev => ({
                                    ...prev,
                                    trip_package: selectedTrip,
                                    booking_mode: "",
                                    km_limit: "",
                                    base_price: "",
                                    total_price: ""
                                  }));
                                }
                              }}
                              style={{ paddingLeft: '38px' }}
                            >
                              <option value="">Select Trip Type</option>
<option value="Hourly">Hourly</option>
<option value="Daily">Daily</option>
                              <option value="Weekly">Weekly</option>
                              <option value="Monthly">Monthly</option>
                            </select>
                          </div>
                        </div>

                        {/* PACKAGE - Auto-selected, Read-only Display (NO DROPDOWN) */}
                        <div className="col-md-12">
                          <label className="field-label d-flex align-items-center gap-1" style={{ textTransform: 'uppercase' }}>
                            <Package size={14} color="#94a3b8" /> PACKAGE
                          </label>
                          <div className="input-icon-wrapper position-relative">
                            <input
                              className="form-control glass-input"
                              value={booking.booking_mode || "Select Trip Type First"}
                              readOnly
                              style={{
                                paddingLeft: '38px',
                                backgroundColor: 'rgba(15, 23, 42, 0.3) !important',
                                cursor: 'default',
                                color: booking.booking_mode ? '#f8fafc' : '#64748b'
                              }}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div className="col-md-6">
                    <div className="section-body">
                      <div className="d-flex align-items-start mb-3">
                        <div className="flex-grow-1">
                          <h6 className="fw-bold mb-1 d-flex align-items-center gap-1" style={{ display: 'flex', alignItems: 'center' }}>
                            <span className="rounded-icon mb-1"><MapPin size={15} /></span> Pickup</h6>
                          <input type="text" className="form-control glass-input" name="pickup_location" value={booking.pickup_location || ""} onChange={handleInputChange} placeholder="Enter pickup location" style={{ marginBottom: '3px' }} />
                          <div style={{ marginTop: '0' }}>
                            <DateTimePicker
                              name="start_date"
                              value={booking.start_date || ""}
                              onChange={(iso) => handleInputChange({ target: { name: "start_date", value: iso } })}
                              placeholder="Select Date & Time"
                              className="small-datetime-picker"
                            />
                          </div>
                        </div>
                      </div>
                      <div className="d-flex align-items-start">
                        <div className="flex-grow-1">
                          <h6 className="fw-bold mb-1 d-flex align-items-center gap-1" style={{ display: 'flex', alignItems: 'center' }}>
                            <span className="rounded-icon mb-1"><MapPin size={15} /> Drop </span></h6>
                          <input type="text" className="form-control glass-input" name="drop_location" value={booking.drop_location || ""} onChange={handleInputChange} placeholder="Enter drop location" style={{ marginBottom: '3px' }} />
                          <div>
                            <DateTimePicker
                              name="end_date"
                              value={booking.end_date || ""}
                              onChange={(iso) => handleInputChange({ target: { name: "end_date", value: iso } })}
                              placeholder="Select Date & Time"
                            />
                          </div>
                        </div>
                      </div>

                      <div className="col-md-12 " style={{ marginTop: "12px" }} >
                        <label className="field-label d-flex align-items-center gap-1" style={{ textTransform: 'uppercase' }}>
                           BASE PRICE
                        </label>
                        <input
                          type="number"
                          className="form-control glass-input"
                          name="base_price"
                          value={booking.base_price}
                          onChange={handleInputChange}  // This makes it editable
                        />
                      </div>
                    </div>
                  </div>
                </div>
              )}
              {(booking.status === 'confirmed' || booking.status === 'completed' || booking.status === 'cancelled') && booking.id && (
                <div className="summary-button-wrapper" style={{ padding: '12px 16px 16px 16px', borderTop: '1px solid rgba(255, 255, 255, 0.04)', marginTop: '4px' }}>
                  <button type="button" onClick={() => setShowSummaryModal(true)} className="grand-save-btn w-100" style={{ padding: '14px !important', fontSize: '1rem', fontWeight: 700, letterSpacing: '0.5px', textTransform: 'uppercase', borderRadius: '12px', background: 'linear-gradient(135deg, #7c3aed, #6d28d9) !important', boxShadow: '0 4px 20px rgba(124, 58, 237, 0.35) !important', transition: 'all 0.3s ease !important', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '10px' }}>
                    <FileText size={20} /> VIEW FINAL SUMMARY <span style={{ fontSize: '10px', opacity: 0.7, fontWeight: 400, marginLeft: '4px' }}>→</span>
                  </button>
                </div>
              )}
            </div>

            {/* Payment & Billing */}
            <div className="glass-panel mb-3">
              <h4 className="panel-title "> Payment & Billing</h4>
              <div className="row g-2">
                <div className="col-md-6"><label className="field-label"><FileText size={12} />Booking ID</label>
                  <input className="form-control glass-input mb-2" value={booking.id || "Auto-generated"} readOnly style={{ color: booking.id ? '#4ade80' : '#94a3b8' }} /></div>
                <div className="col-md-6">
                  <label className="field-label"><Calendar size={12} /> Booking Date</label>
                  <DateTimePicker name="booking_date" value={booking.booking_date || ""} onChange={(iso) => handleInputChange({ target: { name: "booking_date", value: iso } })} placeholder="Date & Time" />
                </div>

                <div className="col-md-6">
                  <label className="field-label d-flex align-items-center gap-1" style={{ textTransform: 'uppercase' }}><CreditCard size={14} color="#94a3b8" /> PAYMENT TYPE</label>
                  <div className="input-icon-wrapper position-relative">
                    <select className="glass-input" name="payment_method" value={booking.payment_method} onChange={handleInputChange}>
                      <option value="Cash">Cash</option><option value="Card">Card</option>
                    </select>
                  </div>
                </div>
                <div className="col-md-6">
                  <div className="highlight-box">
                    <label className="field-label"> Total Amount</label>
                    <input className="form-control glass-input ps-5 fw-bold text-success" value={booking.total_price || "0.00"}
                      readOnly style={{ background: 'rgba(74, 222, 128, 0.08)', borderColor: 'rgba(74, 222, 128, 0.3)' }} />
                  </div>
                </div>

<div className="p-3 p-md-4 rounded-4 my-3 glass-card" style={{
                  background: 'rgba(225, 78, 202, 0.03)',
                  border: '1px solid rgba(225, 78, 202, 0.12)',
                  backdropFilter: 'blur(8px)'
                }}>

                 <div className="row g-3">
                    {/* Security Deposit */}
                    <div className="col-12 col-md-4">
                      <label htmlFor="deposit" className="form-label d-flex align-items-center gap-1 small fw-medium text-secondary mb-1">
                        <Shield size={14} className="text-warning" />
                        <span>Security Deposit</span>
                      </label>
                      <div className="input-group input-group-sm">
                        <input type="number" min="0" onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }} name="deposit" className="form-control glass-input bg-transparent fw-bold text-warning py-1" value={booking.deposit} onChange={handleInputChange} />
                      </div>
                    </div>
                    {/* Advance Paid */}
                    <div className="col-12 col-md-4">
                      <label htmlFor="advance_paid" className="form-label d-flex align-items-center gap-1 small fw-medium text-secondary mb-1">
                        <CheckCircle size={14} className="text-success" />
                        <span>Advance Paid</span>
                      </label>
                      <div className="input-group input-group-sm">
                        <input type="number" min="0" onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }} name="advance_paid" className="form-control glass-input bg-transparent fw-bold text-success py-1" value={booking.advance_paid} onChange={handleInputChange} />
                      </div></div>
                    {/* Tax Percentage */}
                    <div className="col-12 col-md-4">
                      <label htmlFor="tax_amount" className="form-label d-flex align-items-center gap-1 small fw-medium text-secondary mb-1">
                        <Percent size={14} className="text-primary" />
                        <span>Tax (%)</span>
                      </label>
                      <div className="input-group input-group-sm">
                        <input type="number" min="0" onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }} name="tax_amount" className="form-control glass-input bg-transparent py-1" value={booking.tax_amount} onChange={handleInputChange} />
                      </div>
                    </div>
                    </div>

                  <div className="row mt-3">
                    <div className="col-12">
                      <div className="d-flex align-items-center justify-content-between p-3 rounded-3" style={{ background: 'linear-gradient(135deg, rgba(168, 85, 247, 0.15), rgba(6, 182, 212, 0.08))', border: '1px solid rgba(168, 85, 247, 0.2)' }}>
                        <div>
                          <label className="field-label m-0" style={{ fontSize: '14px', color: "#a855f7" }}><AlertCircle size={16} className="me-2" style={{ color: "#a855f7" }} />Balance to Pay</label>
                        </div>
                        <div className="fw-bold" style={{ fontSize: '1.5rem', color: "#06b6d4" }}>AED {balanceToPay?.toFixed(2) || '0.00'}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Detailed Invoice Split */}
            <div className="glass-panel mb-3">
              <div className="d-flex flex-wrap justify-content-between align-items-center mb-3 gap-2">
                <h4 className="panel-title m-0"><FileText size={18} className="me-2" /> Detailed Invoice Split</h4>
                <div className="d-flex flex-row gap-2 flex-nowrap align-items-center">

                  {/* DYNAMIC ADD CHARGE DROPDOWN (VISIBLE ON ALL INVOICES) */}
                  <select
                    className="form-select form-select-sm"
                    value={selectedChargeDropdown}
                    onChange={(e) => {
                      const val = e.target.value;
                      const lastIdx = Math.max(0, numberOfSections - 1);

                      // Auto jump to last invoice if trying to add charge on previous invoices
                      if (activeInvoiceTab !== lastIdx && val) {
                        setActiveInvoiceTab(lastIdx);
                        alert("Additional charges can only be added to the last invoice. You have been redirected.");
                      }

                      const targetTab = (activeInvoiceTab !== lastIdx && val) ? lastIdx : activeInvoiceTab;

                      setSelectedChargeDropdown(val);
                      if (val) {
                        if (val.startsWith('add_')) {
                          const idx = parseInt(val.split('_')[1]);
                          setChargeInputValue(additionalCharges[targetTab]?.[idx]?.amount || "");
                        } else {
                          setChargeInputValue(sectionCharges[targetTab]?.[val] || "");
                        }
                      } else {
                        setChargeInputValue("");
                      }
                    }}
                    style={{ minWidth: "130px", width: "auto", backgroundColor: "#1E2A38", color: "#00FFE0", borderColor: "#00FFE0" }}
                  >
                    <option value="">Select Charge</option>
                    <option value="cleaning">Cleaning</option>
                    <option value="damage">Damage</option>
                    <option value="excess_km">Excess KM</option>
                    <option value="salik">Salik / Toll</option>
                    {additionalCharges[activeInvoiceTab]?.map((c, idx) => (
                      c.name ? <option key={`add_${idx}`} value={`add_${idx}`}>{c.name}</option> : null
                    ))}
                  </select>

                  <select className="form-select form-select-sm" value={activeInvoiceTab} onChange={(e) => {
                    setActiveInvoiceTab(parseInt(e.target.value));
                    setSelectedChargeDropdown("");
                    setChargeInputValue("");
                    setIsAddingExtraCharge(false);
                    setNewExtraCharge({ name: "", amount: "" });
                  }} style={{ minWidth: "160px", width: "auto", backgroundColor: "#1E2A38", color: "#00FFE0", borderColor: "#00FFE0" }}>
                    {Array.from({ length: numberOfSections }).map((_, idx) => {
                      const startDay = idx * 30 + 1;
                      const endDay = Math.min((idx + 1) * 30, totalDays);
                      return <option key={idx} value={idx}>Invoice {idx + 1} ({startDay}-{endDay} Days)</option>;
                    })}
                  </select>
                </div>
              </div>

              {(() => {
                const totalDays = getDays(booking.start_date, booking.end_date);
                const baseRate = parseFloat(booking.base_price) || 0;
                const startDay = (activeInvoiceTab * 30) + 1;
                const endDay = Math.min((activeInvoiceTab + 1) * 30, totalDays);
                const currentDays = endDay - startDay + 1;

                return (
                  <div className="p-3 rounded-4" style={{ background: 'rgba(0,0,0,0.2)', border: '1px solid rgba(255,255,255,0.05)' }}>
                    <div className="row align-items-start">
                      <div className="col-md-5 border-end border-secondary border-opacity-25 h-100">
                        <label className="field-label mb-1">Base Rent ({currentDays} Days x {baseRate})</label>
                        <div className="d-flex align-items-baseline gap-2">
                          <span className="fs-2 fw-bold text-white">AED  {(currentDays * baseRate).toFixed(2)}</span>
                        </div>
                        <small className="text-secondary italic" style={{ fontSize: '10px' }}>Standard rental charges for this period</small>
                      </div>

                      <div className="col-md-7 ps-md-4">
                        <div className="pt-2" style={{ maxHeight: '400px', overflowY: 'auto', overflowX: 'hidden', paddingRight: '8px' }}>

                          {/* ALREADY APPLIED CHARGES LIST - SCROLLABLE */}
                          <div className="applied-charges-wrapper mb-3">
                            <label className="field-label-tiny mb-2 text-info">APPLIED CHARGES</label>
                            <div className="d-flex flex-column gap-2 scrollable-charges" style={{ maxHeight: '300px', overflowY: 'auto', paddingRight: '5px' }}>

                              {/* Map through standard base charges */}
                              {['cleaning', 'damage', 'excess_km', 'salik'].map(key => {
                                const amount = sectionCharges[activeInvoiceTab]?.[key];
                                const isEditing = selectedChargeDropdown === key;

                                if ((amount && parseFloat(amount) > 0) || isEditing) {
                                  return (
                                    <div key={key} className="d-flex flex-column gap-2 mb-2 p-2 rounded" style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)' }}>
                                      <div className="d-flex justify-content-between align-items-center">
                                        <span className="text-white text-capitalize" style={{ fontSize: '12px' }}>{key.replace('_', ' ')}</span>

                                        <div className="d-flex align-items-center gap-3">
                                          {isEditing ? (
                                            <div className="d-flex align-items-center gap-2">
                                              <input
                                                type="number"
                                                min="0"
                                                className="form-control glass-input bg-transparent text-white m-0"
                                                style={{ width: '80px', padding: '2px 8px', height: '28px', fontSize: '12px' }}
                                                value={chargeInputValue}
                                                onChange={(e) => setChargeInputValue(e.target.value)}
                                                onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }}
                                                autoFocus
                                              />
                                              <button
                                                type="button"
                                                className="btn btn-sm text-white fw-bold px-2 py-0"
                                                onClick={handleUpdateDropdownCharge}
                                                style={{ background: 'linear-gradient(135deg, #7c3aed, #6d28d9)', border: 'none', borderRadius: '4px', height: '28px', fontSize: '11px' }}
                                              >
                                                Save
                                              </button>
                                            </div>
                                          ) : (
                                            <span className="text-info fw-bold" style={{ fontSize: '13px' }}>AED {parseFloat(amount).toFixed(2)}</span>
                                          )}

                                          {/* DISPLAY EDIT/DELETE IN ALL INVOICES, BUT ACTION JUMPS TO LAST */}
                                          <div className="d-flex gap-2">
                                            <button
                                              type="button"
                                              className="btn btn-sm text-primary p-0 m-0 d-flex align-items-center justify-content-center"
                                              style={{ border: 'none', background: 'transparent' }}
                                              onClick={() => {
                                                const lastIdx = Math.max(0, numberOfSections - 1);
                                                if (activeInvoiceTab !== lastIdx) {
                                                  setActiveInvoiceTab(lastIdx);
                                                  alert("Charges can only be modified in the last invoice. You have been redirected.");
                                                  return;
                                                }
                                                setSelectedChargeDropdown(isEditing ? "" : key);
                                                setChargeInputValue(isEditing ? "" : amount);
                                              }}
                                              title="Edit Charge"
                                            >
                                              {isEditing ? <X size={15} className="text-danger" /> : <Edit2 size={15} />}
                                            </button>
                                            <button
                                              type="button"
                                              className="btn btn-sm text-danger p-0 m-0 d-flex align-items-center justify-content-center"
                                              style={{ border: 'none', background: 'transparent' }}
                                              onClick={() => {
                                                const lastIdx = Math.max(0, numberOfSections - 1);
                                                if (activeInvoiceTab !== lastIdx) {
                                                  setActiveInvoiceTab(lastIdx);
                                                  alert("Charges can only be modified in the last invoice. You have been redirected.");
                                                  return;
                                                }
                                                handleSectionChargeChange(activeInvoiceTab, key, 0);
                                                if (selectedChargeDropdown === key) {
                                                  setSelectedChargeDropdown("");
                                                  setChargeInputValue("");
                                                }
                                              }}
                                              title="Delete Charge"
                                            >
                                              <Trash2 size={15} />
                                            </button>
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  );
                                }
                                return null;
                              })}

                              {/* Map through dynamically added extra charges */}
                              {additionalCharges[activeInvoiceTab]?.map((charge, idx) => {
                                const chargeKey = `add_${idx}`;
                                const isEditing = selectedChargeDropdown === chargeKey;

                                if ((charge.name && parseFloat(charge.amount) > 0) || isEditing) {
                                  return (
                                    <div key={`add_applied_${idx}`} className="d-flex flex-column gap-2 mb-2 p-2 rounded" style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)' }}>
                                      <div className="d-flex justify-content-between align-items-center">
                                        <span className="text-white" style={{ fontSize: '12px' }}>{charge.name}</span>

                                        <div className="d-flex align-items-center gap-3">
                                          {isEditing ? (
                                            <div className="d-flex align-items-center gap-2">
                                              <input
                                                type="number"
                                                min="0"
                                                className="form-control glass-input bg-transparent text-white m-0"
                                                style={{ width: '80px', padding: '2px 8px', height: '28px', fontSize: '12px' }}
                                                value={chargeInputValue}
                                                onChange={(e) => setChargeInputValue(e.target.value)}
                                                onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }}
                                                autoFocus
                                              />
                                              <button
                                                type="button"
                                                className="btn btn-sm text-white fw-bold px-2 py-0"
                                                onClick={handleUpdateDropdownCharge}
                                                style={{ background: 'linear-gradient(135deg, #7c3aed, #6d28d9)', border: 'none', borderRadius: '4px', height: '28px', fontSize: '11px' }}
                                              >
                                                Save
                                              </button>
                                            </div>
                                          ) : (
                                            <span className="text-info fw-bold" style={{ fontSize: '13px' }}>AED {parseFloat(charge.amount).toFixed(2)}</span>
                                          )}

                                          {/* DISPLAY EDIT/DELETE IN ALL INVOICES, BUT ACTION JUMPS TO LAST */}
                                          <div className="d-flex gap-2">
                                            <button
                                              type="button"
                                              className="btn btn-sm text-primary p-0 m-0 d-flex align-items-center justify-content-center"
                                              style={{ border: 'none', background: 'transparent' }}
                                              onClick={() => {
                                                const lastIdx = Math.max(0, numberOfSections - 1);
                                                if (activeInvoiceTab !== lastIdx) {
                                                  setActiveInvoiceTab(lastIdx);
                                                  alert("Charges can only be modified in the last invoice. You have been redirected.");
                                                  return;
                                                }
                                                setSelectedChargeDropdown(isEditing ? "" : chargeKey);
                                                setChargeInputValue(isEditing ? "" : charge.amount);
                                              }}
                                              title="Edit Charge"
                                            >
                                              {isEditing ? <X size={15} className="text-danger" /> : <Edit2 size={15} />}
                                            </button>
                                            <button
                                              type="button"
                                              className="btn btn-sm text-danger p-0 m-0 d-flex align-items-center justify-content-center"
                                              style={{ border: 'none', background: 'transparent' }}
                                              onClick={() => {
                                                const lastIdx = Math.max(0, numberOfSections - 1);
                                                if (activeInvoiceTab !== lastIdx) {
                                                  setActiveInvoiceTab(lastIdx);
                                                  alert("Charges can only be modified in the last invoice. You have been redirected.");
                                                  return;
                                                }
                                                removeAdditionalCharge(activeInvoiceTab, idx);
                                                if (selectedChargeDropdown === chargeKey) {
                                                  setSelectedChargeDropdown("");
                                                  setChargeInputValue("");
                                                }
                                              }}
                                              title="Delete Charge"
                                            >
                                              <Trash2 size={15} />
                                            </button>
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  );
                                }
                                return null;
                              })}

                              {/* Message if no charges are applied */}
                              {
                                !['cleaning', 'damage', 'excess_km', 'salik'].some(key => parseFloat(sectionCharges[activeInvoiceTab]?.[key]) > 0 || selectedChargeDropdown === key) &&
                                !(additionalCharges[activeInvoiceTab]?.some((c, idx) => (c.name && parseFloat(c.amount) > 0) || selectedChargeDropdown === `add_${idx}`)) &&
                                <div className="text-center p-3 rounded" style={{ background: 'rgba(255,255,255,0.02)', border: '1px dashed rgba(255,255,255,0.1)', color: '#64748b', fontSize: '11px' }}>
                                  No extra charges applied yet.
                                </div>
                              }
                            </div>
                          </div>

                          <div className="row g-2">
                            {/* INLINE ADD EXTRA CHARGE FORM (VISIBLE ON ALL INVOICES) */}
                            {!isAddingExtraCharge && (
                              <div className="col-12 mt-4">
                                <button type="button" onClick={() => {
                                  const lastIdx = Math.max(0, numberOfSections - 1);
                                  if (activeInvoiceTab !== lastIdx) {
                                    setActiveInvoiceTab(lastIdx);
                                    alert("Additional charges can only be added to the last invoice. You have been redirected.");
                                  }
                                  setIsAddingExtraCharge(true);
                                }} className="btn btn-outline-primary btn-sm w-100" style={{ fontSize: '11px', borderColor: 'rgba(61, 90, 254, 0.3)', color: '#3d5afe', borderStyle: 'dashed', backgroundColor: 'rgba(61, 90, 254, 0.05)' }}>+ Add Extra Charge</button>
                              </div>
                            )}

                            {isAddingExtraCharge && (
                              <div className="col-12 mt-4 p-3 rounded shadow" style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)' }}>
                                <label className="field-label-tiny mb-2">NEW EXTRA CHARGE</label>
                                <div className="d-flex flex-column gap-2">
                                  <input type="text" placeholder="Description (e.g. Fine)" className="form-control glass-input text-white w-100" value={newExtraCharge.name} onChange={e => setNewExtraCharge({ ...newExtraCharge, name: e.target.value })} />
                                  <input type="number" min="0" placeholder="Amount" className="form-control glass-input text-white w-100" value={newExtraCharge.amount} onChange={e => setNewExtraCharge({ ...newExtraCharge, amount: e.target.value })} onKeyDown={(e) => { if (e.key === '-' || e.key === 'e') e.preventDefault(); }} />
                                  <div className="d-flex gap-2 pt-1">
                                    <button type="button" className="btn btn-sm text-white fw-bold w-50" style={{ background: 'linear-gradient(135deg, #7c3aed, #6d28d9)', border: 'none', borderRadius: '8px' }} onClick={() => {
                                      if (newExtraCharge.name) {
                                        setAdditionalCharges(prev => {
                                          const updated = [...prev];
                                          updated[activeInvoiceTab] = [...(updated[activeInvoiceTab] || []), { name: newExtraCharge.name, amount: parseFloat(newExtraCharge.amount) || 0 }];
                                          return updated;
                                        });
                                        setIsAddingExtraCharge(false);
                                        setNewExtraCharge({ name: "", amount: "" });
                                      }
                                    }}>Update</button>
                                    <button type="button" className="btn btn-sm btn-danger fw-bold w-50" style={{ borderRadius: '8px' }} onClick={() => setIsAddingExtraCharge(false)}>Cancel</button>
                                  </div>
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                    <hr className="my-3 opacity-10" />
                    <div className="d-flex justify-content-between align-items-center">
                      <div className="d-flex gap-2">
                        <button type="button" className="btn btn-outline-primary btn-sm d-flex align-items-center gap-2" onClick={() => handlePrint('invoice', activeInvoiceTab)}><Printer size={14} /> Print Invoice {activeInvoiceTab + 1}</button>
                      </div>
                      <div className="text-end">
                        {(() => {
                          const startDay = (activeInvoiceTab * 30) + 1;
                          const endDay = Math.min((activeInvoiceTab + 1) * 30, totalDays);
                          const currentTabDays = endDay - startDay + 1;
                          const baseRate = parseFloat(booking.base_price) || 0;
                          const sectionRent = currentTabDays * baseRate;
                          const sectionExtra = (parseFloat(sectionCharges[activeInvoiceTab]?.cleaning) || 0) +
                            (parseFloat(sectionCharges[activeInvoiceTab]?.damage) || 0) +
                            (parseFloat(sectionCharges[activeInvoiceTab]?.excess_km) || 0) +
                            (parseFloat(sectionCharges[activeInvoiceTab]?.salik) || 0);
                          const additional = additionalCharges[activeInvoiceTab]?.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0) || 0;
                          return (
                            <>
                              <label className="field-label mb-0" style={{ fontSize: '9px' }}>Invoice {activeInvoiceTab + 1} Subtotal ({currentTabDays} Days + Extras)</label>
                              <div className="text-success fw-bold fs-4"> AED  {(sectionRent + sectionExtra + additional).toFixed(2)}</div>
                            </>
                          );
                        })()}
                      </div>
                    </div>
                  </div>
                );
              })()}
            </div>

            <div className="d-flex flex-wrap gap-2 mb-3">
              {booking.id && (
                <button
                  type="button"
                  className="btn btn-outline-danger flex-fill d-flex align-items-center justify-content-center gap-2"
                  style={{
                    borderRadius: '12px',
                    padding: '12px',
                    fontWeight: 600,
                    fontSize: '0.85rem',
                    minWidth: '80px',
                    cursor: 'pointer'
                  }}
                  onClick={async () => {
                    if (window.confirm('Are you sure you want to cancel this booking?')) {
                      booking.status = 'cancelled';
                      setBooking(prev => ({ ...prev, status: 'cancelled' }));
                      const savedId = await saveBookingData();
                      if (savedId) {
                        alert('Booking cancelled successfully!');
                        setShowSummaryModal(true);
                      }
                    }
                  }}
                >
                  <X size={18} /> Cancel
                </button>
              )}

              <button
                type="submit"
                className="grand-save-btn flex-fill d-flex align-items-center justify-content-center gap-2"
                style={{
                  borderRadius: '12px',
                  padding: '12px',
                  fontWeight: 600,
                  fontSize: '0.85rem',
                  minWidth: '80px',
                }}
              >
                <Save size={20} /> {booking.id ? "UPDATE BOOKING DETAILS" : "REGISTER BOOKING"}
              </button>

              {booking.id && (
                <button
                  type="button"
                  className="btn btn-success flex-fill d-flex align-items-center justify-content-center gap-2"
                  style={{
                    borderRadius: '12px',
                    padding: '12px',
                    fontWeight: 600,
                    fontSize: '0.85rem',
                    minWidth: '80px'
                  }}
                  onClick={async () => {
                    // Check 1: Ending KMs
                    if (!booking.ending_kms || booking.ending_kms === '') {
                      alert('⚠️ Please fill the Ending KMs before finishing the trip.');
                      return;
                    }

                    // Check 2: Return Fuel
                    if (!booking.return_fuel_level || booking.return_fuel_level === '') {
                      alert('⚠️ Please select the Return Fuel level before finishing the trip.');
                      return;
                    }

                    // Check 3: Drop Date & Time
                    if (!booking.end_date || booking.end_date === '') {
                      alert('⚠️ Please set the Drop Date & Time before finishing the trip.');
                      return;
                    }

                    // If all validations pass - mark as completed
                    if (window.confirm('✅ All details are filled. Mark this trip as COMPLETED?')) {
                      try {
                        // Update status in state
                        booking.status = 'completed';
                        setBooking(prev => ({ ...prev, status: 'completed' }));

                        // Use the existing save function
                        const savedId = await saveBookingData();

                        if (savedId) {
                          alert('🎉 Trip completed successfully!');
                          navigate('/booking-management');
                        } else {
                          alert('❌ Failed to save booking. Please try again.');
                        }
                      } catch (err) {
                        console.error('Error:', err);
                        alert('❌ Error completing trip: ' + (err.response?.data?.message || err.message));
                      }
                    }
                  }}
                >
                  <Flag size={18} /> Finish Trip
                </button>
              )}
            </div>

          </div>
        </form>
      </div>

      {showModal && (
        <div className="modal-overlay">
          <div className="booking-modal-wrapper">
            <AddCustomer onSuccess={handleSuccess} onCancel={() => { setShowModal(false); setIsNewCustomer(false); }} isBookingMode={true} initialData={null} />
          </div>
        </div>
      )}
      {showSummaryModal && (
        <div className="modal-overlay" style={{ zIndex: 1050 }}>
          <div className="booking-modal-wrapper" style={{ maxWidth: '1050px', width: '95%', background: '#181a24', borderRadius: '16px', overflowY: 'auto', maxHeight: '90vh', padding: '0px' }}>
            <FinalSummary bookingId={booking.id} onClose={() => setShowSummaryModal(false)} />
          </div>
        </div>
      )}
      {selectedVideo && (
        <div className="video-modal" onClick={() => setSelectedVideo(null)}>
          <div className="video-modal-content" onClick={e => e.stopPropagation()}>
            <video src={selectedVideo} controls autoPlay className="w-100 rounded-3" />
            <button className="close-video-btn" onClick={() => setSelectedVideo(null)}>✕</button>
          </div>
        </div>
      )}
      {selectedImage && (
        <div className="video-modal" onClick={() => setSelectedImage(null)}>
          <div className="video-modal-content" style={{ display: 'flex', justifyContent: 'center', background: 'transparent', boxShadow: 'none' }} onClick={e => e.stopPropagation()}>
            <img src={selectedImage} alt="preview" style={{ maxHeight: '90vh', maxWidth: '100%', objectFit: 'contain' }} className="rounded-3 shadow-lg" />
            <button className="close-video-btn" onClick={() => setSelectedImage(null)}>✕</button>
          </div>
        </div>
      )}

      <style>{`
        .field-label-tiny { font-size: 9px; color: #64748b; text-transform: uppercase; font-weight: bold; margin-bottom: 2px; display: block; }
        .video-modal { position: fixed; inset: 0; background: rgba(0,0,0,0.85); display: flex; align-items: center; justify-content: center; z-index: 9999; backdrop-filter: blur(5px); }
        .video-modal-content { position: relative; max-width: 800px; width: 90%; background: #000; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); }
        .close-video-btn { position: absolute; top: -15px; right: -15px; background: #ef4444; color: white; border: none; width: 32px; height: 32px; border-radius: 50%; font-size: 16px; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(239,68,68,0.4); z-index: 10; transition: transform 0.2s; }
        .close-video-btn:hover { transform: scale(1.1); background: #dc2626; }
        .glass-page-bg { min-height: 100vh; background: rgba(30, 41, 59, 0.4); color: #e2e8f0; font-family: "Maiandra GD", sans-serif !important; }
        .glass-panel { background: rgba(30, 41, 59, 0.5); backdrop-filter: blur(12px); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 16px; padding: 1.25rem; margin-bottom: 1.25rem !important; transition: all 0.3s ease; }
        .glass-panel:hover { border-color: rgba(139, 92, 246, 0.2); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); }
        .glass-panel .row { --bs-gutter-x: 12px !important; --bs-gutter-y: 10px !important; }
        .glass-panel .row.custom-gap { --bs-gutter-x: 24px !important; }
.glass-panel [class*="col-"] {
    margin-top: 12px !important;
    margin-bottom:2px;
    padding-top: 0;
    padding-bottom: 0;
}
 .btn-close-camera {
    background: rgba(255, 255, 255, 0.04);
    color: rgba(255, 255, 255, 0.5);
    border: 1px solid rgba(255, 255, 255, 0.06);
  }

  .btn-close-camera:hover {
    background: rgba(255, 255, 255, 0.08);
    color: rgba(255, 255, 255, 0.8);
    transform: translateY(-2px);
  }
    .btn-capture {
    background: linear-gradient(135deg, rgba(168, 85, 247, 0.15), rgba(168, 85, 247, 0.05));
    color: #a855f7;
    border: 1px solid rgba(168, 85, 247, 0.15);
  }

  .btn-capture:hover {
    background: linear-gradient(135deg, rgba(168, 85, 247, 0.25), rgba(168, 85, 247, 0.1));
    border-color: rgba(168, 85, 247, 0.3);
    transform: translateY(-2px);
  }
    .camera-controls {
  width: 100%;
}

.camera-controls > button {
  min-width: 100px; /* Minimum width for smaller screens */
  white-space: nowrap; /* Prevents text wrapping */
}

/* For very small screens, allow wrapping */
@media (max-width: 480px) {
  .camera-controls > button {
    min-width: 80px;
    font-size: 12px;
    padding: 16px 10px;
  }
}
      .mini-cam-btn {  background: linear-gradient(135deg, rgba(13, 202, 240, 0.15), rgba(13, 202, 240, 0.05));
  color: #6edff6;
  border: 1px solid rgba(13, 202, 240, 0.15);}
        .mini-cam-btn:hover {  background: linear-gradient(135deg, rgba(13, 202, 240, 0.25), rgba(13, 202, 240, 0.1));
  border-color: rgba(13, 202, 240, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(13, 202, 240, 0.15); }


        .panel-title { margin: 0 0 1.25rem 0; color: #f8fafc; font-size: 0.975rem; font-weight: 700; display: flex; align-items: center; gap: 8px; border-left: 3px solid #a855f7; padding-left: 10px; padding-bottom: 2px; letter-spacing: 0.02em; text-transform: uppercase; }
        .field-label { display: flex; align-items: center; gap: 6px; color: #94a3b8; font-size: 0.725rem; text-transform: uppercase; font-weight: 700; margin-bottom: 6px; letter-spacing: 0.06em; }

        .glass-input { background-color: rgba(15, 23, 42, 0.55) !important; border: 1px solid rgba(255, 255, 255, 0.08) !important; color: white !important; font-family: "Maiandra GD", sans-serif !important; border-radius: 8px !important; padding: 9px 14px !important; font-size: 14px !important; height: auto !important; width: 100%; margin-bottom: 0 !important; transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); }
        .glass-input:hover { background-color: rgba(15, 23, 42, 0.75) !important; border-color: rgba(168, 85, 247, 0.45) !important; }
        .glass-input:focus { border-color: #a855f7 !important; box-shadow: 0 0 0 0.25rem rgba(168, 85, 247, 0.25) !important; background-color: rgba(15, 23, 42, 0.9) !important; outline: none; }
        .highlight-box .total-field { border-color: #a855f7 !important; background: rgba(168, 85, 247, 0.1) !important; color: #a855f7 !important; font-weight: 800; }
        .balance-row-bootstrap { background: rgba(255, 255, 255, 0.03); border: 1px dashed rgba(255, 255, 255, 0.1); padding: 15px; border-radius: 15px; }
        .amount.red { color: #ef4444; font-size: 20px; font-weight: 800; }
        .remark-textarea { background: rgba(255, 255, 255, 0.05) !important; resize: none; transition: 0.3s; }
        .remark-textarea:focus { height: 60px; background: rgba(255, 255, 255, 0.1) !important; }
        //.mini-cam-btn { background: rgba(168, 85, 247, 0.08) !important; border: 1px solid rgba(168, 85, 247, 0.3) !important; color: white !important; padding: 8px 16px; border-radius: 10px; font-size: 13px; font-weight: bold; transition: all 0.25s ease; cursor: pointer; }
        //.mini-cam-btn:hover { background: rgba(168, 85, 247, 0.18) !important; border-color: #a855f7 !important; }
        .grand-save-btn { background: linear-gradient(135deg, #7c3aed, #a855f7) !important; border: none; color: white; padding: 18px; border-radius: 15px; font-weight: 800; display: flex; align-items: center; justify-content: center; gap: 10px; box-shadow: 0 4px 15px rgba(124, 58, 237, 0.3); transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); cursor: pointer; }
        .grand-save-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(124, 58, 237, 0.45); filter: brightness(1.1); }
        .grand-save-btn:active { transform: translateY(1px); }
        .mini-thumb { position: relative; width: 65px; height: 50px; border-radius: 8px; overflow: hidden; border: 1px solid rgba(255,255,255,0.1); cursor: pointer; }
        .mini-thumb img, .mini-thumb video { width: 100%; height: 100%; object-fit: cover; }
        .delete-icon-btn { position: absolute; top:2px; right: 2px; background: #ef4444 !important; border: 2px solid #1e293b !important; border-radius: 50% !important; width: 22px !important; height: 22px !important; display: flex !important; align-items: center !important; justify-content: center !important; padding: 0 !important; cursor: pointer !important; z-index: 100 !important; box-shadow: 0 2px 4px rgba(0,0,0,0.5); }
        .glass-input::placeholder { color: #64748b !important; opacity: 1; }
        .delete-icon-btn:hover { background: #f87171 !important; transform: scale(1.1); }
        .search-dropdown { position: absolute; top: 100%; left: 0; width: 100%; max-height: 200px; overflow-y: auto; background: #1e293b; border: 1px solid rgba(255,255,255,0.15); border-radius: 10px; z-index: 1050; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5); }
        .search-item { padding: 10px; cursor: pointer; border-bottom: 1px solid rgba(255,255,255,0.05); }
        .search-item:hover { background: rgba(225, 78, 202, 0.2); }
        .new-badge { position: absolute; bottom: 0; left: 0; background: #4ade80; color: black; font-size: 8px; font-weight: bold; padding: 1px 3px; }
        .video-thumb .play-icon { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: white; font-size: 12px; background: rgba(0,0,0,0.5); padding: 4px; border-radius: 50%; }
        .recording-indicator { position: absolute; top: 10px; left: 10px; background: rgba(0,0,0,0.6); padding: 4px 10px; border-radius: 20px; display: flex; align-items: center; gap: 8px; font-size: 12px; }
        .blink-dot { width: 8px; height: 8px; background: red; border-radius: 50%; animation: blink 1s infinite; }
        .cus-name { display: block; font-weight: bold; color: white; }
        .cus-meta { font-size: 11px; color: #94a3b8; }
        .add-customer-btn { background: linear-gradient(135deg, #7c3aed, #6d28d9); border: none; color: white; font-weight: 600; padding: 6px 16px; border-radius: 8px; transition: all 0.3s ease; font-size: 13px; display: flex; align-items: center; gap: 6px; cursor: pointer; white-space: nowrap; }
        .add-customer-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 15px rgba(124, 58, 237, 0.4); background: linear-gradient(135deg, #8b5cf6, #7c3aed); }
        .booking-card { background: rgba(30, 41, 59, 0.5); backdrop-filter: blur(12px); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 16px; margin-bottom: 16px; overflow: hidden; transition: all 0.3s ease; }
        .booking-card:hover { border-color: rgba(139, 92, 246, 0.15); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); }
        .section-header { padding: 12px 16px; cursor: pointer; user-select: none; transition: all 0.2s ease; border-bottom: 1px solid rgba(255, 255, 255, 0.06); }
        .section-header:hover { background: rgba(255, 255, 255, 0.03); }
        .section-body { padding: 16px; animation: slideDown 0.3s ease; }
        .timeline-line { width: 2px; flex-grow: 1; background: rgba(255,255,255,0.1); margin: 4px 0; }

        /* Custom Scrollbars for dynamically added charges */
        .scrollable-charges::-webkit-scrollbar { width: 4px; }
        .scrollable-charges::-webkit-scrollbar-track { background: rgba(255,255,255,0.02); border-radius: 4px; }
        .scrollable-charges::-webkit-scrollbar-thumb { background: rgba(168, 85, 247, 0.4); border-radius: 4px; }
        .scrollable-charges::-webkit-scrollbar-thumb:hover { background: rgba(168, 85, 247, 0.7); }

        @keyframes slideDown { from { opacity: 0; transform: translateY(-8px); } to { opacity: 1; transform: translateY(0); } }

        /* Booking Title CSS adjustments */
        .booking-title { font-size: 1.1rem; font-weight: 700; background: linear-gradient(135deg, #e14eca, #8b5cf6); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

        /* Media Queries Mobile Responsive */
        @media (max-width: 991.98px) {
            .row.g-2 { flex-direction: column !important; }
            .col-xl-6 { flex: 0 0 100% !important; max-width: 100% !important; }
        }
        @media (max-width: 767.98px) {
            .glass-panel { padding: 0.8rem !important; border-radius: 12px !important; margin-bottom: 0.8rem !important; }
            .section-header { padding: 10px !important; }
            .section-body { padding: 10px !important; }
            .add-customer-btn { padding: 6px 10px !important; font-size: 11px !important; }
            .search-wrapper input { font-size: 11px !important; }
            .grand-save-btn { padding: 14px !important; font-size: 13px !important; border-radius: 12px !important; }
            .field-label { font-size: 0.65rem !important; }
        }
      `}</style>
    </div>
  );
};

export default BookingPage;