// Component for creating, editing, and managing vehicle booking records, customer links, and logging deposits.
import React, { useState, useRef, useEffect } from "react";
import DateTimePicker from "./DateTimePicker";
import { MapPin, Clock, User, UserPlus, Car, Calendar, CreditCard, Tag, FileText, Camera, Save, X, Info, Gauge, Fuel, ArrowLeft, Trash2, Pencil, Printer, ChevronDown, ChevronUp, MoreVertical, Check, Package, DollarSign, Shield, CheckCircle, Percent, AlertCircle } 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";
constBookingPage = () => {
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: "", start_date: "", end_date: "",
base_price: "", discount_code: "", discount_percent: "0.00", discount_amount: "0.00", total_price: "",
tax_amount: "5"
    , advance_paid: "0.00", deposit: "1000.00", 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);
constvideoRef = useRef(null);
constcanvasRef = 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 [videoChunks, setVideoChunks] = useState([]);
const [carVideos, setCarVideos] = useState([]);
constmediaRecorderRef = useRef(null);
const [existingCarImages, setExistingCarImages] = useState([]);
const [existingCarVideos, setExistingCarVideos] = useState([]);
const [recordingTime, setRecordingTime] = useState(0);
const [selectedVideo, setSelectedVideo] = useState(null);
const [printType, setPrintType] = useState("");
const [activeInvoiceTab, setActiveInvoiceTab] = useState(0);
const [sectionCharges, setSectionCharges] = useState([
{ cleaning: 0, damage: 0, excess_km: 0, salik: 0 },
{ cleaning: 0, damage: 0, excess_km: 0, salik: 0 }
  ]);
const [isCollapsed, setIsCollapsed] = useState({
    customer: false,
    car: false,
    inspection: false,
    logistics: false,
    payment: false,
    invoice: false,
    remarks: false
  });
const [additionalCharges, setAdditionalCharges] = useState([[]]); constaddAdditionalCharge = (sectionIdx) => {
setAdditionalCharges(prev => {
const updated = [...prev];

constsectionData = updated[sectionIdx] || [];

      updated[sectionIdx] = [
        ...sectionData,
{ name: "", amount: 0 }
      ];

      return updated;
    });
  };
consthandleAdditionalChargeChange = (sectionIdx, idx, field, value) => {
setAdditionalCharges(prev => {
const updated = [...prev];
      updated[sectionIdx][idx][field] =
        field === "amount" ?parseFloat(value) || 0 : value;
      return updated;
    });
  };
constremoveAdditionalCharge = (sectionIdx, idx) => {
setAdditionalCharges(prev => {
const updated = [...prev];
      updated[sectionIdx] = updated[sectionIdx].filter((_, i) =>i !== idx);
      return updated;
    });
  };
consttotalDays = 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;

constnumberOfSections = Math.ceil(totalDays / 30);
useEffect(() => {
    if (!booking || numberOfSections === 0) return;

const tab = parseInt(searchParams.get("tab"));
constvalidTab = isNaN(tab) ?0 : tab;

setActiveInvoiceTab(validTab<numberOfSections ?validTab : 0);

  }, [searchParams, numberOfSections, booking]);
constgetDays = (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;
  };
consthandleSectionChargeChange = (sectionIdx, field, value) => {
constnewVal = parseFloat(value) || 0;
setSectionCharges(prev => {
const updated = [...prev];
      updated[sectionIdx] = { ...updated[sectionIdx], [field]: newVal };
      return updated;
    });
  };




useEffect(() => {
setSectionCharges(prev => {
constnewCharges = [...prev];
      while (newCharges.length<numberOfSections) {
newCharges.push({ cleaning: 0, damage: 0, excess_km: 0, salik: 0 });
      }
      return newCharges;
    });
  }, [numberOfSections]);
useEffect(() => {
setAdditionalCharges(prev => {
constnewAdd = [...prev];
      while (newAdd.length<numberOfSections) {
newAdd.push([]); // Oru oru section-kum empty array
      }
      return newAdd;
    });
  }, [numberOfSections]);
useEffect(() => {
constbaseRate = parseFloat(booking.base_price) || 0;
constgstPercent = parseFloat(booking.tax_amount) || 0;

consttotalBaseRent = baseRate * totalDays;

constadditionalChargesTotal = additionalCharges.reduce((acc, section) => {
      if (!section) return acc;

      return acc + section.reduce((sum, item) => {
        return sum + (parseFloat(item?.amount) || 0);
      }, 0);
    }, 0);
constallExtraCharges =
sectionCharges.reduce((acc, sec) =>
acc +
        (parseFloat(sec?.cleaning) || 0) +
        (parseFloat(sec?.damage) || 0) +
        (parseFloat(sec?.excess_km) || 0) +
        (parseFloat(sec?.salik) || 0),
        0)
      + additionalChargesTotal;
constsubTotal = totalBaseRent + allExtraCharges;
constgstAmount = (subTotal * gstPercent) / 100;
constfinalGrandTotal = subTotal + gstAmount;

setBooking(prev => ({
      ...prev,
total_price: finalGrandTotal.toFixed(2)
    }));
  }, [booking.base_price, booking.tax_amount, booking.start_date, booking.end_date, sectionCharges, additionalCharges]);
useEffect(() => {
window.scrollTo(0, 0);
  }, []);
useEffect(() => {
constinitPage = async () => {
constbookingId = searchParams.get("id");
constcarIdFromUrl = searchParams.get("car_id");

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

          if (data.cleaning_charges !== undefined) {
setSectionCharges(prev => {
constnewCharges = [...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 || "",
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 || "0.00",
advance_paid: data.advance_paid || "0.00",
total_price: data.total_price || "",
payment_status: data.payment_status || "Unpaid",
amount_collected: data.amount_collected || "0.00",
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 || "Weekly"
          }));

constimagesData = typeofdata.car_images === 'string' ?JSON.parse(data.car_images) :data.car_images;
constvideosData = typeofdata.car_videos === 'string' ?JSON.parse(data.car_videos) :data.car_videos;
setExistingCarImages(imagesData || []);
setExistingCarVideos(videosData || []);
          if (data.additional_charges) {
            try {
const parsed = typeofdata.additional_charges === 'string'
                ? JSON.parse(data.additional_charges)
                : data.additional_charges;
setAdditionalCharges(parsed || []);
            } catch (e) {
console.error("Error parsing additional charges", e);
setAdditionalCharges([]);
            }
          } else {
setAdditionalCharges([]);
          }

        } catch (err) {
console.error("Booking Fetch Error:", err);
        }
      }

      else if (carIdFromUrl || location.state?.car) {
constcarData = 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) {
console.error("Car Fetch Error:", err);
          }
        }
      }
    };

initPage();
  }, [searchParams, location.state]);
consthandlePrint = (type, sectionIndex = null) => {
    if (!booking.id) {
alert("Please save the booking first to get an ID!");
      return;
    }

    if (type === 'invoice' &&sectionIndex !== null) {
window.open(`/print/${type}/${booking.id}?tab=${sectionIndex}`, '_blank');
    } else {
window.open(`/print/${type}/${booking.id}`, '_blank');
    }
  };
consthandleSuccess = (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
    }));
setIsNewCustomer(false);
setShowModal(false);
  };

useEffect(() => {
constcarId = 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]);
constformatForInput = (dateStr) => {
    if (!dateStr) return "";
const date = new Date(dateStr);
    if (isNaN(date.getTime())) return "";

    // Local time values-ah direct-ah string-ah mathurom
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');

    return `${year}-${month}-${day}T${hours}:${minutes}`;
  };
useEffect(() => {
    if (!booking.car_id) return;
constfetchModes = 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]);
consthandleModeChange = (e) => {
constselectedFullText = e.target.value;

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

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

    if (selected) {
setBooking(prev => ({
        ...prev,
booking_mode: selectedFullText,
km_limit: selected.km,
base_price: selected.price,
total_price: selected.price
      }));
    }
  };
useEffect(() => {
    let interval;
    if (isRecording) {
setRecordingTime(0);
      interval = setInterval(() => {
setRecordingTime((prev) =>prev + 1);
      }, 1000);
    } else {
clearInterval(interval);
    }
    return () =>clearInterval(interval);
  }, [isRecording]);

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

conststartRecording = () => {
    if (!stream) {
alert("Please open the camera first!");
      return;
    }

constmimeType = MediaRecorder.isTypeSupported("video/webm")
      ? "video/webm"
      : "video/mp4";

constmediaRecorder = new MediaRecorder(stream, { mimeType });
mediaRecorderRef.current = mediaRecorder;

constlocalChunks = [];

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);
  };



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


consthandleInputChange = (e) => {
const{ name, value } = e.target;
setBooking(prev =>({ ...prev, [name]: value }));
  };

constopenCamera = 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"); }
  };
constcapturePhoto = () => {
const canvas = canvasRef.current;
const video = videoRef.current;
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;

constctx = 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");
  };
constselectCustomer = (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 || ""
    }));
setIsNewCustomer(false);
setCustomerResults([]);
  };
consthandleSubmit = async (e) => {
e.preventDefault();
constformData = new FormData();

constexcludeFromBackend = [
      'customer_name',
      'customer_email',
      'customer_phone',
      'customer_address',
      'customer_license',
      'car_brand',
      'car_model',
      'car_year',
      'car_km'
    ];
formData.append("additional_charges", JSON.stringify(additionalCharges));
consttotalCleaning = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.cleaning) || 0), 0);
consttotalDamage = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.damage) || 0), 0);
consttotalExcessKm = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.excess_km) || 0), 0);
consttotalSalik = sectionCharges.reduce((sum, s) => sum + (parseFloat(s.salik) || 0), 0);
const additional = (additionalCharges[activeInvoiceTab] || []).reduce(
      (sum, item) => sum + (parseFloat(item?.amount) || 0),
      0
    );
formData.append("cleaning_charges", totalCleaning);
formData.append("damage_charges", totalDamage);
formData.append("excess_km_charges", totalExcessKm);
formData.append("salik_charges", totalSalik);

Object.keys(booking).forEach((key) => {
      if (!excludeFromBackend.includes(key) && booking[key] !== null && booking[key] !== undefined) {
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' }
        });
alert("Booking Updated Successfully! ✅");
      } else {
        response = await api.post("/bookings", formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
alert("Booking Registered Successfully! ");
      }

constupdatedData = response.data;
constnewId = 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(
typeofupdatedData.car_images === 'string' ?JSON.parse(updatedData.car_images) :updatedData.car_images || []
      );
setExistingCarVideos(
typeofupdatedData.car_videos === 'string' ?JSON.parse(updatedData.car_videos) :updatedData.car_videos || []
      );

setCarImages([]);
setCarVideos([]);

      // --------- NEW: Update Fleet table ---------------
      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
          });
console.log("Fleet updated successfully");
        } catch (fleetErr) {
console.error("Error updating fleet:", fleetErr);
        }
      }
      // -------------------------------------------------

    } catch (err) {
console.error("Submit Error:", err);
alert("Error saving: " + (err.response?.data?.message || err.message));
    }
  };
constCurrencyIcon = () => (
<img
src={aedIcon}
      alt="AED"
      style={{ width: "20px", height: "15px", marginLeft: "4px", verticalAlign: "middle" }}
    />
  );
consttoggleCollapse = (section) => setIsCollapsed(prev => ({ ...prev, [section]: !prev[section] }));
constSectionHeader = ({ icon, title, section, badge, badgeColor = "primary" }) => (
<div
className="section-header d-flex justify-content-between align-items-center cursor-pointer"
onClick={() =>toggleCollapse(section)}
>
<div className="d-flex align-items-center gap-2">
        {icon}
<h4 className="panel-title m-0">{title}</h4>
        {badge &&<span className={`badge bg-${badgeColor} ms-2`}>{badge}</span>}
</div>
<div className="d-flex align-items-center gap-2">
        {isCollapsed[section] ?<ChevronDown size={18} /> :<ChevronUp size={18} />}
</div>
</div>
  );


constadditionalChargesTotal = additionalCharges.reduce((acc, section) => {
    return acc + section.reduce((sum, item) => sum + (parseFloat(item.amount) || 0), 0);
  }, 0);

constgrandTotal = parseFloat(booking.total_price || 0);

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

  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-3 ">
              {/* title  */}
<h1 className="booking-title">
<Car size={30} className="me-2" />
                {booking.id ? "Edit Booking" : "New Booking"}
</h1>
              {booking.id && (
<span className="booking-id-badge">
                  # {booking.id}
</span>
              )}
</div>

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


<div className="col-12 col-xl-6">
<div className="glass-panel " >
              {/* Header */}
<div className="d-flex justify-content-between align-items-center mb-2">
<h4 className="panel-title mb-0">
<User size={18} className="me-2" />
ID :
<span className="ms-2 customer-id-badge">
                    {booking.cus_id || "-----"}
</span>
</h4>

                {/* Search */}
{!booking.cus_id&& !isNewCustomer&& (
<div className="col-md-5">
<label className="field-label">&nbsp;</label>
<div className="search-wrapper position-relative">
<input
className="form-control glass-input"
                        placeholder="Search by name / phone / email..."
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) {
console.error(err);
                          }
                        }}
                      />

                      {customerResults.length> 0 && (
<div className="search-dropdown shadow-lg">
                          {customerResults.map((c) => (
<div
                              key={c.cus_id}
className="search-item"
onClick={() =>selectCustomer(c)}
>
<div className="cus-info">
<span className="cus-name">{c.full_name}</span>
<span className="cus-meta">
                                  {c.mobile} • ID: {c.cus_id}
</span>
</div>
</div>
                          ))}
</div>
                      )}
</div>
</div>
                )}


{!isNewCustomer ? (
booking.cus_id ? (
<button
                      type="button"
className="btn btn-primary add-customer-btn"
onClick={() =>
setBooking(prev => ({
                          ...prev,
cus_id: "",
customer_name: "",
customer_phone: "",
customer_email: "",
customer_license: "",
                        }))
                      }
>
<X size={14} className="me-1" />
                      Change
</button>
                  ) : (
<button
                      type="button"
className="btn btn-primary add-customer-btn"
onClick={() => {
setShowModal(true);
setIsNewCustomer(true);
                      }}
>
<UserPlus size={16} className="me-1" />
                      New Customer
</button>
                  )
                ) : (
<button
                    type="button"
className="btn btn-outline-light"
onClick={() =>setIsNewCustomer(false)}
>
<ArrowLeft size={14} className="me-1" />
                    Search Existing
</button>
                )}

</div>

<div className="row g-3">
{!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.." /></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" /></div>
<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" /></div>
<div className="col-md-6"><label className="field-label">License No</label><input className="form-control glass-input" name="customer_license" value={booking.customer_license} onChange={handleInputChange} placeholder="1234567890" /></div>
</>
                )}
</div>
</div>

            {/* car details  */}
<div className="booking-card">
<div className="section-header d-flex justify-content-between align-items-center">
<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>
<div className="section-body ">
<div className="row g-2">
<div className="col-md-3">
<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-6">
<label className="field-label">Brand</label>
<input className="form-control glass-input" value={booking.car_brand || "-"} readOnly />
</div>

<div className="col-md-3 mb-0">
<label className="field-label">Year</label>
<input className="form-control glass-input" value={booking.car_year || "-"} readOnly />
</div>
<div className="col-md-12 mt-0">
<label className="field-label">Model</label>
<input className="form-control glass-input" value={booking.car_model || "-"} readOnly />
</div>
</div>
</div>
</div>

            {/* Inspection Section */}
<div className="booking-card">
<div className="section-header d-flex justify-content-between align-items-center">
<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>
{!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="btn btn-outline-info">
<Camera size={16} className="me-1" /> Open Camera
</button>
                    ) : (
<>
<button
                          type="button"
onClick={isRecording ?stopRecording :startRecording}
className={`btn ${isRecording ? 'btn-danger' : 'btn-success'}`}
>
                          {isRecording ?<X size={16} className="me-1" /> :<Car size={16} className="me-1" />}
                          {isRecording ? "Stop Video" : "Record Video"}
</button>
<button type="button" onClick={capturePhoto} className="btn btn-outline-primary">
<Camera size={16} className="me-1" /> Capture
</button>
<button
                          type="button"
className="btn btn-outline-danger"
onClick={() =>{ if (isRecording) stopRecording(); stream.getTracks().forEach(t =>t.stop()); setShowCamera(false); }}
>
                          Close Camera
</button>
</>
                    )}
</div>

                  {showCamera&& (
<div className="camera-preview">
<video ref={videoRef} autoPlay muted playsInline className="camera-video" />
                      {isRecording&& (
<div className="recording-overlay">
<div className="recording-dot" />
<span>{formatTime(recordingTime)}</span>
</div>
                      )}
<canvas ref={canvasRef} hidden />
</div>
                  )}

<div className="media-grid">
                    {existingCarImages.map((imgName, i) => (
<div key={`ex-img-${i}`} className="media-item">
<img src={`/car/api/uploads/${imgName}`} alt="car" />
<button type="button" className="media-delete-btn" onClick={() =>setExistingCarImages(existingCarImages.filter((_, idx) =>idx !== i))}>
<X size={14} />
</button>
<span className="media-badge existing">Existing</span>
</div>
                    ))}
                    {carImages.map((file, i) => (
<div key={`new-img-${i}`} className="media-item new">
<img src={URL.createObjectURL(file)} alt="new" />
<button type="button" className="media-delete-btn" onClick={() =>setCarImages(carImages.filter((_, idx) =>idx !== i))}>
<X size={14} />
</button>
<span className="media-badge new">New</span>
</div>
                    ))}
                    {existingCarVideos.map((vidName, i) => (
<div key={`ex-vid-${i}`} className="media-item video" onClick={() =>setSelectedVideo(`/car/api/uploads/${vidName}`)}>
<video src={`/car/api/uploads/${vidName}`} />
<div className="play-icon">▶</div>
<button type="button" className="media-delete-btn" onClick={(e) =>{ e.stopPropagation(); setExistingCarVideos(existingCarVideos.filter((_, idx) =>idx !== i)); }}>
<X size={14} />
</button>
<span className="media-badge existing">Existing</span>
</div>
                    ))}
                    {carVideos.map((file, i) => (
<div key={`new-vid-${i}`} className="media-item video new" onClick={() =>setSelectedVideo(URL.createObjectURL(file))}>
<video src={URL.createObjectURL(file)} />
<div className="play-icon">▶</div>
<button type="button" className="media-delete-btn" onClick={(e) =>{ e.stopPropagation(); setCarVideos(carVideos.filter((_, idx) =>idx !== i)); }}>
<X size={14} />
</button>
<span className="media-badge new">New</span>
</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>


            {/* Trip Logistics Section */}
<div className="booking-card">
<div className="section-header d-flex justify-content-between align-items-center">
<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>

{!isCollapsed.logistics&& (
<div className="d-flex ">
                  {/* LEFT SIDE - 6 columns */}
<div className="col-md-6">
<div className="section-body">
                      {/* Status Row */}
<div className="row g-2">
<div className="col-md-12">
<label className="field-label" style={{ marginBottom: "0" }}>Booking Status</label>
<select name="status" value={booking.status} onChange={handleInputChange} className="form-select glass-input">
<option value="">Select status</option>
<option value="confirmed">Confirmed</option>
<option value="On-Trip">On Trip</option>
<option value="returned">Returned</option>
<option value="completed">Completed</option>
<option value="cancelled">Cancelled</option>
</select>
</div>
</div>

                      {/* KM Row */}
<div className="row g-2 ">
<div className="col-md-6">
<label className="field-label"><Gauge size={12} className="me-1" /> Starting KMs</label>
<input type="number" className="form-control glass-input bg-dark-soft" name="starting_kms" value={booking.starting_kms} readOnly style={{ opacity: 0.8, cursor: 'not-allowed' }} />
</div>
<div className="col-md-6">
<label className="field-label"><Gauge size={12} className="me-1" /> 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>

                      {/* Fuel Row */}
<div className="row g-2 ">
<div className="col-md-6">
<label className="field-label"><Fuel size={12} className="me-1" /> Start Fuel</label>
<select className="form-control glass-input" name="fuel_level" value={booking.fuel_level} onChange={handleInputChange}>
<option value="">Select Fuel Level</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} className="me-1" /> Return Fuel</label>
<select className="form-control glass-input" name="return_fuel_level" value={booking.return_fuel_level} onChange={handleInputChange}>
<option value="">Select Fuel Level</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>
</div>
</div>
                  {/* RIGHT SIDE - Timeline Style */}
<div className="col-md-6 d-flex justify-content-evenly">
<div className="section-body">

                      {/* ─── PICKUP ─── */}
<div className="d-flex align-items-start mb-1">
<div className="d-flex flex-column align-items-center me-2" style={{ paddingTop: '4px' }}>
<div className="rounded-circle bg-success" style={{ width: "12px", height: "12px" }}></div>
</div>

<div className="flex-grow-1">
<h6 className="fw-bold text-success mb-1">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>


                      {/* ─── DROP ─── */}
<div className="d-flex align-items-start">
                        {/* Timeline Dot */}
<div className="d-flex flex-column align-items-center me-2" style={{ paddingTop: '4px' }}>
<div className="rounded-circle bg-danger" style={{ width: "12px", height: "12px" }}></div>
</div>

                        {/* Drop Details */}
<div className="flex-grow-1">
<h6 className="fw-bold text-danger mb-2">Drop</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 className="">
                            {/* <div className="d-flex align-items-center mb-1">
<Calendar size={14} className="text-danger me-1" />
<small className="text-muted fw-semibold me-2">Date & Time</small>
</div> */}
<DateTimePicker
                              name="end_date"
                              value={booking.end_date || ""}
onChange={(iso) =>
handleInputChange({
                                  target: { name: "end_date", value: iso },
                                })
                              }
                              placeholder="Select Date & Time"
minDate={booking.start_date ?booking.start_date.slice(0, 10) : ""}
                            />
</div>
</div>
</div>

</div>
</div>


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

          {/* closing 1 row*/}


<div className="col-12 col-xl-6">

<div className="glass-panel mb-3">
<h4 className="panel-title"> Payment & Billing</h4>
<div className="row g-2">
                {/* Booking ID */}
<div className="col-md-6"><label className="field-label"><FileText size={12} className="me-1" />Booking ID</label><input className="form-control glass-input" value={booking.id || "Auto-generated"} readOnly style={{ color: booking.id ? '#4ade80' : '#94a3b8' }} /></div>
<div className="col-md-6">
                  {/* Booking Date */}
<label className="field-label">
<Calendar size={12} className="me-1" /> Booking Date</label>
<DateTimePicker
                    name="booking_date"
                    value={booking.booking_date || ""}
onChange={(iso) =>handleInputChange({ target: { name: "booking_date", value: iso } })}
                    placeholder="Date &Time  "
                  />
</div>
                {/* Payment Type */}
<div className="col-md-6">
<label className="field-label"><CreditCard size={12} className="me-1" /> Payment Type</label>
<select className="form-select glass-input" name="payment_method" value={booking.payment_method} onChange={handleInputChange}>
<option value="Cash">💵 Cash</option><option value="Card">💳 Card</option><option value="Bank Transfer">🏦 Bank Transfer</option>
</select>
</div>
                {/* Trip Package */}
<div className="col-md-6">
<label className="field-label"><Package size={12} className="me-1" />Trip Package</label>
<select className="form-select glass-input" name="trip_package" value={booking.trip_package || "Weekly"} onChange={handleInputChange}>
<option value="Daily">📅 Daily</option>
<option value="Weekly">📆 Weekly</option>
<option value="Monthly">📊 Monthly</option>
</select>
</div>

                {/* Total Amount */}
<div className="col-md-6"><label className="field-label"><DollarSign size={12} className="me-1" />Base Price</label>
<input type="number" className="form-control glass-input" name="base_price" value={booking.base_price} onChange={handleInputChange} />
</div>
                {/* Total Amount */}
<div className="col-md-6">
<div className="highlight-box">
<label className="field-label"><DollarSign size={12} className="me-1" /> Total Amount</label>
<input className="form-control glass-input ps-5 fw-bold text-success" value={booking.total_price || "0.00"}
                      style={{ background: 'rgba(74, 222, 128, 0.08)', borderColor: 'rgba(74, 222, 128, 0.3)' }} /></div>
</div>


                {/* Financial Details Section */}
<div className="p-3 rounded-4 mb-3" style={{ background: 'rgba(225, 78, 202, 0.05)', border: '1px solid rgba(225, 78, 202, 0.1)' }}>
<div className="row g-2 justify-content-between">
<div className="col-md-3">
<label className="field-label"><Shield size={12} />Security Deposit</label>
<input type="number" name="deposit" className="form-control glass-input bg-transparent fw-bold text-warning py-1" value={booking.deposit} onChange={handleInputChange} />
</div>
                    {/* Advance Paid */}
<div className="col-md-3">
<label className="field-label"><CheckCircle size={12} className="me-1" />Advance Paid</label>
<input type="number" name="advance_paid" className="form-control glass-input bg-transparent fw-bold text-success py-1" value={booking.advance_paid} onChange={handleInputChange} />
</div>
                    {/* Tax */}
<div className="col-md-3">
<label className="field-label"><Percent size={12} className="me-1" />Tax (%)</label>
<input type="number" name="tax_amount" className="form-control glass-input bg-transparent py-1" value={booking.tax_amount} onChange={handleInputChange} />
</div>
</div>

                  {/* Balance to Pay */}
<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(239, 68, 68, 0.08), rgba(239, 68, 68, 0.02))',
                        border: '1px solid rgba(239, 68, 68, 0.15)'
                      }}>
<div>
<label className="field-label text-danger m-0" style={{ fontSize: '14px' }}>
<AlertCircle size={16} className="me-2" />
                            Balance to Pay
</label>
</div>
<div className="text-danger fw-bold" style={{ fontSize: '1.5rem' }}>
                          AED {balanceToPay?.toFixed(2) || '0.00'}
</div>
</div>
</div>
</div>
</div>

<style>{`
.field-label-tiny { font-size: 9px; color: #64748b; text-transform: uppercase; font-weight: bold; margin-bottom: 2px; display: block; }
`}</style>

</div>
</div>
            {/* deatiled voice split */}
<div className="glass-panel mb-3">
<div className="d-flex justify-content-between align-items-center mb-3">
<h4 className="panel-title m-0"><FileText size={18} /> Detailed Invoice Split</h4>
<div className="d-flex gap-2 flex-wrap">
<select
className="form-select form-select-sm"
                    value={activeInvoiceTab}
onChange={(e) =>setActiveInvoiceTab(parseInt(e.target.value))}
                    style={{
maxWidth: "220px",
backgroundColor: "#1E2A38",
color: "#00FFE0",
borderColor: "#00FFE0"
                    }}
>
                    {Array.from({ length: numberOfSections }).map((_, idx) => {
conststartDay = idx * 30 + 1;
constendDay = Math.min((idx + 1) * 30, totalDays);

                      return (
<option key={idx} value={idx}>
                          Invoice {idx + 1} ({startDay}-{endDay} Days)
</option>
                      );
                    })}
</select>
</div>

</div>


              {(() => {
consttotalDays = getDays(booking.start_date, booking.end_date);
constbaseRate = parseFloat(booking.base_price) || 0;
conststartDay = (activeInvoiceTab * 30) + 1;

constendDay = Math.min((activeInvoiceTab + 1) * 30, totalDays);

constcurrentDays = 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-center">
<div className="col-md-5 border-end border-secondary border-opacity-25">
<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="row g-2">
                          {/* Existing Fields */}
<div className="col-6">
<label className="field-label-tiny">Cleaning</label>
<input type="number" className="form-control glass-input bg-transparent py-1 text-white" value={sectionCharges[activeInvoiceTab].cleaning} onChange={(e) =>handleSectionChargeChange(activeInvoiceTab, 'cleaning', e.target.value)} />
</div>
<div className="col-6">
<label className="field-label-tiny">Damage</label>
<input type="number" className="form-control glass-input bg-transparent py-1 text-white" value={sectionCharges[activeInvoiceTab].damage} onChange={(e) =>handleSectionChargeChange(activeInvoiceTab, 'damage', e.target.value)} />
</div>
<div className="col-6">
<label className="field-label-tiny">Excess KM</label>
<input type="number" className="form-control glass-input bg-transparent py-1 text-white" value={sectionCharges[activeInvoiceTab].excess_km} onChange={(e) =>handleSectionChargeChange(activeInvoiceTab, 'excess_km', e.target.value)} />
</div>
<div className="col-6">
<label className="field-label-tiny">Salik / Toll</label>
<input type="number" className="form-control glass-input bg-transparent py-1 text-white" value={sectionCharges[activeInvoiceTab].salik} onChange={(e) =>handleSectionChargeChange(activeInvoiceTab, 'salik', e.target.value)} />
</div>

                          {/* Additional Charges Section */}
<div className="col-12 mt-3">
<h6 className="field-label-tiny mb-2">ADDITIONAL CHARGES</h6>
</div>

                          {additionalCharges[activeInvoiceTab]?.map((charge, idx) => (
<React.Fragment key={idx}>
                              {/* Description Field (Full Width like a label/input pair) */}
<div className="col-6">
<label className="field-label-tiny">Description</label>
<input
                                  type="text"
                                  placeholder="Enter charge name..."
                                  value={charge.name}
onChange={(e) =>handleAdditionalChargeChange(activeInvoiceTab, idx, "name", e.target.value)}
className="form-control glass-input bg-transparent py-1 text-white"
                                />
</div>

<div className="col-6">
<label className="field-label-tiny d-flex justify-content-between">
                                  Amount
<span
onClick={() =>removeAdditionalCharge(activeInvoiceTab, idx)}
                                    style={{ color: '#ff4d4d', cursor: 'pointer', fontSize: '10px' }}
>
                                    REMOVE
</span>
</label>
<div className="d-flex gap-2">
<input
                                    type="number"
                                    placeholder="0"
                                    value={charge.amount}
onChange={(e) =>handleAdditionalChargeChange(activeInvoiceTab, idx, "amount", e.target.value)}
className="form-control glass-input bg-transparent py-1 text-white"
                                  />
</div>
</div>
</React.Fragment>
                          ))}

<div className="col-12 mt-2">
<button
                              type="button"
onClick={() =>addAdditionalCharge(activeInvoiceTab)}
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>
</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">
                        {(() => {
conststartDay = (activeInvoiceTab * 30) + 1;
constendDay = Math.min((activeInvoiceTab + 1) * 30, totalDays);
constcurrentTabDays = endDay - startDay + 1;
constbaseRate = parseFloat(booking.base_price) || 0;
constsectionRent = currentTabDays * baseRate;
constsectionExtra = (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="glass-panel mb-3">
<h4 className="panel-title"><FileText size={18} /> 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>
