import React, { useState, useEffect, useCallback } from 'react';
import {
  Plus, Search, Truck, X, Loader2, CheckCircle,
  AlertCircle, ChevronDown, Edit2
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { fleetApi } from '../../api/fleet';

interface Station {
  id: string;
  name: string;
}

interface Vehicle {
  id: string;
  registration_number: string;
  vehicle_type: string;
  brand?: string;
  model?: string;
  chassis_number?: string;
  engine_number?: string;
  make_year?: number;
  stretcher_capacity?: number;
  ownership_type?: string;
  station_id?: string;
  status?: string;
}

interface VehicleForm {
  registration_number: string;
  vehicle_type: string;
  chassis_number: string;
  brand: string;
  model: string;
  station_id: string;
  engine_number: string;
  make_year: number | '';
  stretcher_capacity: number | '';
  ownership_type: string;
}

const VEHICLE_TYPES = ['ALS', 'BLS', 'TRANSPORT', 'ICU', 'NEONATAL'];
const OWNERSHIP_TYPES = ['self-owned', 'hospital-owned', 'leased'];

const EMPTY_FORM: VehicleForm = {
  registration_number: '',
  vehicle_type: 'ALS',
  chassis_number: '',
  brand: '',
  model: '',
  station_id: '',
  engine_number: '',
  make_year: '',
  stretcher_capacity: '',
  ownership_type: 'self-owned',
};

const cardStyle: React.CSSProperties = {
  background: '#FFFFFF',
  border: '1px solid rgba(15, 23, 42, 0.08)',
  borderRadius: '16px',
  padding: '24px',
  boxShadow: '0 4px 20px rgba(15, 23, 42, 0.02)',
};

const labelStyle: React.CSSProperties = {
  fontSize: '0.7rem',
  color: '#475569',
  textTransform: 'uppercase',
  letterSpacing: '1px',
  marginBottom: '6px',
  display: 'block',
};

const inputStyle: React.CSSProperties = {
  background: '#FFFFFF',
  border: '1px solid #CBD5E1',
  padding: '11px 14px',
  borderRadius: '10px',
  color: '#0F172A',
  fontSize: '0.875rem',
  outline: 'none',
  width: '100%',
  boxSizing: 'border-box',
  transition: 'border-color 0.2s',
};

const selectStyle: React.CSSProperties = {
  ...inputStyle,
  cursor: 'pointer',
  appearance: 'none',
  WebkitAppearance: 'none',
};

export const FleetAssets: React.FC = () => {
  const [searchQuery, setSearchQuery] = useState('');
  const [isSearchFocused, setIsSearchFocused] = useState(false);
  const [selectedStationFilter, setSelectedStationFilter] = useState('');
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [stations, setStations] = useState<Station[]>([]);
  const [stationsLoading, setStationsLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [editingVehicle, setEditingVehicle] = useState<Vehicle | null>(null);
  const [showEditModal, setShowEditModal] = useState(false);
  const [form, setForm] = useState<VehicleForm>(EMPTY_FORM);
  const [editForm, setEditForm] = useState<VehicleForm>(EMPTY_FORM);
  const [submitting, setSubmitting] = useState(false);
  const [toast, setToast] = useState<{ type: 'success' | 'error'; message: string } | null>(null);

  const token = localStorage.getItem('teleems_token') || '';

  const showToast = (type: 'success' | 'error', message: string) => {
    setToast({ type, message });
    setTimeout(() => setToast(null), 4000);
  };

  const fetchStations = useCallback(async () => {
    setStationsLoading(true);
    try {
      const json = await fleetApi.getStations(token);
      let list: Station[] = [];
      if (json?.data?.data && Array.isArray(json.data.data)) list = json.data.data;
      else if (json?.data && Array.isArray(json.data)) list = json.data;
      else if (Array.isArray(json)) list = json;
      setStations(list);
    } catch (e) {
      console.error('Failed to fetch stations:', e);
    } finally {
      setStationsLoading(false);
    }
  }, [token]);

  const fetchVehicles = useCallback(async () => {
    setLoading(true);
    try {
      const json = selectedStationFilter
        ? await fleetApi.getVehiclesByStationName(token, selectedStationFilter)
        : await fleetApi.getVehicles(token);

      let list: Vehicle[] = [];
      if (json?.data?.data && Array.isArray(json.data.data)) list = json.data.data;
      else if (json?.data && Array.isArray(json.data)) list = json.data;
      else if (Array.isArray(json)) list = json;
      setVehicles(list);
    } catch (e) {
      console.error('Failed to fetch vehicles:', e);
    } finally {
      setLoading(false);
    }
  }, [token, selectedStationFilter]);

  useEffect(() => { fetchVehicles(); fetchStations(); }, [fetchVehicles, fetchStations]);

  // Debounced search by registration_number — fires 400ms after user stops typing
  useEffect(() => {
    if (!searchQuery.trim()) return; // empty → fetchVehicles handles it via selectedStationFilter
    const timer = setTimeout(async () => {
      setLoading(true);
      try {
        const json = await fleetApi.getVehiclesByRegistrationNumber(token, searchQuery.trim());
        let list: Vehicle[] = [];
        if (json?.data?.data && Array.isArray(json.data.data)) list = json.data.data;
        else if (json?.data && Array.isArray(json.data)) list = json.data;
        else if (Array.isArray(json)) list = json;
        setVehicles(list);
      } catch (e) {
        console.error('Failed to search vehicles:', e);
      } finally {
        setLoading(false);
      }
    }, 400);
    return () => clearTimeout(timer);
  }, [searchQuery, token]);

  const openModal = () => {
    setForm(EMPTY_FORM);
    setShowModal(true);
  };

  const openEditModal = (v: Vehicle) => {
    setEditingVehicle(v);
    setEditForm({
      registration_number: v.registration_number || '',
      vehicle_type: v.vehicle_type || 'ALS',
      chassis_number: v.chassis_number || '',
      brand: v.brand || '',
      model: v.model || '',
      station_id: v.station_id || '',
      engine_number: v.engine_number || '',
      make_year: v.make_year || '',
      stretcher_capacity: v.stretcher_capacity || '',
      ownership_type: v.ownership_type || 'self-owned',
    });
    setShowEditModal(true);
  };

  const handleUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editingVehicle) return;
    setSubmitting(true);
    try {
      const payload = {
        registration_number: editForm.registration_number,
        vehicle_type: editForm.vehicle_type,
        station_id: editForm.station_id || undefined,
        chassis_number: editForm.chassis_number || undefined,
        brand: editForm.brand,
        model: editForm.model,
        engine_number: editForm.engine_number || undefined,
        make_year: editForm.make_year ? Number(editForm.make_year) : undefined,
        stretcher_capacity: editForm.stretcher_capacity ? Number(editForm.stretcher_capacity) : undefined,
        ownership_type: editForm.ownership_type || undefined,
      };
      const json = await fleetApi.updateVehicleDetails(editingVehicle.id, payload, token);
      if (!json) return;
      if (!json.status || json.status < 400 || json?.id || json?.data?.id) {
        showToast('success', 'Vehicle updated successfully!');
        setShowEditModal(false);
        setEditingVehicle(null);
        fetchVehicles();
      } else {
        showToast('error', json?.message || `Error ${json.status || ''}: Failed to update vehicle.`);
      }
    } catch (err: any) {
      showToast('error', err?.message || 'Network error.');
    } finally {
      setSubmitting(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!form.station_id) {
      showToast('error', 'Please select a station.');
      return;
    }
    setSubmitting(true);
    try {
      const payload = {
        registration_number: form.registration_number,
        vehicle_type: form.vehicle_type,
        station_id: form.station_id,
        chassis_number: form.chassis_number || undefined,
        brand: form.brand,
        model: form.model,
        engine_number: form.engine_number || undefined,
        make_year: form.make_year ? Number(form.make_year) : undefined,
        stretcher_capacity: form.stretcher_capacity ? Number(form.stretcher_capacity) : undefined,
        ownership_type: form.ownership_type || undefined,
      };

      const json = await fleetApi.createVehicle(payload, token);
      if (!json) return;
      if (!json.status || json.status < 400 || json?.id || json?.data?.id) {
        showToast('success', `Vehicle "${form.registration_number}" registered successfully!`);
        setShowModal(false);
        setForm(EMPTY_FORM);
        fetchVehicles();
      } else {
        showToast('error', json?.message || `Error ${json.status || ''}: Failed to register vehicle.`);
      }
    } catch (err: any) {
      showToast('error', err?.message || 'Network error. Please check your connection.');
    } finally {
      setSubmitting(false);
    }
  };

  // When search is cleared, reload via fetchVehicles (respects station filter)
  useEffect(() => {
    if (!searchQuery.trim()) {
      fetchVehicles();
    }
  }, [searchQuery, fetchVehicles]);

  const getStatusColor = (status?: string) => {
    if (status === 'ACTIVE') return { bg: 'rgba(34,197,94,0.1)', border: 'rgba(34,197,94,0.2)', color: '#22C55E' };
    if (status === 'BREAKDOWN') return { bg: 'rgba(239,68,68,0.1)', border: 'rgba(239,68,68,0.2)', color: '#EF4444' };
    return { bg: 'rgba(245,158,11,0.1)', border: 'rgba(245,158,11,0.2)', color: '#F59E0B' };
  };

  return (
    <div style={{ color: '#0F172A', position: 'relative' }}>

      <AnimatePresence>
        {toast && (
          <motion.div
            initial={{ opacity: 0, y: -20, x: '-50%' }}
            animate={{ opacity: 1, y: 0, x: '-50%' }}
            exit={{ opacity: 0, y: -20, x: '-50%' }}
            style={{
              position: 'fixed', top: '24px', left: '50%', zIndex: 9999,
              padding: '14px 24px', borderRadius: '12px', display: 'flex', alignItems: 'center', gap: '10px',
              background: toast.type === 'success' ? '#ECFDF5' : '#FEF2F2',
              border: `1px solid ${toast.type === 'success' ? '#10B981' : '#EF4444'}`,
              color: toast.type === 'success' ? '#065F46' : '#991B1B',
              fontWeight: 600, fontSize: '0.875rem',
              boxShadow: '0 8px 32px rgba(0,0,0,0.1)',
            }}
          >
            {toast.type === 'success' ? <CheckCircle size={18} /> : <AlertCircle size={18} />}
            {toast.message}
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {showModal && (
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            style={{ position: 'fixed', inset: 0, background: 'rgba(15, 23, 42, 0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}
            onClick={(e) => { if (e.target === e.currentTarget) setShowModal(false); }}
          >
            <motion.div
              initial={{ scale: 0.92, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.92, opacity: 0 }}
              style={{ background: '#FFFFFF', borderRadius: '20px', padding: '32px', width: '560px', maxWidth: '95vw', boxShadow: '0 20px 50px rgba(0,0,0,0.1)' }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '28px' }}>
                <div>
                  <h2 style={{ fontSize: '1.4rem', fontWeight: 900, color: '#0F172A', margin: 0 }}>Register New Vehicle</h2>
                  <p style={{ fontSize: '0.8rem', color: '#64748B', margin: '4px 0 0' }}>Add an ambulance to your fleet</p>
                </div>
                <button onClick={() => setShowModal(false)} style={{ background: '#F1F5F9', border: 'none', borderRadius: '8px', padding: '8px', color: '#475569', cursor: 'pointer' }}>
                  <X size={18} />
                </button>
              </div>

              <form onSubmit={handleSubmit}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Registration Number *</label>
                      <input style={inputStyle} required value={form.registration_number} onChange={e => setForm(f => ({ ...f, registration_number: e.target.value }))} />
                    </div>
                    <div style={{ position: 'relative' }}>
                      <label style={labelStyle}>Assign to Station *</label>
                      <select style={selectStyle} required value={form.station_id} onChange={e => setForm(f => ({ ...f, station_id: e.target.value }))}>
                        <option value="">— Select a Station —</option>
                        {stations.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                      </select>
                      <ChevronDown size={16} color="#64748B" style={{ position: 'absolute', right: '14px', bottom: '13px', pointerEvents: 'none' }} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div style={{ position: 'relative' }}>
                      <label style={labelStyle}>Vehicle Type *</label>
                      <select style={selectStyle} required value={form.vehicle_type} onChange={e => setForm(f => ({ ...f, vehicle_type: e.target.value }))}>
                        {VEHICLE_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                      </select>
                      <ChevronDown size={16} color="#64748B" style={{ position: 'absolute', right: '14px', bottom: '13px', pointerEvents: 'none' }} />
                    </div>
                    <div style={{ position: 'relative' }}>
                      <label style={labelStyle}>Ownership Type</label>
                      <select style={selectStyle} value={form.ownership_type} onChange={e => setForm(f => ({ ...f, ownership_type: e.target.value }))}>
                        {OWNERSHIP_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                      </select>
                      <ChevronDown size={16} color="#64748B" style={{ position: 'absolute', right: '14px', bottom: '13px', pointerEvents: 'none' }} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Brand *</label>
                      <input style={inputStyle} required value={form.brand} onChange={e => setForm(f => ({ ...f, brand: e.target.value }))} />
                    </div>
                    <div>
                      <label style={labelStyle}>Model *</label>
                      <input style={inputStyle} required value={form.model} onChange={e => setForm(f => ({ ...f, model: e.target.value }))} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Make Year</label>
                      <input type="number" style={inputStyle} value={form.make_year} onChange={e => setForm(f => ({ ...f, make_year: e.target.value ? Number(e.target.value) : '' }))} />
                    </div>
                    <div>
                      <label style={labelStyle}>Patient Capacity</label>
                      <input type="number" style={inputStyle} value={form.stretcher_capacity} onChange={e => setForm(f => ({ ...f, stretcher_capacity: e.target.value ? Number(e.target.value) : '' }))} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Chassis Number</label>
                      <input style={{ ...inputStyle, fontFamily: 'monospace' }} value={form.chassis_number} onChange={e => setForm(f => ({ ...f, chassis_number: e.target.value }))} />
                    </div>
                    <div>
                      <label style={labelStyle}>Engine Number</label>
                      <input style={{ ...inputStyle, fontFamily: 'monospace' }} value={form.engine_number} onChange={e => setForm(f => ({ ...f, engine_number: e.target.value }))} />
                    </div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '12px', marginTop: '28px' }}>
                  <button type="button" onClick={() => setShowModal(false)} style={{ flex: 1, padding: '13px', background: '#F1F5F9', border: 'none', borderRadius: '12px', color: '#475569', cursor: 'pointer', fontWeight: 600 }}>Cancel</button>
                  <button type="submit" disabled={submitting} style={{ flex: 2, padding: '13px', background: '#0F172A', border: 'none', borderRadius: '12px', color: '#fff', cursor: 'pointer', fontWeight: 700 }}>{submitting ? 'Registering...' : 'REGISTER VEHICLE'}</button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {showEditModal && editingVehicle && (
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            style={{ position: 'fixed', inset: 0, background: 'rgba(15, 23, 42, 0.5)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}
            onClick={(e) => { if (e.target === e.currentTarget) setShowEditModal(false); }}
          >
            <motion.div
              initial={{ scale: 0.92, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.92, opacity: 0 }}
              style={{ background: '#FFFFFF', borderRadius: '20px', padding: '32px', width: '560px', maxWidth: '95vw', boxShadow: '0 20px 50px rgba(0,0,0,0.1)' }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '28px' }}>
                <div>
                  <h2 style={{ fontSize: '1.4rem', fontWeight: 900, color: '#0F172A', margin: 0 }}>Edit Vehicle</h2>
                  <p style={{ fontSize: '0.8rem', color: '#64748B', margin: '4px 0 0' }}>Update details for {editingVehicle.registration_number}</p>
                </div>
                <button onClick={() => setShowEditModal(false)} style={{ background: '#F1F5F9', border: 'none', borderRadius: '8px', padding: '8px', color: '#475569', cursor: 'pointer' }}>
                  <X size={18} />
                </button>
              </div>

              <form onSubmit={handleUpdate}>
                <div style={{ display: 'flex', flexDirection: 'column', gap: '18px' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Registration Number *</label>
                      <input style={inputStyle} required value={editForm.registration_number} onChange={e => setEditForm(f => ({ ...f, registration_number: e.target.value }))} />
                    </div>
                    <div style={{ position: 'relative' }}>
                      <label style={labelStyle}>Assign to Station</label>
                      <select style={selectStyle} value={editForm.station_id} onChange={e => setEditForm(f => ({ ...f, station_id: e.target.value }))}>
                        <option value="">— Select a Station —</option>
                        {stations.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                      </select>
                      <ChevronDown size={16} color="#64748B" style={{ position: 'absolute', right: '14px', bottom: '13px', pointerEvents: 'none' }} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div style={{ position: 'relative' }}>
                      <label style={labelStyle}>Vehicle Type *</label>
                      <select style={selectStyle} required value={editForm.vehicle_type} onChange={e => setEditForm(f => ({ ...f, vehicle_type: e.target.value }))}>
                        {VEHICLE_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                      </select>
                      <ChevronDown size={16} color="#64748B" style={{ position: 'absolute', right: '14px', bottom: '13px', pointerEvents: 'none' }} />
                    </div>
                    <div style={{ position: 'relative' }}>
                      <label style={labelStyle}>Ownership Type</label>
                      <select style={selectStyle} value={editForm.ownership_type} onChange={e => setEditForm(f => ({ ...f, ownership_type: e.target.value }))}>
                        {OWNERSHIP_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                      </select>
                      <ChevronDown size={16} color="#64748B" style={{ position: 'absolute', right: '14px', bottom: '13px', pointerEvents: 'none' }} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Brand *</label>
                      <input style={inputStyle} required value={editForm.brand} onChange={e => setEditForm(f => ({ ...f, brand: e.target.value }))} />
                    </div>
                    <div>
                      <label style={labelStyle}>Model *</label>
                      <input style={inputStyle} required value={editForm.model} onChange={e => setEditForm(f => ({ ...f, model: e.target.value }))} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Make Year</label>
                      <input type="number" style={inputStyle} value={editForm.make_year} onChange={e => setEditForm(f => ({ ...f, make_year: e.target.value ? Number(e.target.value) : '' }))} />
                    </div>
                    <div>
                      <label style={labelStyle}>Patient Capacity</label>
                      <input type="number" style={inputStyle} value={editForm.stretcher_capacity} onChange={e => setEditForm(f => ({ ...f, stretcher_capacity: e.target.value ? Number(e.target.value) : '' }))} />
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
                    <div>
                      <label style={labelStyle}>Chassis Number</label>
                      <input style={{ ...inputStyle, fontFamily: 'monospace' }} value={editForm.chassis_number} onChange={e => setEditForm(f => ({ ...f, chassis_number: e.target.value }))} />
                    </div>
                    <div>
                      <label style={labelStyle}>Engine Number</label>
                      <input style={{ ...inputStyle, fontFamily: 'monospace' }} value={editForm.engine_number} onChange={e => setEditForm(f => ({ ...f, engine_number: e.target.value }))} />
                    </div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '12px', marginTop: '28px' }}>
                  <button type="button" onClick={() => setShowEditModal(false)} style={{ flex: 1, padding: '13px', background: '#F1F5F9', border: 'none', borderRadius: '12px', color: '#475569', cursor: 'pointer', fontWeight: 600 }}>Cancel</button>
                  <button type="submit" disabled={submitting} style={{ flex: 2, padding: '13px', background: '#0F172A', border: 'none', borderRadius: '12px', color: '#fff', cursor: 'pointer', fontWeight: 700 }}>{submitting ? 'Updating...' : 'UPDATE VEHICLE'}</button>
                </div>
              </form>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px', flexWrap: 'wrap', gap: '16px' }}>
        <div style={{ display: 'flex', gap: '12px', alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{
            display: 'flex',
            alignItems: 'center',
            gap: '10px',
            background: '#FFFFFF',
            padding: '10px 16px',
            borderRadius: '12px',
            border: isSearchFocused ? '1px solid #06B6D4' : '1px solid #CBD5E1',
            boxShadow: isSearchFocused ? '0 0 0 3px rgba(6, 182, 212, 0.15)' : '0 2px 4px rgba(15, 23, 42, 0.01)',
            transition: 'all 0.2s ease',
            width: '280px',
            position: 'relative'
          }}>
            <Search size={16} color={isSearchFocused ? "#06B6D4" : "#64748B"} style={{ transition: 'color 0.2s' }} />
            <input
              type="text"
              placeholder="Search vehicles..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onFocus={() => setIsSearchFocused(true)}
              onBlur={() => setIsSearchFocused(false)}
              className="stations-search-input"
              style={{ 
                background: 'transparent', 
                border: 'none', 
                color: '#0F172A', 
                fontSize: '0.875rem', 
                outline: 'none', 
                width: '100%',
                paddingRight: searchQuery ? '24px' : '0'
              }}
            />
            {searchQuery && (
              <button 
                onClick={() => setSearchQuery('')}
                style={{
                  position: 'absolute',
                  right: '12px',
                  background: 'transparent',
                  border: 'none',
                  cursor: 'pointer',
                  color: '#94A3B8',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  padding: '2px',
                  borderRadius: '50%',
                }}
                onMouseEnter={e => e.currentTarget.style.color = '#475569'}
                onMouseLeave={e => e.currentTarget.style.color = '#94A3B8'}
              >
                <X size={14} />
              </button>
            )}
          </div>

          <div style={{ position: 'relative', display: 'inline-block' }}>
            <select
              value={selectedStationFilter}
              onChange={(e) => setSelectedStationFilter(e.target.value)}
              style={{
                background: '#FFFFFF',
                border: '1px solid #CBD5E1',
                padding: '11px 36px 11px 16px',
                borderRadius: '12px',
                color: '#0F172A',
                fontSize: '0.875rem',
                outline: 'none',
                cursor: 'pointer',
                appearance: 'none',
                WebkitAppearance: 'none',
                minWidth: '200px',
                boxShadow: '0 2px 4px rgba(15, 23, 42, 0.01)',
              }}
            >
              <option value="">📁 All Stations</option>
              {stations.map(s => (
                <option key={s.id} value={s.name}>📍 {s.name}</option>
              ))}
            </select>
            <ChevronDown 
              size={16} 
              color="#64748B" 
              style={{
                position: 'absolute',
                right: '12px',
                top: '50%',
                transform: 'translateY(-50%)',
                pointerEvents: 'none'
              }}
            />
          </div>
        </div>

        <button
          onClick={openModal}
          style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '11px 22px', background: '#0F172A', border: 'none', borderRadius: '12px', color: '#fff', fontWeight: 700, cursor: 'pointer', fontSize: '0.875rem' }}
        >
          <Plus size={18} /> REGISTER NEW VEHICLE
        </button>
      </div>

      {loading && (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '200px', color: '#64748B' }}>
          <Loader2 size={24} className="spin" />
        </div>
      )}

      {!loading && vehicles.length === 0 && (
        <div style={{ textAlign: 'center', padding: '60px 24px', color: '#64748B' }}>
          <Truck size={48} style={{ opacity: 0.2, marginBottom: '16px' }} />
          <h3 style={{ fontSize: '1.1rem', fontWeight: 700, color: '#475569', marginBottom: '8px' }}>No Vehicles Found</h3>
        </div>
      )}

      {!loading && vehicles.length > 0 && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: '20px' }}>
          {vehicles.map(v => {
            const sc = getStatusColor(v.status);
            return (
              <motion.div
                key={v.id}
                initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}
                style={{ ...cardStyle, borderLeft: `4px solid ${sc.color}` }}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '16px' }}>
                  <div>
                    <div style={{ fontSize: '0.65rem', fontWeight: 900, color: '#64748B', marginBottom: '4px' }}>{v.vehicle_type} UNIT</div>
                    <h3 style={{ fontSize: '1rem', fontWeight: 800, color: '#0F172A', margin: 0 }}>{v.registration_number}</h3>
                    <div style={{ fontSize: '0.78rem', color: '#475569', marginTop: '4px' }}>{v.brand} {v.model} {v.make_year ? `(${v.make_year})` : ''}</div>
                  </div>
                  <div style={{ padding: '4px 10px', borderRadius: '6px', fontSize: '0.65rem', fontWeight: 900, background: sc.bg, color: sc.color }}>{v.status}</div>
                </div>
                <div style={{ fontSize: '0.7rem', color: '#64748B', display: 'flex', gap: '12px', marginBottom: '16px' }}>
                  {v.ownership_type && <span>Ownership: <strong>{v.ownership_type}</strong></span>}
                  {v.stretcher_capacity ? <span>Capacity: <strong>{v.stretcher_capacity} Pts</strong></span> : null}
                </div>
                <button
                  onClick={() => openEditModal(v)}
                  style={{ width: '100%', padding: '9px', background: '#F1F5F9', border: 'none', borderRadius: '8px', color: '#0F172A', fontSize: '0.75rem', fontWeight: 700, cursor: 'pointer' }}
                >
                  EDIT DETAILS
                </button>
              </motion.div>
            );
          })}
        </div>
      )}

      <style>{`@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } .spin { animation: spin 1s linear infinite; }`}</style>
    </div>
  );
};
