import React, { useState } from 'react';
import { UserAccount, Mechanic, RepairBooking, EmergencySubscription, Booking } from '../types';
import { 
  Wrench, 
  ShieldCheck, 
  Timer, 
  MapPin, 
  Phone, 
  Calendar, 
  Heart, 
  AlertTriangle, 
  Check, 
  ArrowRight,
  LifeBuoy,
  X,
  CreditCard,
  ChevronRight
} from 'lucide-react';

interface RepairPageProps {
  currentUser: UserAccount;
  mechanics: Mechanic[];
  repairBookings: RepairBooking[];
  emergencySubscriptions: EmergencySubscription[];
  userBookings: Booking[]; // To check co-bookings within 5 days
  onBookRepair: (booking: RepairBooking) => void;
  onSubscribeEmergency: (sub: EmergencySubscription) => void;
  onUpdateWallet: (newBalance: number) => void;
  onDispatchEmergency: (bookingId: string) => void;
}

export default function RepairPage({
  currentUser,
  mechanics,
  repairBookings,
  emergencySubscriptions,
  userBookings,
  onBookRepair,
  onSubscribeEmergency,
  onUpdateWallet,
  onDispatchEmergency
}: RepairPageProps) {
  
  const [activeTab, setActiveTab] = useState<'schedule' | 'emergency' | 'logs'>('schedule');

  // Booking Form State
  const [selectedMechanicId, setSelectedMechanicId] = useState<string>('');
  const [repairDate, setRepairDate] = useState<string>('');
  const [repairTime, setRepairTime] = useState<string>('09:00');
  const [vehicleNumber, setVehicleNumber] = useState<string>('');
  const [vehicleType, setVehicleType] = useState<'Bicycle' | 'Bike' | 'Car' | 'Rickshah'>('Car');
  const [description, setDescription] = useState<string>('');
  const [couponCode, setCouponCode] = useState<string>('');
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);

  // Emergency Form State
  const [emergencyLocation, setEmergencyLocation] = useState<string>('');
  const [emergencyIssue, setEmergencyIssue] = useState<string>('');
  const [sosSuccess, setSosSuccess] = useState<boolean>(false);

  // Filtering approved mechanics
  const approvedMechanics = mechanics.filter(m => m.isApproved);

  // Check if user currently has an active 24/7 emergency subscription (bought in last 24 hours)
  const activeSubscription = emergencySubscriptions.find(sub => {
    if (sub.userEmail !== currentUser.email) return false;
    const expiresAt = new Date(sub.expiresAt).getTime();
    return expiresAt > Date.now() && sub.status === 'Active';
  });

  // Calculate if the user has a reservation (charging or parking booking) within 5 days of the target date
  const checkIfEligibleForDiscount = (targetDateStr: string): { eligible: boolean; bookingReason?: Booking } => {
    if (!targetDateStr) return { eligible: false };
    const targetDate = new Date(targetDateStr);
    
    // Check user bookings
    for (const b of userBookings) {
      if (b.userEmail.toLowerCase() !== currentUser.email.toLowerCase()) continue;
      
      const bookingDate = new Date(b.bookingDate);
      const diffTime = Math.abs(targetDate.getTime() - bookingDate.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      if (diffDays <= 5) {
        return { eligible: true, bookingReason: b };
      }
    }
    return { eligible: false };
  };

  // Helper calculation for price
  const selectedMechObj = approvedMechanics.find(m => m.id === selectedMechanicId);
  const basePrice = selectedMechObj ? selectedMechObj.baseFare : 300;
  const discountCheck = checkIfEligibleForDiscount(repairDate);
  const coBookingDiscount = discountCheck.eligible ? 100 : 0; // ₹100 discount
  const finalPrice = Math.max(100, basePrice - coBookingDiscount);

  // Submit appointment booking
  const handleScheduleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMsg(null);
    setSuccessMsg(null);

    if (!selectedMechanicId) {
      setErrorMsg('Please select a mechanic partner first.');
      return;
    }
    if (!repairDate) {
      setErrorMsg('Please choose an appointment date.');
      return;
    }
    if (!repairTime) {
      setErrorMsg('Please choose an appointment time.');
      return;
    }
    if (!vehicleNumber.trim()) {
      setErrorMsg('Please specify your vehicle registration plate number.');
      return;
    }

    // Check operating hours: normal repair available from 6:00 AM to 8:00 PM (06:00 - 20:00)
    const [hours, minutes] = repairTime.split(':').map(Number);
    if (hours < 6 || hours >= 20) {
      setErrorMsg('Normal bookings are ONLY available during day shift hours (6 AM to 8 PM). For 24/7 night coverage, pre-book our Emergency Rescue services! (₹50)');
      return;
    }

    const m = approvedMechanics.find(mech => mech.id === selectedMechanicId);
    if (!m) return;

    // Deduct user wallet
    const balance = currentUser.walletBalance ?? 250;
    if (balance < finalPrice) {
      setErrorMsg(`Insufficient Wallet Balance. This repair requires ₹${finalPrice}. Please add funds to your wallet!`);
      return;
    }

    // Book it
    const newRepairBooking: RepairBooking = {
      id: 'rbook-' + Math.random().toString(36).substring(2, 9),
      userEmail: currentUser.email,
      userName: currentUser.name,
      mechanicId: m.id,
      mechanicName: m.name,
      vehicleNumber: vehicleNumber.trim().toUpperCase(),
      vehicleType: vehicleType,
      bookingDate: repairDate,
      bookingTime: repairTime,
      description: description.trim() || 'General maintenance checkup',
      originalFare: basePrice,
      finalFare: finalPrice,
      isDiscountApplied: discountCheck.eligible,
      paymentMethod: 'COD',
      paymentStatus: 'Pending',
      status: 'Scheduled',
      isEmergency: false,
      createdAt: new Date().toISOString()
    };

    onBookRepair(newRepairBooking);
    onUpdateWallet(balance - finalPrice);
    
    setSuccessMsg(`Success! Scheduled repair appointment with ${m.name} under Co-Booking loyalty rate. ₹${finalPrice} paid out of wallet.`);
    
    // Clear inputs
    setVehicleNumber('');
    setDescription('');
    setSelectedMechanicId('');
  };

  // Subscribe to SOS Rescue plan
  const handlePreBookEmergency = () => {
    setErrorMsg(null);
    setSuccessMsg(null);

    const balance = currentUser.walletBalance ?? 250;
    const rate = 50; // ₹50 flat emergency pre-booking fee
    
    if (balance < rate) {
      alert(`Insufficient funds! Pre-booking the 24/7 shield costs ₹50. Please add money to your wallet.`);
      return;
    }

    const expiry = new Date();
    expiry.setHours(expiry.getHours() + 24); // valide for 24 hours

    const sub: EmergencySubscription = {
      id: 'sub-' + Math.random().toString(36).substring(2, 9),
      userEmail: currentUser.email,
      amountPaid: 50,
      prebookFare: 50,
      createdAt: new Date().toISOString(),
      expiresAt: expiry.toISOString(),
      status: 'Active'
    };

    onSubscribeEmergency(sub);
    onUpdateWallet(balance - rate);

    alert(`🛡️ 24/7 Mechanical On-Call Shield Activated! You are covered until ${expiry.toLocaleTimeString()} tomorrow. SOS dispatches can now be triggered free of base charges!`);
  };

  // Sos Dispatch trigger
  const handleSOSDispatch = (e: React.FormEvent) => {
    e.preventDefault();
    if (!emergencyLocation.trim()) {
      alert('Please specify your current breakdown address or landmark.');
      return;
    }

    // Query 24/7 mechanics
    const midnightMechs = approvedMechanics.filter(m => m.availabilityHours.includes('24/7'));
    const assignedMech = midnightMechs.length > 0 ? midnightMechs[Math.floor(Math.random() * midnightMechs.length)] : approvedMechanics[0];

    if (!assignedMech) {
      alert('We are currently setting up mechanical partners in Bihar. Please try again or call support.');
      return;
    }

    const dispatchBooking: RepairBooking = {
      id: 'rbook-' + Math.random().toString(36).substring(2, 9),
      userEmail: currentUser.email,
      userName: currentUser.name,
      mechanicId: assignedMech.id,
      mechanicName: assignedMech.name,
      vehicleNumber: 'IMMEDIATE DISPATCH',
      vehicleType: 'Car',
      bookingDate: new Date().toLocaleDateString(),
      bookingTime: new Date().toLocaleTimeString(),
      description: `SOS BREAKDOWN DISPATCH: ${emergencyIssue || 'Engine/Tire Fault'}`,
      originalFare: 0,
      finalFare: 0,
      isDiscountApplied: false,
      paymentMethod: 'COD',
      paymentStatus: 'Paid',
      status: 'Dispatched',
      isEmergency: true,
      createdAt: new Date().toISOString(),
      location: emergencyLocation.trim()
    };

    onBookRepair(dispatchBooking);
    setSosSuccess(true);
    setEmergencyLocation('');
    setEmergencyIssue('');

    setTimeout(() => {
      setSosSuccess(false);
      setActiveTab('logs');
    }, 4500);
  };

  return (
    <div id="repairing-system-container" className="max-w-7xl mx-auto px-4 py-8 space-y-8 text-left">
      
      {/* Banner design */}
      <div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 sm:p-8 flex flex-col md:flex-row items-center gap-6 justify-between relative overflow-hidden select-none shadow-xl">
        <div className="space-y-2 max-w-2xl text-left z-10">
          <span className="text-[10px] uppercase font-bold tracking-widest text-emerald-400 bg-emerald-950/40 border border-emerald-900/60 px-2 py-1 rounded-full inline-block">
            Authorized Mechanics Dispatch & Repairs
          </span>
          <h2 className="text-2xl sm:text-3xl font-black text-white tracking-tight">On-Road Assistance & Vehicle Care</h2>
          <p className="text-xs sm:text-sm text-slate-300 leading-relaxed">
            Reserve certified mechanics at special discounted rates. Pre-book our 24/7 roadside mechanical shield for day/night emergency protection across Bihar.
          </p>
        </div>
        <div className="text-slate-500 shrink-0 select-none hidden lg:block opacity-10">
          <Wrench className="w-40 h-40 transform rotate-12" />
        </div>
      </div>

      {/* Navigation Subtabs */}
      <div className="flex border-b border-slate-800 gap-2 text-xs font-mono font-bold scrollbar-hide overflow-x-auto pb-px">
        <button
          onClick={() => { setActiveTab('schedule'); setErrorMsg(null); setSuccessMsg(null); }}
          className={`px-4 py-3 border-b-2 transition-all flex items-center gap-2 whitespace-nowrap
            ${activeTab === 'schedule' 
              ? 'border-amber-500 text-white font-black bg-slate-900/40' 
              : 'border-transparent text-slate-400 hover:text-slate-200'}`}
        >
          <Calendar className="w-4 h-4 text-amber-500" />
          <span>Schedule Day Repair (6 AM - 8 PM)</span>
        </button>

        <button
          onClick={() => { setActiveTab('emergency'); setErrorMsg(null); setSuccessMsg(null); }}
          className={`px-4 py-3 border-b-2 transition-all flex items-center gap-2 whitespace-nowrap relative
            ${activeTab === 'emergency' 
              ? 'border-rose-500 text-white font-black bg-slate-900/40' 
              : 'border-transparent text-slate-400 hover:text-slate-250'}`}
        >
          <Timer className="w-4 h-4 text-rose-500" />
          <span>24/7 Roadside breakdown shield (₹50)</span>
          {activeSubscription && (
            <span className="w-2.5 h-2.5 bg-emerald-500 border border-slate-950 rounded-full animate-ping absolute top-2 right-1" />
          )}
        </button>

        <button
          onClick={() => { setActiveTab('logs'); setErrorMsg(null); setSuccessMsg(null); }}
          className={`px-4 py-3 border-b-2 transition-all flex items-center gap-2 whitespace-nowrap
            ${activeTab === 'logs' 
              ? 'border-teal-500 text-white font-black bg-slate-900/40' 
              : 'border-transparent text-slate-400 hover:text-slate-200'}`}
        >
          <Wrench className="w-4 h-4 text-teal-400" />
          <span>My Repair Logs ({repairBookings.filter(log => log.userEmail === currentUser.email).length})</span>
        </button>
      </div>

      {activeTab === 'schedule' && (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          
          {/* Booking Form element */}
          <div className="lg:col-span-2 space-y-6">
            <div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 space-y-4">
              <h3 className="text-base font-black text-white">Book Repair Service Partner</h3>
              <p className="text-xs text-slate-400">Regular servicing is only available during standard operating shifts (6:00 AM - 8:00 PM).</p>

              {errorMsg && (
                <div className="bg-rose-950/30 border border-rose-900/60 p-3 rounded-xl text-rose-400 text-xs font-mono">
                  ⚠️ {errorMsg}
                </div>
              )}

              {successMsg && (
                <div className="bg-emerald-950/30 border border-emerald-900/60 p-3 rounded-xl text-emerald-400 text-xs font-mono">
                  ✓ {successMsg}
                </div>
              )}

              <form onSubmit={handleScheduleSubmit} className="space-y-4 text-left">
                
                {/* Mechanic selector dropdown */}
                <div className="space-y-1.5">
                  <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Select Certified Mechanic Partner *</label>
                  <select
                    required
                    value={selectedMechanicId}
                    onChange={(e) => setSelectedMechanicId(e.target.value)}
                    className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-4 py-2 text-xs text-white outline-none"
                  >
                    <option value="">-- Choose a Mechanic --</option>
                    {approvedMechanics.map(mech => (
                      <option key={mech.id} value={mech.id}>
                        {mech.name} ({mech.specialty}) - Rate: ₹{mech.baseFare}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Preferred Appointment Date *</label>
                    <input
                      type="date"
                      required
                      value={repairDate}
                      onChange={(e) => setRepairDate(e.target.value)}
                      min={new Date().toISOString().split('T')[0]}
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-4 py-2 text-xs text-white outline-none font-mono"
                    />
                  </div>

                  <div className="space-y-1.5">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Preferred Time (6 AM - 8 PM only) *</label>
                    <input
                      type="time"
                      required
                      value={repairTime}
                      onChange={(e) => setRepairTime(e.target.value)}
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-4 py-2 text-xs text-white outline-none font-mono"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="space-y-1.5">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Vehicle Number plate *</label>
                    <input
                      type="text"
                      required
                      value={vehicleNumber}
                      onChange={(e) => setVehicleNumber(e.target.value)}
                      placeholder="e.g. MH-12-AB-1234"
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-4 py-2 text-xs text-white outline-none font-mono"
                    />
                  </div>

                  <div className="space-y-1.5">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Vehicle Category Type</label>
                    <select
                      value={vehicleType}
                      onChange={(e) => setVehicleType(e.target.value as any)}
                      className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-4 py-2 text-xs text-white outline-none"
                    >
                      <option value="Bike">Motorcycle / Electric Bike</option>
                      <option value="Car">Sedan / SUV Car / Heavy Auto</option>
                      <option value="Bicycle">Pedal Bicycle / Gear</option>
                      <option value="Rickshah">E-Rickshah Three Wheeler</option>
                    </select>
                  </div>
                </div>

                <div className="space-y-1.5">
                  <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Explain breakdown details or issue</label>
                  <textarea
                    rows={2}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    placeholder="e.g. Inverter not turning on, vehicle flat tire at garage, brake pad worn out..."
                    className="w-full bg-slate-950 border border-slate-800 focus:border-amber-500 rounded-xl px-4 py-2 text-xs text-white outline-none resize-none"
                  />
                </div>

                {/* Price Quote Panel with Co-booking loyalty validation */}
                {selectedMechanicId && repairDate && (
                  <div className="bg-slate-950 p-4 rounded-2xl border border-slate-800 space-y-2">
                    <span className="text-[10px] text-slate-500 font-bold uppercase tracking-wider block">Estimated Service Quotation</span>
                    
                    <div className="flex justify-between items-center text-xs">
                      <span className="text-slate-400">Mechanic Standard Base Charge:</span>
                      <strong className="text-white">₹{basePrice}</strong>
                    </div>

                    {discountCheck.eligible ? (
                      <div className="flex justify-between items-center text-xs text-emerald-400">
                        <span className="flex items-center gap-1">
                          <Check className="w-3.5 h-3.5" />
                          <span>Co-booking Loyalty discount (within 5d):</span>
                        </span>
                        <span>- ₹100</span>
                      </div>
                    ) : (
                      <div className="text-[10px] text-slate-500 leading-relaxed italic">
                        Tip: Book parking & charging on our app to get a ₹100 discount reward if within 5 days of repair!
                      </div>
                    )}

                    <div className="border-t border-slate-850 my-2 pt-2 flex justify-between items-center">
                      <strong className="text-sm text-slate-200">Total Net Amount Payable:</strong>
                      <span className="text-emerald-400 font-black text-base">₹{finalPrice}</span>
                    </div>

                    <div className="text-[10px] text-slate-400">
                      Paid dynamically using your system wallet. Your Balance: <strong className="text-slate-200">₹{currentUser.walletBalance ?? 250}</strong>
                    </div>
                  </div>
                )}

                <button
                  type="submit"
                  className="w-full py-3 bg-gradient-to-r from-amber-500 to-amber-400 hover:from-amber-400 hover:to-amber-300 text-slate-950 font-black text-xs rounded-xl shadow-lg transition"
                >
                  Confirm Appointment & Book Now
                </button>
              </form>
            </div>
          </div>

          {/* Mechanics info panel card list */}
          <div className="space-y-4">
            <div className="border-b border-indigo-950 pb-2">
              <h3 className="text-xs font-black text-indigo-400 uppercase tracking-widest block font-mono">Approved Mobile Mechanics Team</h3>
            </div>

            {approvedMechanics.length === 0 ? (
              <p className="text-xs text-slate-500 italic">No approved mechanics in Bihar registered yet.</p>
            ) : (
              approvedMechanics.map(mech => (
                <div key={mech.id} className="bg-slate-900 border border-slate-850 rounded-2xl p-4 space-y-3 hover:border-slate-800 transition">
                  <div className="flex items-center gap-3">
                    <img src={mech.photo} className="w-10 h-10 rounded-full object-cover border border-slate-800 shrink-0" alt="" referrerPolicy="no-referrer" />
                    <div>
                      <strong className="text-white text-xs block font-bold">{mech.name}</strong>
                      <span className="text-[9px] bg-slate-950 text-amber-500 px-1.5 py-0.2 border border-slate-850 rounded mt-0.5 inline-block font-mono">
                        {mech.specialty}
                      </span>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-2 text-[10px] text-slate-400 font-mono">
                    <div className="bg-slate-950/40 p-1.5 rounded-lg border border-slate-850">
                      <span className="text-[8px] text-slate-600 block uppercase font-sans">Shift Slots</span>
                      <span className="text-slate-300 block">{mech.availabilityHours}</span>
                    </div>
                    <div className="bg-slate-950/40 p-1.5 rounded-lg border border-slate-850">
                      <span className="text-[8px] text-slate-600 block uppercase font-sans">Base Charge</span>
                      <span className="text-emerald-400 block font-bold">₹{mech.baseFare}</span>
                    </div>
                  </div>

                  <div className="flex justify-between items-center text-[10px] text-slate-500 bg-slate-950/30 p-2 rounded-xl">
                    <span>📍 {mech.location}</span>
                    <span>⭐ {mech.rating} Rating</span>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      )}

      {activeTab === 'emergency' && (
        <div className="max-w-2xl mx-auto space-y-8 text-center py-4">
          
          {/* Main info */}
          <div className="bg-slate-900 border border-slate-800 rounded-3xl p-6 sm:p-8 space-y-4">
            <div className="w-12 h-12 bg-rose-500/10 border border-rose-500/30 text-rose-500 rounded-2xl flex items-center justify-center mx-auto mb-2 animate-bounce">
              <LifeBuoy className="w-6 h-6" />
            </div>

            <h3 className="text-lg font-black text-white">24/7 Breakdown & Night-Time Repair Cover</h3>
            <p className="text-xs text-slate-300 leading-relaxed max-w-lg mx-auto">
              Regular mechanic bookings are strictly unavailable at night (8 PM to 6 AM). Bikers, rickshah drives, or hybrid car owners can pre-book this mechanical rescue cover for just <strong className="text-emerald-400">₹50 flat rate</strong>.
            </p>

            <ul className="text-left text-xs text-slate-300 space-y-2 max-w-sm mx-auto bg-slate-950/60 p-4 rounded-xl border border-slate-850/60">
              <li className="flex items-center gap-1.5 text-slate-300">
                <Check className="w-4 h-4 text-emerald-400" />
                <span>Coverage active all day and night (24 hours)</span>
              </li>
              <li className="flex items-center gap-1.5 text-slate-300">
                <Check className="w-4 h-4 text-emerald-400" />
                <span>Zero dispatch fee / No basic base fare charged</span>
              </li>
              <li className="flex items-center gap-1.5 text-slate-300">
                <Check className="w-4 h-4 text-emerald-400" />
                <span>On-call mechanic arrives right at your spot</span>
              </li>
            </ul>

            {/* Sub/Status view */}
            {activeSubscription ? (
              <div className="bg-emerald-950/20 border border-emerald-900/60 p-4 rounded-2xl text-left space-y-2">
                <div className="flex items-center gap-2">
                  <span className="w-2.5 h-2.5 bg-emerald-400 rounded-full animate-ping" />
                  <strong className="text-emerald-400 text-xs font-bold font-mono">ACTIVE EMERGENCY PROTECTION COVER</strong>
                </div>
                <p className="text-[11px] text-slate-450 leading-relaxed font-medium">
                  Shield active for next 24 Hours. Valid until {new Date(activeSubscription.expiresAt).toLocaleTimeString()} on {new Date(activeSubscription.expiresAt).toLocaleDateString()}. Use the SOS controller below if you hit issues.
                </p>
              </div>
            ) : (
              <div className="space-y-2">
                <button
                  type="button"
                  onClick={handlePreBookEmergency}
                  className="px-6 py-3 bg-gradient-to-r from-rose-600 to-amber-600 hover:from-rose-500 hover:to-amber-500 text-white font-black text-xs rounded-xl shadow-lg transition"
                >
                  Activate 24/7 Roadside Cover (₹50)
                </button>
                <span className="block text-[10px] text-slate-500 font-medium">
                  Billed from system wallet. Your balance: ₹{currentUser.walletBalance ?? 250}
                </span>
              </div>
            )}
          </div>

          {/* SOS Form Activation */}
          {activeSubscription && (
            <div className="bg-rose-950/10 border border-rose-500/20 rounded-3xl p-6 text-left space-y-4">
              <h4 className="text-sm font-black text-rose-400 uppercase tracking-widest font-mono">⚠️ Trigger SOS Rescue Dispatch</h4>
              <p className="text-xs text-slate-400">Our closest 24/7 designated mechanic partner will be immediately assigned and route to you.</p>

              {sosSuccess ? (
                <div className="bg-emerald-950/30 border border-emerald-850 p-6 rounded-2xl text-center space-y-2">
                  <Check className="w-8 h-8 text-emerald-400 mx-auto animate-pulse" />
                  <strong className="text-white block text-xs">SOS Route Locked & Dispatch Active!</strong>
                  <p className="text-[11px] text-slate-300">Checking closest verified Bihar mechanical dispatch... Mechanics are on their way to rescue you.</p>
                </div>
              ) : (
                <form onSubmit={handleSOSDispatch} className="space-y-3">
                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Your Current Address / Landmark *</label>
                    <input
                      type="text"
                      required
                      value={emergencyLocation}
                      onChange={(e) => setEmergencyLocation(e.target.value)}
                      placeholder="e.g. Near Sasaram Bypass, Nokha Road"
                      className="w-full bg-slate-950 border border-rose-500/20 focus:border-rose-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    />
                  </div>

                  <div className="space-y-1">
                    <label className="text-[10px] font-bold text-slate-400 uppercase tracking-wide block">Briefly state the issue</label>
                    <input
                      type="text"
                      value={emergencyIssue}
                      onChange={(e) => setEmergencyIssue(e.target.value)}
                      placeholder="e.g. Electric Scooter cut off mid way, flat tire"
                      className="w-full bg-slate-950 border border-rose-500/20 focus:border-rose-500 rounded-xl px-3 py-2 text-xs text-white outline-none"
                    />
                  </div>

                  <button
                    type="submit"
                    className="w-full py-3 bg-rose-600 hover:bg-rose-500 text-white font-black text-xs rounded-xl shadow-lg transition flex items-center justify-center gap-1.5"
                  >
                    <span className="w-2.5 h-2.5 bg-white rounded-full animate-ping shrink-0" />
                    <span>EMERGENCY DISPATCH NOW</span>
                  </button>
                </form>
              )}
            </div>
          )}

        </div>
      )}

      {activeTab === 'logs' && (
        <div className="space-y-6">
          <div className="border-b border-slate-800 pb-2">
            <h3 className="text-sm font-black text-white">Your Mechanical Repair Checkins History</h3>
            <p className="text-xs text-slate-400">View statuses, pricing breakdown, and verified dispatch agents.</p>
          </div>

          {repairBookings.filter(log => log.userEmail === currentUser.email).length === 0 ? (
            <div className="bg-slate-900 mx-auto text-center p-12 rounded-3xl border border-slate-850 max-w-sm">
              <Wrench className="w-8 h-8 text-slate-500 mx-auto animate-pulse" />
              <span className="font-extrabold text-white text-xs block mt-2">No repair logs found!</span>
              <p className="text-slate-400 text-[11px] leading-relaxed mt-1">Book day appointments or pre-book emergency dispatch shields to log servicing activity.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {repairBookings
                .filter(log => log.userEmail === currentUser.email)
                .map((log) => {
                  const mObj = approvedMechanics.find(mech => mech.id === log.mechanicId);
                  
                  return (
                    <div key={log.id} className="bg-slate-900 border border-slate-850 rounded-2xl p-5 space-y-4 hover:border-slate-800 transition">
                      
                      <div className="flex justify-between items-start gap-4">
                        <div>
                          <div className="flex items-center gap-2">
                            <span className={`text-[9px] font-black tracking-wider uppercase px-1.5 py-0.5 rounded
                              ${log.isEmergency ? 'bg-rose-950 text-rose-400 border border-rose-900/60' : 'bg-slate-950 text-indigo-400 border border-slate-800/80'}`}>
                              {log.isEmergency ? '🔔 Emergency SOS' : '🧾 Normal Service'}
                            </span>
                            <span className="text-[10px] text-slate-500 font-mono font-bold">ID: {log.id}</span>
                          </div>
                          
                          <h4 className="text-sm font-black text-white mt-1 leading-snug">
                            {log.vehicleType} • {log.vehicleNumber}
                          </h4>
                        </div>

                        <div>
                          <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full
                            ${log.status === 'Dispatched' ? 'bg-amber-950/20 text-amber-400 border border-amber-900/40 animate-pulse' : 
                              log.status === 'Completed' ? 'bg-emerald-950/25 text-emerald-400 border border-emerald-900/40' : 
                              'bg-slate-950 text-slate-400 border border-slate-800'}`}>
                            {log.status}
                          </span>
                        </div>
                      </div>

                      <p className="text-xs text-slate-300 italic">
                        "{log.description}"
                      </p>

                      <div className="bg-slate-950 p-3 rounded-xl border border-slate-850 text-xs text-left space-y-1.5">
                        <div className="flex items-center gap-2">
                          <strong className="text-slate-300">Mechanic:</strong>
                          <span className="text-white font-bold">{log.mechanicName} ({mObj?.specialty || 'Bihar Authorized Mechanic'})</span>
                        </div>
                        
                        <div className="flex items-center gap-2">
                          <strong className="text-slate-300">Date & Slot:</strong>
                          <span className="text-slate-300 font-mono">{log.bookingDate} at {log.bookingTime}</span>
                        </div>

                        {log.location && (
                          <div className="flex items-center gap-2">
                            <strong className="text-slate-300">Dispatch Landmark:</strong>
                            <span className="text-rose-400 truncate">{log.location}</span>
                          </div>
                        )}

                        <div className="flex justify-between items-center border-t border-slate-850/60 pt-1.5 mt-1.5">
                          <span className="text-slate-400 font-mono text-[10px]">Net Charges paid:</span>
                          <span className="text-emerald-450 font-extrabold text-xs">₹{log.finalFare}</span>
                        </div>
                      </div>

                      {log.status === 'Dispatched' && (
                        <div className="flex justify-between items-center text-[10px] bg-amber-500/5 hover:bg-amber-500/10 border border-amber-500/15 p-2 rounded-xl text-amber-500">
                          <span className="flex items-center gap-1">
                            <Timer className="w-3.5 h-3.5 shrink-0 animate-spin" />
                            <span>Dispatch Active. Mechanic on way.</span>
                          </span>
                          
                          <button
                            type="button"
                            onClick={() => {
                              onDispatchEmergency(log.id);
                              alert('Mechanic completed the repairs successfully. Thank you for using ChargeBuddy Roadside Support!');
                            }}
                            className="bg-amber-500 hover:bg-amber-400 text-slate-950 px-2 py-1 rounded font-extrabold transition shrink-0"
                          >
                            Mark Fixed
                          </button>
                        </div>
                      )}

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

    </div>
  );
}
