'use client';

import { useState, use } from 'react';
import { Zap, ArrowLeft, Phone, Mail, MapPin, Battery, Clock, CheckCircle, XCircle, Edit, Trash2, RefreshCw, ZapOff } from 'lucide-react';

interface BatterySlot {
  slotId: string;
  batteryId: string | null;
  charge: number;
  status: 'empty' | 'charging' | 'ready' | 'in-use';
  lastUpdate: string;
}

interface SwapStation {
  id: string;
  name: string;
  address: string;
  city: string;
  phone: string;
  status: 'active' | 'inactive' | 'maintenance';
  lastRestock: string;
  hubId?: string;
}

interface SwapRequest {
  id: string;
  stationId: string;
  bikerName: string;
  bikerPhone: string;
  bikeModel: string;
  currentBattery: number;
  requestedBattery: number;
  status: 'pending' | 'approved' | 'rejected' | 'completed';
  requestedAt: string;
  processedAt?: string;
}

const generateSlots = (total: number) => {
  const slots: BatterySlot[] = [];
  const statuses: BatterySlot['status'][] = ['ready', 'ready', 'ready', 'charging', 'charging', 'in-use'];
  
  for (let i = 1; i <= total; i++) {
    const status = i <= 12 ? 'ready' : i <= 17 ? 'charging' : 'in-use';
    slots.push({
      slotId: `SL-${String(i).padStart(2, '0')}`,
      batteryId: `BAT-${String(1000 + i).padStart(4, '0')}`,
      charge: status === 'ready' ? 85 + Math.floor(Math.random() * 15) : status === 'charging' ? 45 + Math.floor(Math.random() * 35) : 30 + Math.floor(Math.random() * 30),
      status,
      lastUpdate: '2024-02-16 10:00'
    });
  }
  return slots;
};

const mockStation: SwapStation = {
  id: 'SS-001',
  name: 'JAIBEN Swap Hub - Gulshan',
  address: 'House 45, Road 13, Gulshan 1',
  city: 'Dhaka',
  phone: '+8801712345670',
  status: 'active',
  lastRestock: '2024-02-15',
  hubId: 'HUB-001'
};

const mockRequests: SwapRequest[] = [
  { id: 'SWR-001', stationId: 'SS-001', bikerName: 'Karim Khan', bikerPhone: '+8801712345678', bikeModel: 'Yamaha NMAX', currentBattery: 15, requestedBattery: 100, status: 'pending', requestedAt: '2024-02-16 10:30:00' },
  { id: 'SWR-002', stationId: 'SS-001', bikerName: 'Jamal Mia', bikerPhone: '+8801812345678', bikeModel: 'Honda PCX', currentBattery: 20, requestedBattery: 100, status: 'approved', requestedAt: '2024-02-16 09:15:00' },
  { id: 'SWR-003', stationId: 'SS-001', bikerName: 'Rahim Ali', bikerPhone: '+8801912345678', bikeModel: 'TVS Ntorq', currentBattery: 10, requestedBattery: 100, status: 'pending', requestedAt: '2024-02-16 08:45:00' },
  { id: 'SWR-004', stationId: 'SS-001', bikerName: 'Rashid Khan', bikerPhone: '+8801512345678', bikeModel: 'Suzuki Burgman', currentBattery: 25, requestedBattery: 100, status: 'rejected', requestedAt: '2024-02-15 18:30:00' },
  { id: 'SWR-005', stationId: 'SS-001', bikerName: 'Saif Ahmed', bikerPhone: '+8801612345678', bikeModel: 'Yamaha NMAX', currentBattery: 18, requestedBattery: 100, status: 'completed', requestedAt: '2024-02-15 14:20:00', processedAt: '2024-02-15 14:25:00' },
];

const statusColors: Record<string, string> = {
  active: 'bg-green-100 text-green-700',
  inactive: 'bg-slate-100 text-slate-700',
  maintenance: 'bg-amber-100 text-amber-700'
};

const slotStatusColors: Record<string, string> = {
  ready: 'bg-green-100 border-green-300',
  charging: 'bg-amber-100 border-amber-300',
  'in-use': 'bg-blue-100 border-blue-300',
  empty: 'bg-slate-100 border-slate-300'
};

const requestStatusColors: Record<string, string> = {
  pending: 'bg-amber-100 text-amber-700',
  approved: 'bg-blue-100 text-blue-700',
  rejected: 'bg-red-100 text-red-700',
  completed: 'bg-green-100 text-green-700'
};

const requestStatusLabels: Record<string, string> = {
  pending: 'Pending',
  approved: 'Approved',
  rejected: 'Rejected',
  completed: 'Completed'
};

export default function SwapStationDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const [station] = useState<SwapStation>(mockStation);
  const [slots, setSlots] = useState<BatterySlot[]>(generateSlots(20));
  const [requests, setRequests] = useState<SwapRequest[]>(mockRequests);
  const [activeTab, setActiveTab] = useState<'slots' | 'requests' | 'transactions'>('slots');

  const readyCount = slots.filter(s => s.status === 'ready').length;
  const chargingCount = slots.filter(s => s.status === 'charging').length;
  const inUseCount = slots.filter(s => s.status === 'in-use').length;
  const emptyCount = slots.filter(s => s.status === 'empty').length;

  const handleApprove = (requestId: string) => {
    setRequests(requests.map(r => r.id === requestId ? { ...r, status: 'approved' as const, processedAt: new Date().toISOString().replace('T', ' ').split('.')[0] } : r));
  };

  const handleReject = (requestId: string) => {
    setRequests(requests.map(r => r.id === requestId ? { ...r, status: 'rejected' as const, processedAt: new Date().toISOString().replace('T', ' ').split('.')[0] } : r));
  };

  const handleComplete = (requestId: string) => {
    setRequests(requests.map(r => r.id === requestId ? { ...r, status: 'completed' as const, processedAt: new Date().toISOString().replace('T', ' ').split('.')[0] } : r));
  };

  const pendingRequests = requests.filter(r => r.status === 'pending');
  const completedTransactions = requests.filter(r => r.status === 'completed');

  const getChargeColor = (charge: number) => {
    if (charge >= 80) return 'text-green-600';
    if (charge >= 50) return 'text-amber-600';
    return 'text-red-600';
  };

  return (
    <div className="p-4 lg:p-6">
      <div className="flex items-center gap-4 mb-6">
        <a href="/admin/swap-stations" className="p-2 hover:bg-slate-100 rounded-lg">
          <ArrowLeft className="w-5 h-5 text-slate-600" />
        </a>
        <div className="flex-1">
          <h1 className="text-xl lg:text-2xl font-extrabold text-slate-800">{station.name}</h1>
          <p className="text-sm text-slate-500">{station.id} • Last restock: {station.lastRestock}</p>
        </div>
        <div className="flex gap-2">
          <button className="py-2 px-4 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50 flex items-center gap-2">
            <Edit className="w-4 h-4" /> Edit
          </button>
          <button className="py-2 px-4 bg-red-500 text-white rounded-lg text-sm hover:bg-red-600 flex items-center gap-2">
            <Trash2 className="w-4 h-4" /> Delete
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
        <div className="bg-white rounded-xl p-4 shadow-sm border border-slate-100">
          <p className="text-xl lg:text-2xl font-bold text-green-600">{readyCount}</p>
          <p className="text-sm text-slate-500">Ready to Swap</p>
        </div>
        <div className="bg-white rounded-xl p-4 shadow-sm border border-slate-100">
          <p className="text-xl lg:text-2xl font-bold text-amber-600">{chargingCount}</p>
          <p className="text-sm text-slate-500">Charging</p>
        </div>
        <div className="bg-white rounded-xl p-4 shadow-sm border border-slate-100">
          <p className="text-xl lg:text-2xl font-bold text-blue-600">{inUseCount}</p>
          <p className="text-sm text-slate-500">In Use</p>
        </div>
        <div className="bg-white rounded-xl p-4 shadow-sm border border-slate-100">
          <p className="text-xl lg:text-2xl font-bold text-amber-600">{pendingRequests.length}</p>
          <p className="text-sm text-slate-500">Pending Requests</p>
        </div>
        <div className="bg-white rounded-xl p-4 shadow-sm border border-slate-100">
          <p className="text-xl lg:text-2xl font-bold text-blue-600">{completedTransactions.length}</p>
          <p className="text-sm text-slate-500">Swaps Today</p>
        </div>
      </div>

      <div className="grid lg:grid-cols-2 gap-6 mb-6">
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <h3 className="font-semibold text-slate-800 mb-4">Station Information</h3>
          <div className="space-y-3">
            <div className="flex items-center gap-3">
              <Zap className="w-4 h-4 text-amber-500" />
              <span className="text-sm text-slate-600">{station.name}</span>
            </div>
            <div className="flex items-center gap-3">
              <span className="text-xs px-2 py-1 rounded-full bg-slate-50 text-slate-600">Status</span>
              <span className={`text-xs px-2 py-1 rounded-full ${statusColors[station.status]}`}>
                {station.status.toUpperCase()}
              </span>
            </div>
            <div className="flex items-center gap-3">
              <Phone className="w-4 h-4 text-slate-400" />
              <span className="text-sm text-slate-600">{station.phone}</span>
            </div>
            <div className="flex items-center gap-3">
              <MapPin className="w-4 h-4 text-slate-400" />
              <span className="text-sm text-slate-600">{station.address}, {station.city}</span>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <h3 className="font-semibold text-slate-800 mb-4">Quick Actions</h3>
          <div className="space-y-3">
            <div className="flex justify-between text-sm">
              <span className="text-slate-600">Total Slots</span>
              <span className="font-medium text-slate-800">20</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-slate-600">Ready</span>
              <span className="font-medium text-green-600">{readyCount}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-slate-600">Charging</span>
              <span className="font-medium text-amber-600">{chargingCount}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-slate-600">In Use</span>
              <span className="font-medium text-blue-600">{inUseCount}</span>
            </div>
            <button className="w-full mt-2 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm hover:bg-slate-50 flex items-center justify-center gap-2">
              <RefreshCw className="w-4 h-4" /> Restock Batteries
            </button>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100 mb-6">
        <div className="flex gap-6 p-4 border-b border-slate-100 overflow-x-auto">
          {(['slots', 'requests', 'transactions'] as const).map(tab => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`text-sm font-medium pb-2 border-b-2 whitespace-nowrap transition-colors ${
                activeTab === tab 
                  ? 'text-accent border-accent' 
                  : 'text-slate-500 border-transparent hover:text-slate-700'
              }`}
            >
              {tab === 'slots' ? 'Battery Slots' : tab === 'requests' ? 'Swap Requests' : 'Transactions'}
              {tab === 'requests' && pendingRequests.length > 0 && (
                <span className="ml-2 px-1.5 py-0.5 bg-amber-500 text-white text-xs rounded-full">{pendingRequests.length}</span>
              )}
            </button>
          ))}
        </div>

        {activeTab === 'slots' && (
          <div className="p-4">
            <div className="flex items-center gap-4 mb-4">
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-green-500" />
                <span className="text-xs text-slate-600">Ready ({readyCount})</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-amber-500" />
                <span className="text-xs text-slate-600">Charging ({chargingCount})</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-blue-500" />
                <span className="text-xs text-slate-600">In Use ({inUseCount})</span>
              </div>
              <div className="flex items-center gap-2">
                <div className="w-3 h-3 rounded-full bg-slate-300" />
                <span className="text-xs text-slate-600">Empty ({emptyCount})</span>
              </div>
            </div>

            <div className="grid grid-cols-4 sm:grid-cols-5 md:grid-cols-6 lg:grid-cols-10 gap-3">
              {slots.map(slot => (
                <div 
                  key={slot.slotId}
                  className={`
                    aspect-square rounded-lg border-2 p-2 flex flex-col justify-between
                    ${slotStatusColors[slot.status]}
                    ${slot.status === 'empty' ? 'opacity-50' : ''}
                  `}
                >
                  <div className="flex items-center justify-between">
                    <span className="text-xs font-medium text-slate-600">{slot.slotId}</span>
                    {slot.status === 'charging' && (
                      <div className="w-2 h-2 rounded-full bg-amber-500 animate-pulse" />
                    )}
                  </div>
                  <div>
                    {slot.batteryId ? (
                      <>
                        <p className="text-[10px] text-slate-500 truncate">{slot.batteryId}</p>
                        <p className={`text-lg font-bold ${getChargeColor(slot.charge)}`}>{slot.charge}%</p>
                      </>
                    ) : (
                      <div className="flex items-center justify-center h-full">
                        <ZapOff className="w-5 h-5 text-slate-400" />
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {activeTab === 'requests' && (
          <div className="p-4">
            <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">Request</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Biker</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Bike</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Current %</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Time</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Status</th>
                    <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-50">
                  {requests.map(request => (
                    <tr key={request.id} className="hover:bg-slate-50">
                      <td className="px-4 py-3 text-sm font-medium text-slate-700">{request.id}</td>
                      <td className="px-4 py-3">
                        <p className="text-sm text-slate-600">{request.bikerName}</p>
                        <p className="text-xs text-slate-400">{request.bikerPhone}</p>
                      </td>
                      <td className="px-4 py-3 text-sm text-slate-600">{request.bikeModel}</td>
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-2">
                          <Battery className="w-4 h-4 text-green-500" />
                          <span className={`text-sm font-medium ${request.currentBattery <= 20 ? 'text-red-600' : 'text-green-600'}`}>
                            {request.currentBattery}%
                          </span>
                        </div>
                      </td>
                      <td className="px-4 py-3 text-sm text-slate-500">{request.requestedAt}</td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-1 rounded-full ${requestStatusColors[request.status]}`}>
                          {requestStatusLabels[request.status]}
                        </span>
                      </td>
                      <td className="px-4 py-3">
                        {request.status === 'pending' && (
                          <div className="flex gap-1">
                            <button onClick={() => handleApprove(request.id)} className="px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600">Approve</button>
                            <button onClick={() => handleReject(request.id)} className="px-2 py-1 text-xs bg-red-500 text-white rounded hover:bg-red-600">Reject</button>
                          </div>
                        )}
                        {request.status === 'approved' && (
                          <button onClick={() => handleComplete(request.id)} className="px-2 py-1 text-xs bg-green-500 text-white rounded hover:bg-green-600">Complete</button>
                        )}
                        {request.status === 'completed' && <span className="text-xs text-slate-400">Done</span>}
                        {request.status === 'rejected' && <span className="text-xs text-red-500">Rejected</span>}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {activeTab === 'transactions' && (
          <div className="p-4">
            <div className="text-center py-12 text-slate-500">
              <Zap className="w-12 h-12 mx-auto mb-4 text-amber-300" />
              <p className="text-sm">Select a request tab to view completed transactions</p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}