'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import {
  Battery, Plus, Search, Filter, X, Download, Upload, MoreHorizontal,
  BatteryCharging, BatteryWarning, BatteryFull, Zap, Thermometer,
  Activity, Clock, MapPin, Bike, User, History, TrendingUp, DollarSign, Handshake,
  Eye, Edit, Trash2, RefreshCw, CheckCircle, AlertTriangle, ChevronRight,
  ArrowUpDown, Calendar, Gauge, Timer
} from 'lucide-react';

interface BMSData {
  voltage: number;
  current: number;
  soc: number;
  temperature: number;
  cycles: number;
  health: number;
  timestamp: string;
}

interface BatteryHistory {
  id: string;
  batteryId: string;
  bikeId?: string;
  bikeModel?: string;
  bikerId?: string;
  bikerName?: string;
  stationId?: string;
  stationName?: string;
  action: 'assigned' | 'swapped' | 'maintenance' | 'retired';
  timestamp: string;
  notes?: string;
}

interface Battery {
  id: string;
  serialNumber: string;
  brand: string;
  model: string;
  type: 'lithium-ion' | 'lifepo4' | 'lead-acid';
  capacity: number;
  voltage: number;
  purchaseDate: string;
  purchasePrice: number;
  transactionMethod?: 'cash' | 'bank_transfer' | 'mobile_banking' | 'cheque' | 'credit' | 'other';
  autoJournal?: boolean;
  autoJournalSource?: 'supplier' | 'import' | 'internal' | 'transfer' | 'other';
  warrantyExpiry: string;
  status: 'available' | 'in-use' | 'maintenance' | 'retired' | 'charging';
  currentSoc: number;
  health: number;
  cycleCount: number;
  assignedBikeId?: string;
  assignedBikeModel?: string;
  assignedBikerId?: string;
  assignedBikerName?: string;
  currentStationId?: string;
  currentStationName?: string;
  hubId?: string;
  hubName?: string;
  lastMaintenance?: string;
  nextMaintenance?: string;
  bmsData?: BMSData;
  deposit?: number;
  rentPrice?: number;
  investorId?: string;
  investorName?: string;
  investorSharePercentage?: number;
  investedAmount?: number;
  history: BatteryHistory[];
}

interface Bike {
  id: string;
  model: string;
  brand: string;
  plateNumber: string;
  status: 'available' | 'rented' | 'maintenance' | 'retired';
}

interface Biker {
  id: string;
  name: string;
  phone: string;
  stationId?: string;
  stationName?: string;
}

interface SwapStation {
  id: string;
  name: string;
  location: string;
}

const mockBatteries: Battery[] = [
  {
    id: 'BAT-001',
    serialNumber: 'SN-2024-00001',
    brand: 'EVE Energy',
    model: 'Li-Ion 60V50Ah',
    type: 'lithium-ion',
    capacity: 50,
    voltage: 60,
    purchaseDate: '2024-01-15',
    purchasePrice: 45000,
    deposit: 5000,
    rentPrice: 150,
    investorId: 'INV-001',
    investorName: 'Tahmid Rahman',
    investorSharePercentage: 60,
    investedAmount: 45000,
    warrantyExpiry: '2027-01-15',
    status: 'in-use',
    currentSoc: 78,
    health: 95,
    cycleCount: 156,
    assignedBikeId: 'EV001',
    assignedBikeModel: 'Etron ET50',
    assignedBikerId: 'BK-001',
    assignedBikerName: 'Rahim Ahmed',
    currentStationId: 'SS-001',
    currentStationName: 'Banani Swap Station',
    lastMaintenance: '2024-03-01',
    nextMaintenance: '2024-06-01',
    history: [
      { id: 'H1', batteryId: 'BAT-001', bikeId: 'EV001', bikeModel: 'Etron ET50', bikerId: 'BK-001', bikerName: 'Rahim Ahmed', stationId: 'SS-001', stationName: 'Banani Swap Station', action: 'assigned', timestamp: '2024-03-15 08:30:00' },
      { id: 'H2', batteryId: 'BAT-001', stationId: 'SS-002', stationName: 'Gulshan Swap Station', action: 'swapped', timestamp: '2024-03-20 14:22:00' },
      { id: 'H3', batteryId: 'BAT-001', stationId: 'SS-001', stationName: 'Banani Swap Station', action: 'swapped', timestamp: '2024-03-25 10:15:00' },
    ],
    bmsData: { voltage: 67.2, current: -2.5, soc: 78, temperature: 32, cycles: 156, health: 95, timestamp: '2024-03-28 12:00:00' }
  },
  {
    id: 'BAT-002',
    serialNumber: 'SN-2024-00002',
    brand: 'CATL',
    model: 'LiFePO4 48V40Ah',
    type: 'lifepo4',
    capacity: 40,
    voltage: 48,
    purchaseDate: '2024-02-01',
    purchasePrice: 38000,
    deposit: 4000,
    rentPrice: 120,
    warrantyExpiry: '2027-02-01',
    status: 'available',
    currentSoc: 100,
    health: 98,
    cycleCount: 45,
    lastMaintenance: '2024-03-15',
    nextMaintenance: '2024-06-15',
    history: [
      { id: 'H4', batteryId: 'BAT-002', action: 'retired', timestamp: '2024-03-10 09:00:00', notes: 'Retired from active service' },
    ]
  },
  {
    id: 'BAT-003',
    serialNumber: 'SN-2024-00003',
    brand: 'Panasonic',
    model: 'Li-Ion 60V45Ah',
    type: 'lithium-ion',
    capacity: 45,
    voltage: 60,
    purchaseDate: '2024-01-20',
    purchasePrice: 42000,
    deposit: 4500,
    rentPrice: 130,
    warrantyExpiry: '2027-01-20',
    status: 'maintenance',
    currentSoc: 15,
    health: 72,
    cycleCount: 234,
    lastMaintenance: '2024-03-28',
    nextMaintenance: '2024-04-01',
    history: [
      { id: 'H5', batteryId: 'BAT-003', bikeId: 'EV003', bikeModel: 'AIMA Lightning', bikerId: 'BK-002', bikerName: 'Karim Singh', stationId: 'SS-003', stationName: 'Uttara Swap Station', action: 'assigned', timestamp: '2024-02-10 11:00:00' },
      { id: 'H6', batteryId: 'BAT-003', action: 'maintenance', timestamp: '2024-03-28 16:00:00', notes: 'Battery degradation - needs replacement' },
    ]
  },
  {
    id: 'BAT-004',
    serialNumber: 'SN-2024-00004',
    brand: 'LG Chem',
    model: 'Li-Ion 60V50Ah',
    type: 'lithium-ion',
    capacity: 50,
    voltage: 60,
    purchaseDate: '2024-02-15',
    purchasePrice: 46000,
    deposit: 5000,
    rentPrice: 150,
    warrantyExpiry: '2027-02-15',
    status: 'in-use',
    currentSoc: 92,
    health: 96,
    cycleCount: 89,
    assignedBikeId: 'EV006',
    assignedBikeModel: 'Hero Eddy',
    assignedBikerId: 'BK-003',
    assignedBikerName: 'Mahir Khan',
    currentStationId: 'SS-002',
    currentStationName: 'Gulshan Swap Station',
    lastMaintenance: '2024-03-05',
    nextMaintenance: '2024-06-05',
    history: [
      { id: 'H7', batteryId: 'BAT-004', bikeId: 'EV006', bikeModel: 'Hero Eddy', bikerId: 'BK-003', bikerName: 'Mahir Khan', stationId: 'SS-002', stationName: 'Gulshan Swap Station', action: 'assigned', timestamp: '2024-03-05 07:45:00' },
    ],
    bmsData: { voltage: 68.4, current: -1.2, soc: 92, temperature: 28, cycles: 89, health: 96, timestamp: '2024-03-28 12:00:00' }
  },
  {
    id: 'BAT-005',
    serialNumber: 'SN-2024-00005',
    brand: 'Samsung SDI',
    model: 'Li-Ion 60V55Ah',
    type: 'lithium-ion',
    capacity: 55,
    voltage: 60,
    purchaseDate: '2024-03-01',
    purchasePrice: 50000,
    deposit: 5500,
    rentPrice: 160,
    warrantyExpiry: '2027-03-01',
    status: 'charging',
    currentSoc: 85,
    health: 99,
    cycleCount: 12,
    currentStationId: 'SS-001',
    currentStationName: 'Banani Swap Station',
    lastMaintenance: '2024-03-20',
    nextMaintenance: '2024-06-20',
    history: []
  },
  {
    id: 'BAT-006',
    serialNumber: 'SN-2023-00089',
    brand: 'BYD',
    model: 'LiFePO4 48V30Ah',
    type: 'lifepo4',
    capacity: 30,
    voltage: 48,
    purchaseDate: '2023-06-15',
    purchasePrice: 28000,
    deposit: 3000,
    rentPrice: 90,
    warrantyExpiry: '2026-06-15',
    status: 'retired',
    currentSoc: 0,
    health: 45,
    cycleCount: 450,
    lastMaintenance: '2024-01-10',
    history: [
      { id: 'H8', batteryId: 'BAT-006', bikeId: 'EV009', bikeModel: 'JME Victory', action: 'retired', timestamp: '2024-01-10 10:00:00', notes: 'Health below 50% - retired' },
    ]
  },
];

const mockBikes: Bike[] = [
  { id: 'EV001', model: 'Etron ET50', brand: 'Etron', plateNumber: 'Dhaka Metro Cha-A-1234', status: 'rented' },
  { id: 'EV002', model: 'Yadea DT3', brand: 'Yadea', plateNumber: 'Dhaka Metro Cha-A-5678', status: 'available' },
  { id: 'EV003', model: 'AIMA Lightning', brand: 'AIMA', plateNumber: 'Dhaka Metro Cha-A-9012', status: 'rented' },
  { id: 'EV006', model: 'Hero Eddy', brand: 'Hero', plateNumber: 'Dhaka Metro Cha-B-1122', status: 'rented' },
  { id: 'EV010', model: 'Benling Aura', brand: 'Benling', plateNumber: 'Dhaka Metro Cha-C-9900', status: 'rented' },
];

const mockBikers: Biker[] = [
  { id: 'BK-001', name: 'Rahim Ahmed', phone: '01712345678', stationId: 'SS-001', stationName: 'Banani Swap Station' },
  { id: 'BK-002', name: 'Karim Singh', phone: '01712345679', stationId: 'SS-003', stationName: 'Uttara Swap Station' },
  { id: 'BK-003', name: 'Mahir Khan', phone: '01712345680', stationId: 'SS-002', stationName: 'Gulshan Swap Station' },
  { id: 'BK-004', name: 'Ovi Rahman', phone: '01712345681', stationId: 'SS-001', stationName: 'Banani Swap Station' },
];

const mockStations: SwapStation[] = [
  { id: 'SS-001', name: 'Banani Swap Station', location: 'Block A, Road 3, Banani' },
  { id: 'SS-002', name: 'Gulshan Swap Station', location: 'Circle, Gulshan 2' },
  { id: 'SS-003', name: 'Uttara Swap Station', location: 'Sector 11, Uttara' },
  { id: 'SS-004', name: 'Dhanmondi Swap Station', location: 'Jashore Road, Dhanmondi' },
  { id: 'SS-005', name: 'Mirpur Swap Station', location: 'Mirpur 1, Section 2' },
];

const hubs = [
  { id: 'HUB-001', name: 'JAIBEN Head Office' },
  { id: 'HUB-002', name: 'Banani Hub' },
  { id: 'HUB-003', name: 'Uttara Hub' },
  { id: 'HUB-004', name: 'Mirpur Hub' },
];

const statusColors: Record<string, string> = {
  available: 'bg-green-100 text-green-700',
  'in-use': 'bg-blue-100 text-blue-700',
  maintenance: 'bg-amber-100 text-amber-700',
  retired: 'bg-slate-100 text-slate-500',
  charging: 'bg-purple-100 text-purple-700',
};

const typeLabels: Record<string, string> = {
  'lithium-ion': 'Lithium-Ion',
  'lifepo4': 'LiFePO4',
  'lead-acid': 'Lead Acid',
};

export default function BatteriesPage() {
  const [batteries, setBatteries] = useState<Battery[]>(mockBatteries);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [typeFilter, setTypeFilter] = useState('all');
  const [selectedBattery, setSelectedBattery] = useState<Battery | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [showHistoryModal, setShowHistoryModal] = useState(false);
  const [showBMSModal, setShowBMSModal] = useState(false);
  const [editingBattery, setEditingBattery] = useState<Battery | null>(null);
  const [viewMode, setViewMode] = useState<'table' | 'cards'>('table');

  const availableCount = batteries.filter(b => b.status === 'available').length;
  const inUseCount = batteries.filter(b => b.status === 'in-use').length;
  const maintenanceCount = batteries.filter(b => b.status === 'maintenance').length;
  const chargingCount = batteries.filter(b => b.status === 'charging').length;
  const totalValue = batteries.reduce((sum, b) => sum + b.purchasePrice, 0);

  const filteredBatteries = batteries.filter(battery => {
    const matchesSearch = battery.serialNumber.toLowerCase().includes(searchQuery.toLowerCase()) ||
      battery.brand.toLowerCase().includes(searchQuery.toLowerCase()) ||
      battery.model.toLowerCase().includes(searchQuery.toLowerCase()) ||
      battery.id.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = statusFilter === 'all' || battery.status === statusFilter;
    const matchesType = typeFilter === 'all' || battery.type === typeFilter;
    return matchesSearch && matchesStatus && matchesType;
  });

  const handleAddBattery = () => {
    setEditingBattery(null);
    setShowModal(true);
  };

  const handleEditBattery = (battery: Battery) => {
    setEditingBattery(battery);
    setShowModal(true);
  };

  const handleViewDetails = (battery: Battery) => {
    setSelectedBattery(battery);
    setShowDetailsModal(true);
  };

  const handleViewHistory = (battery: Battery) => {
    setSelectedBattery(battery);
    setShowHistoryModal(true);
  };

  const handleReceiveBMSData = (battery: Battery) => {
    setSelectedBattery(battery);
    setShowBMSModal(true);
  };

  const handleDeleteBattery = (id: string) => {
    if (confirm('Are you sure you want to delete this battery?')) {
      setBatteries(batteries.filter(b => b.id !== id));
    }
  };

  const handleSaveBattery = (battery: Battery) => {
    if (editingBattery) {
      setBatteries(batteries.map(b => b.id === editingBattery.id ? battery : b));
    } else {
      const newId = `BAT-${String(batteries.length + 1).padStart(3, '0')}`;
      setBatteries([...batteries, { ...battery, id: newId, history: [] }]);
    }
    setShowModal(false);
  };

  const handleAssignToBike = (batteryId: string, bikeId: string, bikerId: string, stationId: string) => {
    const bike = mockBikes.find(b => b.id === bikeId);
    const biker = mockBikers.find(b => b.id === bikerId);
    const station = mockStations.find(s => s.id === stationId);

    const newHistory: BatteryHistory = {
      id: `H-${Date.now()}`,
      batteryId,
      bikeId,
      bikeModel: bike?.model,
      bikerId,
      bikerName: biker?.name,
      stationId,
      stationName: station?.name,
      action: 'assigned',
      timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
    };

    setBatteries(batteries.map(b => {
      if (b.id === batteryId) {
        return {
          ...b,
          status: 'in-use',
          assignedBikeId: bikeId,
          assignedBikeModel: bike?.model,
          assignedBikerId: bikerId,
          assignedBikerName: biker?.name,
          currentStationId: stationId,
          currentStationName: station?.name,
          history: [newHistory, ...b.history],
        };
      }
      return b;
    }));
    setShowDetailsModal(false);
  };

  return (
    <div className="p-4 lg:p-6">
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl lg:text-3xl font-extrabold text-slate-800">Battery Management</h1>
          <p className="text-sm text-slate-500 mt-1">Manage battery inventory, track BMS data, and assignment history</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowBMSModal(true)}
            className="py-2.5 px-4 border border-slate-200 text-slate-700 bg-white rounded-lg font-semibold text-sm hover:bg-slate-50 transition-colors flex items-center gap-2"
          >
            <RefreshCw className="w-4 h-4" /> Receive BMS Data
          </button>
          <button onClick={handleAddBattery} className="py-2.5 px-4 bg-accent text-white rounded-lg font-semibold text-sm hover:bg-accent-dark transition-colors flex items-center gap-2">
            <Plus className="w-4 h-4" /> Register New Battery
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-green-50 flex items-center justify-center">
              <BatteryFull className="w-6 h-6 text-green-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{availableCount}</p>
              <p className="text-sm text-slate-500">Available</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-blue-50 flex items-center justify-center">
              <Battery className="w-6 h-6 text-blue-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{inUseCount}</p>
              <p className="text-sm text-slate-500">In Use</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-purple-50 flex items-center justify-center">
              <BatteryCharging className="w-6 h-6 text-purple-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{chargingCount}</p>
              <p className="text-sm text-slate-500">Charging</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-amber-50 flex items-center justify-center">
              <Wrench className="w-6 h-6 text-amber-600" />
            </div>
            <div>
              <p className="text-2xl font-extrabold text-slate-800">{maintenanceCount}</p>
              <p className="text-sm text-slate-500">Maintenance</p>
            </div>
          </div>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 rounded-xl bg-slate-100 flex items-center justify-center">
              <DollarSign className="w-6 h-6 text-slate-600" />
            </div>
            <div>
              <p className="text-lg font-extrabold text-slate-800">৳{totalValue.toLocaleString()}</p>
              <p className="text-sm text-slate-500">Total Value</p>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100">
        <div className="p-4 border-b border-slate-100 flex flex-col lg:flex-row lg:items-center gap-3">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
            <input
              type="text"
              placeholder="Search by serial, brand, model, ID..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
            />
          </div>
          <div className="flex items-center gap-2 flex-wrap">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="py-2 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 bg-white"
            >
              <option value="all">All Status</option>
              <option value="available">Available</option>
              <option value="in-use">In Use</option>
              <option value="charging">Charging</option>
              <option value="maintenance">Maintenance</option>
              <option value="retired">Retired</option>
            </select>
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="py-2 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 bg-white"
            >
              <option value="all">All Types</option>
              <option value="lithium-ion">Lithium-Ion</option>
              <option value="lifepo4">LiFePO4</option>
              <option value="lead-acid">Lead Acid</option>
            </select>
            <div className="flex items-center bg-slate-100 p-1 rounded-lg">
              <button
                onClick={() => setViewMode('table')}
                className={`py-1.5 px-3 rounded-md text-sm font-medium transition-all flex items-center gap-2 ${viewMode === 'table' ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
              >
                <Activity className="w-4 h-4" /> Table
              </button>
              <button
                onClick={() => setViewMode('cards')}
                className={`py-1.5 px-3 rounded-md text-sm font-medium transition-all flex items-center gap-2 ${viewMode === 'cards' ? 'bg-white text-slate-800 shadow-sm' : 'text-slate-500 hover:text-slate-700'}`}
              >
                <Gauge className="w-4 h-4" /> Cards
              </button>
            </div>
            <button className="py-2 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50 flex items-center gap-2">
              <Download className="w-4 h-4" /> Export
            </button>
          </div>
        </div>

        {viewMode === 'table' ? (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-slate-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Battery</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Specs</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Current Status</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Assignment</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Health</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Price</th>
                  <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {filteredBatteries.map(battery => (
                  <tr key={battery.id} className="hover:bg-slate-50 transition-colors">
                    <td className="px-4 py-3">
                      <Link href={`/admin/batteries/${battery.id}`} className="flex items-center gap-3 hover:bg-slate-50 -m-2 p-2 rounded-lg">
                        <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${battery.type === 'lithium-ion' ? 'bg-blue-50' : battery.type === 'lifepo4' ? 'bg-green-50' : 'bg-amber-50'}`}>
                          <Battery className={`w-5 h-5 ${battery.type === 'lithium-ion' ? 'text-blue-600' : battery.type === 'lifepo4' ? 'text-green-600' : 'text-amber-600'}`} />
                        </div>
                        <div>
                          <p className="text-sm font-medium text-slate-700">{battery.brand} {battery.model}</p>
                          <p className="text-xs text-slate-400">{battery.serialNumber}</p>
                        </div>
                      </Link>
                    </td>
                    <td className="px-4 py-3">
                      <p className="text-xs text-slate-600">{battery.capacity}Ah / {battery.voltage}V</p>
                      <p className="text-xs text-slate-400">{typeLabels[battery.type]}</p>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${statusColors[battery.status]}`}>
                          {battery.status === 'in-use' ? <Activity className="w-3 h-3" /> : battery.status === 'charging' ? <BatteryCharging className="w-3 h-3" /> : null}
                          {battery.status}
                        </span>
                        <span className={`text-sm font-medium ${battery.currentSoc > 50 ? 'text-green-600' : battery.currentSoc > 20 ? 'text-amber-600' : 'text-red-600'}`}>
                          {battery.currentSoc}%
                        </span>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      {battery.assignedBikeId ? (
                        <div className="text-xs">
                          <p className="font-medium text-slate-700 flex items-center gap-1">
                            <Bike className="w-3 h-3" /> {battery.assignedBikeModel}
                          </p>
                          <p className="text-slate-400 flex items-center gap-1">
                            <User className="w-3 h-3" /> {battery.assignedBikerName}
                          </p>
                          <p className="text-slate-400 flex items-center gap-1">
                            <MapPin className="w-3 h-3" /> {battery.currentStationName}
                          </p>
                        </div>
                      ) : battery.currentStationName ? (
                        <p className="text-xs text-slate-500 flex items-center gap-1">
                          <Zap className="w-3 h-3" /> {battery.currentStationName}
                        </p>
                      ) : (
                        <span className="text-xs text-slate-400">Unassigned</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <div className="w-16 h-2 bg-slate-100 rounded-full overflow-hidden">
                          <div
                            className={`h-full rounded-full ${battery.health > 80 ? 'bg-green-500' : battery.health > 60 ? 'bg-amber-500' : 'bg-red-500'}`}
                            style={{ width: `${battery.health}%` }}
                          />
                        </div>
                        <span className={`text-xs font-medium ${battery.health > 80 ? 'text-green-600' : battery.health > 60 ? 'text-amber-600' : 'text-red-600'}`}>
                          {battery.health}%
                        </span>
                      </div>
                      <p className="text-xs text-slate-400">{battery.cycleCount} cycles</p>
                    </td>
                    <td className="px-4 py-3">
                      <span className="text-sm font-medium text-slate-700">৳{battery.purchasePrice.toLocaleString()}</span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1">
                        <Link href={`/admin/batteries/${battery.id}`} className="p-2 hover:bg-slate-100 rounded-lg inline-flex items-center" title="View Details">
                          <Eye className="w-4 h-4 text-blue-500" />
                        </Link>
                        <button onClick={() => handleViewHistory(battery)} className="p-2 hover:bg-slate-100 rounded-lg" title="History">
                          <History className="w-4 h-4 text-purple-500" />
                        </button>
                        {battery.bmsData && (
                          <button onClick={() => handleReceiveBMSData(battery)} className="p-2 hover:bg-slate-100 rounded-lg" title="BMS Data">
                            <Activity className="w-4 h-4 text-green-500" />
                          </button>
                        )}
                        <button onClick={() => handleEditBattery(battery)} className="p-2 hover:bg-slate-100 rounded-lg" title="Edit">
                          <Edit className="w-4 h-4 text-slate-400" />
                        </button>
                        <button onClick={() => handleDeleteBattery(battery.id)} className="p-2 hover:bg-red-50 rounded-lg" title="Delete">
                          <Trash2 className="w-4 h-4 text-red-400" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4">
            {filteredBatteries.map(battery => (
              <Link key={battery.id} href={`/admin/batteries/${battery.id}`} className="block bg-slate-50 rounded-xl p-4 hover:shadow-md transition-shadow">
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center gap-3">
                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center ${battery.type === 'lithium-ion' ? 'bg-blue-50' : battery.type === 'lifepo4' ? 'bg-green-50' : 'bg-amber-50'}`}>
                      <Battery className={`w-6 h-6 ${battery.type === 'lithium-ion' ? 'text-blue-600' : battery.type === 'lifepo4' ? 'text-green-600' : 'text-amber-600'}`} />
                    </div>
                    <div>
                      <p className="font-semibold text-slate-700">{battery.brand} {battery.model}</p>
                      <p className="text-xs text-slate-400">{battery.serialNumber}</p>
                    </div>
                  </div>
                  <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${statusColors[battery.status]}`}>
                    {battery.status}
                  </span>
                </div>

                <div className="space-y-2 mb-3">
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-slate-500">Capacity</span>
                    <span className="font-medium text-slate-700">{battery.capacity}Ah / {battery.voltage}V</span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-slate-500">SOC</span>
                    <span className={`font-medium ${battery.currentSoc > 50 ? 'text-green-600' : battery.currentSoc > 20 ? 'text-amber-600' : 'text-red-600'}`}>{battery.currentSoc}%</span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-slate-500">Health</span>
                    <span className={`font-medium ${battery.health > 80 ? 'text-green-600' : battery.health > 60 ? 'text-amber-600' : 'text-red-600'}`}>{battery.health}%</span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-slate-500">Cycles</span>
                    <span className="font-medium text-slate-700">{battery.cycleCount}</span>
                  </div>
                  <div className="flex items-center justify-between text-xs">
                    <span className="text-slate-500">Price</span>
                    <span className="font-medium text-slate-700">৳{battery.purchasePrice.toLocaleString()}</span>
                  </div>
                </div>

                {battery.assignedBikeId && (
                  <div className="bg-white rounded-lg p-2 mb-3">
                    <p className="text-xs text-slate-500 mb-1">Current Assignment</p>
                    <p className="text-xs font-medium text-slate-700">{battery.assignedBikeModel}</p>
                    <p className="text-xs text-slate-400">{battery.assignedBikerName} • {battery.currentStationName}</p>
                  </div>
                )}

                <div className="flex items-center gap-1">
                  <div className="flex-1 py-1.5 text-xs font-medium text-blue-600 hover:bg-blue-50 rounded-lg text-center">
                    Details
                  </div>
                  <button onClick={() => handleViewHistory(battery)} className="flex-1 py-1.5 text-xs font-medium text-purple-600 hover:bg-purple-50 rounded-lg">
                    History
                  </button>
                  <button onClick={(e) => { e.preventDefault(); handleEditBattery(battery); }} className="p-1.5 hover:bg-white rounded-lg">
                    <Edit className="w-4 h-4 text-slate-400" />
                  </button>
                </div>
              </Link>
            ))}
          </div>
        )}

        <div className="p-4 border-t border-slate-100 flex items-center justify-between">
          <p className="text-sm text-slate-500">
            Showing <span className="font-medium">1</span> to <span className="font-medium">{filteredBatteries.length}</span> of <span className="font-medium">{batteries.length}</span> batteries
          </p>
          <div className="flex items-center gap-2">
            <button className="px-3 py-1.5 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50">Previous</button>
            <button className="px-3 py-1.5 bg-accent text-white rounded-lg text-sm font-medium">1</button>
            <button className="px-3 py-1.5 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 hover:bg-slate-50">Next</button>
          </div>
        </div>
      </div>

      {/* Add/Edit Modal */}
      {showModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
            <div className="p-5 border-b border-slate-100 flex items-center justify-between">
              <h2 className="text-lg font-bold text-slate-800">
                {editingBattery ? 'Edit Battery' : 'Register New Battery'}
              </h2>
              <button onClick={() => setShowModal(false)} className="p-2 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>
            <BatteryForm
              battery={editingBattery}
              onSave={handleSaveBattery}
              onCancel={() => setShowModal(false)}
            />
          </div>
        </div>
      )}



      {/* History Modal */}
      {showHistoryModal && selectedBattery && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
            <div className="p-5 border-b border-slate-100 flex items-center justify-between">
              <h2 className="text-lg font-bold text-slate-800">Battery History</h2>
              <button onClick={() => setShowHistoryModal(false)} className="p-2 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>
            <BatteryHistoryView battery={selectedBattery} onClose={() => setShowHistoryModal(false)} />
          </div>
        </div>
      )}

      {/* BMS Data Modal */}
      {showBMSModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
            <div className="p-5 border-b border-slate-100 flex items-center justify-between">
              <h2 className="text-lg font-bold text-slate-800">Receive BMS Data</h2>
              <button onClick={() => setShowBMSModal(false)} className="p-2 hover:bg-slate-100 rounded-lg">
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>
            <BMSDataReceiver
              batteries={batteries}
              onReceive={(batteryId, bmsData) => {
                setBatteries(batteries.map(b =>
                  b.id === batteryId ? { ...b, bmsData } : b
                ));
                setShowBMSModal(false);
              }}
              onCancel={() => setShowBMSModal(false)}
            />
          </div>
        </div>
      )}
    </div>
  );
}

function BatteryForm({ battery, onSave, onCancel }: { battery: Battery | null; onSave: (battery: Battery) => void; onCancel: () => void }) {
  const [formData, setFormData] = useState<Battery>(battery || {
    id: '',
    serialNumber: '',
    brand: '',
    model: '',
    type: 'lithium-ion',
    capacity: 50,
    voltage: 60,
    purchaseDate: new Date().toISOString().split('T')[0],
    purchasePrice: 0,
    transactionMethod: 'cash',
    autoJournal: true,
    autoJournalSource: 'supplier',
    warrantyExpiry: '',
    status: 'available',
    currentSoc: 100,
    health: 100,
    cycleCount: 0,
    history: [],
    hubId: '',
    hubName: '',
  });

  const handleChange = (field: keyof Battery, value: any) => {
    setFormData({ ...formData, [field]: value });
  };

  return (
    <div className="p-5 overflow-y-auto flex-1">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Serial Number *</label>
          <input
            type="text"
            value={formData.serialNumber}
            onChange={(e) => handleChange('serialNumber', e.target.value)}
            placeholder="SN-2024-00001"
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Brand *</label>
          <input
            type="text"
            value={formData.brand}
            onChange={(e) => handleChange('brand', e.target.value)}
            placeholder="EVE Energy"
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Model *</label>
          <input
            type="text"
            value={formData.model}
            onChange={(e) => handleChange('model', e.target.value)}
            placeholder="Li-Ion 60V50Ah"
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Type *</label>
          <select
            value={formData.type}
            onChange={(e) => handleChange('type', e.target.value)}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          >
            <option value="lithium-ion">Lithium-Ion</option>
            <option value="lifepo4">LiFePO4</option>
            <option value="lead-acid">Lead Acid</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Capacity (Ah)</label>
          <input
            type="number"
            value={formData.capacity}
            onChange={(e) => handleChange('capacity', parseInt(e.target.value))}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Voltage (V)</label>
          <input
            type="number"
            value={formData.voltage}
            onChange={(e) => handleChange('voltage', parseInt(e.target.value))}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Purchase Date</label>
          <input
            type="date"
            value={formData.purchaseDate}
            onChange={(e) => handleChange('purchaseDate', e.target.value)}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Purchase Price (৳)</label>
          <input
            type="number"
            value={formData.purchasePrice}
            onChange={(e) => handleChange('purchasePrice', parseInt(e.target.value))}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Deposit (৳) *</label>
          <input
            type="number"
            value={formData.deposit || 0}
            onChange={(e) => handleChange('deposit', parseInt(e.target.value))}
            placeholder="5000"
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Daily Rent Price (৳) *</label>
          <input
            type="number"
            value={formData.rentPrice || 0}
            onChange={(e) => handleChange('rentPrice', parseInt(e.target.value))}
            placeholder="150"
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Transaction Method</label>
          <select
            value={formData.transactionMethod || 'cash'}
            onChange={(e) => handleChange('transactionMethod', e.target.value as any)}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          >
            <option value="cash">Cash</option>
            <option value="bank_transfer">Bank Transfer</option>
            <option value="mobile_banking">Mobile Banking</option>
            <option value="cheque">Cheque</option>
            <option value="credit">Credit</option>
            <option value="other">Other</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Hub</label>
          <select
            value={formData.hubId || ''}
            onChange={(e) => {
              const hub = hubs.find(h => h.id === e.target.value);
              handleChange('hubId', e.target.value);
              handleChange('hubName', hub?.name || '');
            }}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          >
            <option value="">Select Hub...</option>
            {hubs.map(hub => (
              <option key={hub.id} value={hub.id}>{hub.name}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Warranty Expiry</label>
          <input
            type="date"
            value={formData.warrantyExpiry}
            onChange={(e) => handleChange('warrantyExpiry', e.target.value)}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Initial SOC (%)</label>
          <input
            type="number"
            value={formData.currentSoc}
            onChange={(e) => handleChange('currentSoc', parseInt(e.target.value))}
            max={100}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Status *</label>
          <select
            value={formData.status}
            onChange={(e) => handleChange('status', e.target.value)}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          >
            <option value="available">Available</option>
            <option value="charging">Charging</option>
            <option value="maintenance">Maintenance</option>
            <option value="retired">Retired</option>
          </select>
        </div>
      </div>
      <div className="flex gap-3 mt-6">
        <button onClick={onCancel} className="flex-1 py-2.5 px-4 border border-slate-200 rounded-lg font-semibold text-sm hover:bg-slate-50">
          Cancel
        </button>
        <button
          onClick={() => onSave(formData)}
          className="flex-1 py-2.5 px-4 bg-accent text-white rounded-lg font-semibold text-sm hover:bg-accent-dark"
        >
          {battery ? 'Update Battery' : 'Register Battery'}
        </button>
      </div>
    </div>
  );
}

function BatteryDetails({
  battery,
  bikes,
  bikers,
  stations,
  onAssign,
  onClose
}: {
  battery: Battery;
  bikes: Bike[];
  bikers: Biker[];
  stations: SwapStation[];
  onAssign: (batteryId: string, bikeId: string, bikerId: string, stationId: string) => void;
  onClose: () => void;
}) {
  const [selectedBike, setSelectedBike] = useState(battery.assignedBikeId || '');
  const [selectedBiker, setSelectedBiker] = useState(battery.assignedBikerId || '');
  const [selectedStation, setSelectedStation] = useState(battery.currentStationId || '');

  const handleAssign = () => {
    if (selectedBike && selectedBiker && selectedStation) {
      onAssign(battery.id, selectedBike, selectedBiker, selectedStation);
    }
  };

  const availableBikes = bikes.filter(b => b.status === 'rented' || b.status === 'available');
  const stationBikers = bikers.filter(b => b.stationId === selectedStation);

  return (
    <div className="p-5 overflow-y-auto flex-1">
      <div className="flex items-center gap-4 mb-6">
        <div className={`w-16 h-16 rounded-xl flex items-center justify-center ${battery.type === 'lithium-ion' ? 'bg-blue-50' : battery.type === 'lifepo4' ? 'bg-green-50' : 'bg-amber-50'}`}>
          <Battery className={`w-8 h-8 ${battery.type === 'lithium-ion' ? 'text-blue-600' : battery.type === 'lifepo4' ? 'text-green-600' : 'text-amber-600'}`} />
        </div>
        <div>
          <h3 className="text-xl font-bold text-slate-800">{battery.brand} {battery.model}</h3>
          <p className="text-sm text-slate-500">{battery.serialNumber}</p>
          <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full mt-1 ${statusColors[battery.status]}`}>
            {battery.status}
          </span>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 mb-6">
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Capacity</p>
          <p className="font-semibold text-slate-700">{battery.capacity}Ah / {battery.voltage}V</p>
        </div>
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Type</p>
          <p className="font-semibold text-slate-700">{typeLabels[battery.type]}</p>
        </div>
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Current SOC</p>
          <p className={`font-semibold ${battery.currentSoc > 50 ? 'text-green-600' : battery.currentSoc > 20 ? 'text-amber-600' : 'text-red-600'}`}>{battery.currentSoc}%</p>
        </div>
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Health</p>
          <p className={`font-semibold ${battery.health > 80 ? 'text-green-600' : battery.health > 60 ? 'text-amber-600' : 'text-red-600'}`}>{battery.health}%</p>
        </div>
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Cycle Count</p>
          <p className="font-semibold text-slate-700">{battery.cycleCount} cycles</p>
        </div>
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Purchase Price</p>
          <p className="font-semibold text-slate-700">৳{battery.purchasePrice.toLocaleString()}</p>
        </div>
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Battery Deposit</p>
          <p className="font-semibold text-emerald-700">৳{(battery.deposit || 0).toLocaleString()}</p>
        </div>
        <div className="bg-slate-50 rounded-lg p-3">
          <p className="text-xs text-slate-500 mb-1">Daily Rent Price</p>
          <p className="font-semibold text-blue-700">৳{(battery.rentPrice || 0).toLocaleString()}/day</p>
        </div>
      </div>

      {battery.bmsData && (
        <div className="border-t border-slate-100 pt-4 mb-4">
          <h4 className="font-semibold text-slate-700 mb-3 flex items-center gap-2">
            <Activity className="w-4 h-4" /> Live BMS Data
          </h4>
          <div className="grid grid-cols-2 lg:grid-cols-3 gap-3">
            <div className="bg-slate-50 rounded-lg p-3">
              <p className="text-xs text-slate-500">Voltage</p>
              <p className="text-lg font-bold text-slate-700">{battery.bmsData.voltage}V</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <p className="text-xs text-slate-500">Current</p>
              <p className="text-lg font-bold text-slate-700">{battery.bmsData.current}A</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <p className="text-xs text-slate-500">Temperature</p>
              <p className="text-lg font-bold text-slate-700">{battery.bmsData.temperature}°C</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <p className="text-xs text-slate-500">SOC</p>
              <p className="text-lg font-bold text-slate-700">{battery.bmsData.soc}%</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <p className="text-xs text-slate-500">Cycles</p>
              <p className="text-lg font-bold text-slate-700">{battery.bmsData.cycles}</p>
            </div>
            <div className="bg-slate-50 rounded-lg p-3">
              <p className="text-xs text-slate-500">Health</p>
              <p className={`text-lg font-bold ${battery.bmsData.health > 80 ? 'text-green-600' : 'text-amber-600'}`}>{battery.bmsData.health}%</p>
            </div>
          </div>
        </div>
      )}

      {battery.status !== 'retired' && (
        <div className="border-t border-slate-100 pt-4">
          <h4 className="font-semibold text-slate-700 mb-3 flex items-center gap-2">
            <User className="w-4 h-4" /> Assign to Bike & Biker
          </h4>
          <div className="space-y-3">
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Select Station *</label>
              <select
                value={selectedStation}
                onChange={(e) => { setSelectedStation(e.target.value); setSelectedBiker(''); }}
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
              >
                <option value="">Select Station...</option>
                {stations.map(s => (
                  <option key={s.id} value={s.id}>{s.name}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Select Biker *</label>
              <select
                value={selectedBiker}
                onChange={(e) => setSelectedBiker(e.target.value)}
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
              >
                <option value="">Select Biker...</option>
                {stationBikers.length > 0 ? stationBikers.map(b => (
                  <option key={b.id} value={b.id}>{b.name} ({b.phone})</option>
                )) : bikers.filter(b => b.stationId === selectedStation).map(b => (
                  <option key={b.id} value={b.id}>{b.name} ({b.phone})</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 mb-1">Select Bike *</label>
              <select
                value={selectedBike}
                onChange={(e) => setSelectedBike(e.target.value)}
                className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
              >
                <option value="">Select Bike...</option>
                {availableBikes.map(b => (
                  <option key={b.id} value={b.id}>{b.model} - {b.plateNumber}</option>
                ))}
              </select>
            </div>
            <button
              onClick={handleAssign}
              disabled={!selectedBike || !selectedBiker || !selectedStation}
              className="w-full py-2.5 px-4 bg-accent text-white rounded-lg font-semibold text-sm hover:bg-accent-dark disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Assign to Bike
            </button>
          </div>
        </div>
      )}

      <button onClick={onClose} className="w-full mt-4 py-2.5 px-4 bg-slate-100 text-slate-600 rounded-lg font-semibold text-sm hover:bg-slate-200">
        Close
      </button>
    </div>
  );
}

function BatteryHistoryView({ battery, onClose }: { battery: Battery; onClose: () => void }) {
  return (
    <div className="p-5 overflow-y-auto flex-1">
      <div className="flex items-center gap-3 mb-4">
        <div className="w-12 h-12 rounded-xl bg-purple-50 flex items-center justify-center">
          <History className="w-6 h-6 text-purple-600" />
        </div>
        <div>
          <p className="font-semibold text-slate-700">{battery.brand} {battery.model}</p>
          <p className="text-xs text-slate-400">{battery.serialNumber}</p>
        </div>
      </div>

      {battery.history.length === 0 ? (
        <div className="text-center py-8">
          <History className="w-12 h-12 text-slate-300 mx-auto mb-3" />
          <p className="text-slate-500">No history records found</p>
        </div>
      ) : (
        <div className="space-y-3">
          {battery.history.map((record, index) => (
            <div key={record.id} className="relative pl-8 pb-4 border-l-2 border-slate-200 last:border-0">
              <div className={`absolute -left-2 top-0 w-4 h-4 rounded-full ${record.action === 'assigned' ? 'bg-green-500' : record.action === 'swapped' ? 'bg-blue-500' : record.action === 'maintenance' ? 'bg-amber-500' : 'bg-slate-400'}`} />
              {index > 0 && <div className="absolute -left-2 top-4 w-4 h-4 rounded-full bg-slate-100 border-2 border-slate-200" />}
              <div className="bg-slate-50 rounded-lg p-3">
                <div className="flex items-center justify-between mb-2">
                  <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-0.5 rounded-full ${record.action === 'assigned' ? 'bg-green-100 text-green-700' : record.action === 'swapped' ? 'bg-blue-100 text-blue-700' : record.action === 'maintenance' ? 'bg-amber-100 text-amber-700' : 'bg-slate-100 text-slate-500'}`}>
                    {record.action === 'assigned' && <User className="w-3 h-3" />}
                    {record.action === 'swapped' && <Zap className="w-3 h-3" />}
                    {record.action === 'maintenance' && <Wrench className="w-3 h-3" />}
                    {record.action === 'retired' && <Trash2 className="w-3 h-3" />}
                    {record.action}
                  </span>
                  <span className="text-xs text-slate-400">{record.timestamp}</span>
                </div>
                {record.bikeModel && (
                  <p className="text-sm font-medium text-slate-700 flex items-center gap-1">
                    <Bike className="w-3 h-3" /> {record.bikeModel}
                  </p>
                )}
                {record.bikerName && (
                  <p className="text-sm text-slate-600 flex items-center gap-1">
                    <User className="w-3 h-3" /> {record.bikerName}
                  </p>
                )}
                {record.stationName && (
                  <p className="text-sm text-slate-500 flex items-center gap-1">
                    <MapPin className="w-3 h-3" /> {record.stationName}
                  </p>
                )}
                {record.notes && (
                  <p className="text-xs text-slate-400 mt-1 italic">{record.notes}</p>
                )}
              </div>
            </div>
          ))}
        </div>
      )}

      <button onClick={onClose} className="w-full mt-4 py-2.5 px-4 bg-slate-100 text-slate-600 rounded-lg font-semibold text-sm hover:bg-slate-200">
        Close
      </button>
    </div>
  );
}

function BMSDataReceiver({
  batteries,
  onReceive,
  onCancel
}: {
  batteries: Battery[];
  onReceive: (batteryId: string, bmsData: BMSData) => void;
  onCancel: () => void;
}) {
  const [selectedBatteryId, setSelectedBatteryId] = useState('');
  const [isReceiving, setIsReceiving] = useState(false);
  const [receivedData, setReceivedData] = useState<BMSData | null>(null);

  const simulateBMSData = (): BMSData => {
    const baseVoltage = 60 + Math.random() * 10;
    const baseSoc = Math.floor(Math.random() * 40) + 60;
    const baseTemp = 25 + Math.floor(Math.random() * 15);
    const baseCurrent = -3 + Math.random() * 4;
    const baseCycles = Math.floor(Math.random() * 300);
    const baseHealth = 70 + Math.floor(Math.random() * 30);

    return {
      voltage: Math.round(baseVoltage * 10) / 10,
      current: Math.round(baseCurrent * 10) / 10,
      soc: baseSoc,
      temperature: baseTemp,
      cycles: baseCycles,
      health: baseHealth,
      timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
    };
  };

  const handleReceiveData = () => {
    if (!selectedBatteryId) return;
    setIsReceiving(true);
    setTimeout(() => {
      const data = simulateBMSData();
      setReceivedData(data);
      setIsReceiving(false);
    }, 1500);
  };

  const handleSaveData = () => {
    if (selectedBatteryId && receivedData) {
      onReceive(selectedBatteryId, receivedData);
    }
  };

  return (
    <div className="p-5 overflow-y-auto flex-1">
      <div className="bg-blue-50 rounded-lg p-4 mb-4">
        <div className="flex items-start gap-3">
          <Activity className="w-5 h-5 text-blue-600 mt-0.5" />
          <div>
            <p className="text-sm font-medium text-blue-800">BMS Data Integration</p>
            <p className="text-xs text-blue-600 mt-1">Connect to digital BMS to receive real-time battery data. Data will be processed and stored for monitoring.</p>
          </div>
        </div>
      </div>

      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-slate-700 mb-1">Select Battery</label>
          <select
            value={selectedBatteryId}
            onChange={(e) => { setSelectedBatteryId(e.target.value); setReceivedData(null); }}
            className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent"
          >
            <option value="">Select Battery...</option>
            {batteries.map(b => (
              <option key={b.id} value={b.id}>{b.brand} {b.model} - {b.serialNumber}</option>
            ))}
          </select>
        </div>

        <button
          onClick={handleReceiveData}
          disabled={!selectedBatteryId || isReceiving}
          className="w-full py-2.5 px-4 bg-green-600 text-white rounded-lg font-semibold text-sm hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
        >
          {isReceiving ? (
            <>
              <RefreshCw className="w-4 h-4 animate-spin" /> Receiving Data...
            </>
          ) : (
            <>
              <BatteryCharging className="w-4 h-4" /> Receive BMS Data
            </>
          )}
        </button>

        {receivedData && (
          <div className="border-t border-slate-100 pt-4 mt-4">
            <h4 className="font-semibold text-slate-700 mb-3 flex items-center gap-2">
              <CheckCircle className="w-4 h-4 text-green-600" /> Received Data
            </h4>
            <div className="grid grid-cols-2 lg:grid-cols-3 gap-3">
              <div className="bg-slate-50 rounded-lg p-3">
                <p className="text-xs text-slate-500">Voltage</p>
                <p className="text-lg font-bold text-slate-700">{receivedData.voltage}V</p>
              </div>
              <div className="bg-slate-50 rounded-lg p-3">
                <p className="text-xs text-slate-500">Current</p>
                <p className="text-lg font-bold text-slate-700">{receivedData.current}A</p>
              </div>
              <div className="bg-slate-50 rounded-lg p-3">
                <p className="text-xs text-slate-500">SOC</p>
                <p className="text-lg font-bold text-green-600">{receivedData.soc}%</p>
              </div>
              <div className="bg-slate-50 rounded-lg p-3">
                <p className="text-xs text-slate-500">Temperature</p>
                <p className="text-lg font-bold text-slate-700">{receivedData.temperature}°C</p>
              </div>
              <div className="bg-slate-50 rounded-lg p-3">
                <p className="text-xs text-slate-500">Cycles</p>
                <p className="text-lg font-bold text-slate-700">{receivedData.cycles}</p>
              </div>
              <div className="bg-slate-50 rounded-lg p-3">
                <p className="text-xs text-slate-500">Health</p>
                <p className={`text-lg font-bold ${receivedData.health > 80 ? 'text-green-600' : 'text-amber-600'}`}>{receivedData.health}%</p>
              </div>
            </div>
            <p className="text-xs text-slate-400 mt-3">Received at: {receivedData.timestamp}</p>
          </div>
        )}
      </div>

      <div className="flex gap-3 mt-6">
        <button onClick={onCancel} className="flex-1 py-2.5 px-4 border border-slate-200 rounded-lg font-semibold text-sm hover:bg-slate-50">
          Cancel
        </button>
        {receivedData && (
          <button onClick={handleSaveData} className="flex-1 py-2.5 px-4 bg-accent text-white rounded-lg font-semibold text-sm hover:bg-accent-dark">
            Save Data
          </button>
        )}
      </div>
    </div>
  );
}

function Wrench({ className }: { className?: string }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" />
    </svg>
  );
}