'use client';

import { useState } from 'react';
import { Zap, Search, Plus, X, MapPin, Phone, Battery, Clock, CheckCircle, XCircle, AlertCircle, Eye, Edit, Trash2, Filter } from 'lucide-react';
import Link from 'next/link';

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

const mockStations: SwapStation[] = [
  {
    id: 'SS-001',
    name: 'JAIBEN Swap Hub - Gulshan',
    address: 'House 45, Road 13, Gulshan 1',
    city: 'Dhaka',
    phone: '+8801712345670',
    status: 'active',
    totalSlots: 20,
    charging: 3,
    readyToSwap: 12,
    inUse: 5,
    lastRestock: '2024-02-15',
    hubId: 'HUB-001'
  },
  {
    id: 'SS-002',
    name: 'JAIBEN Swap Hub - Banani',
    address: 'House 8, Road 11, Banani',
    city: 'Dhaka',
    phone: '+8801712345671',
    status: 'active',
    totalSlots: 15,
    charging: 2,
    readyToSwap: 8,
    inUse: 5,
    lastRestock: '2024-02-14',
    hubId: 'HUB-001'
  },
  {
    id: 'SS-003',
    name: 'JAIBEN Swap Hub - Uttara',
    address: 'Sector 10, Road 2, Uttara',
    city: 'Dhaka',
    phone: '+8801712345672',
    status: 'maintenance',
    totalSlots: 10,
    charging: 0,
    readyToSwap: 0,
    inUse: 0,
    lastRestock: '2024-02-10'
  },
  {
    id: 'SS-004',
    name: 'JAIBEN Swap Hub - Mirpur',
    address: 'Section 10, Mirpur',
    city: 'Dhaka',
    phone: '+8801712345673',
    status: 'active',
    totalSlots: 25,
    charging: 5,
    readyToSwap: 15,
    inUse: 5,
    lastRestock: '2024-02-16'
  }
];

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 statusLabels: Record<string, string> = {
  active: 'Active',
  inactive: 'Inactive',
  maintenance: 'Maintenance'
};

export default function SwapStationsPage() {
  const [stations, setStations] = useState<SwapStation[]>(mockStations);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingStation, setEditingStation] = useState<SwapStation | null>(null);
  const [selectedStation, setSelectedStation] = useState<SwapStation | null>(null);

  const [formData, setFormData] = useState({
    name: '',
    address: '',
    city: 'Dhaka',
    phone: '',
    status: 'active' as SwapStation['status'],
    totalSlots: 10,
    hubId: 'HUB-001'
  });

  const filteredStations = stations.filter(s => {
    const matchesSearch = s.name.toLowerCase().includes(search.toLowerCase()) ||
      s.address.toLowerCase().includes(search.toLowerCase()) ||
      s.id.toLowerCase().includes(search.toLowerCase());
    const matchesStatus = statusFilter === 'all' || s.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const stats = {
    total: stations.length,
    active: stations.filter(s => s.status === 'active').length,
    totalSlots: stations.reduce((a, s) => a + s.totalSlots, 0),
    readyToSwap: stations.reduce((a, s) => a + s.readyToSwap, 0),
    charging: stations.reduce((a, s) => a + s.charging, 0)
  };

  const handleSave = () => {
    if (!formData.name || !formData.address || !formData.phone) return;

    if (editingStation) {
      setStations(stations.map(s => s.id === editingStation.id ? { ...s, ...formData } : s));
    } else {
      const newStation: SwapStation = {
        id: `SS-${String(stations.length + 1).padStart(3, '0')}`,
        ...formData,
        charging: 2,
        readyToSwap: Math.floor(formData.totalSlots * 0.6),
        inUse: formData.totalSlots - Math.floor(formData.totalSlots * 0.6) - 2,
        lastRestock: new Date().toISOString().split('T')[0]
      };
      setStations([...stations, newStation]);
    }

    setShowCreateModal(false);
    setEditingStation(null);
    setFormData({ name: '', address: '', city: 'Dhaka', phone: '', status: 'active', totalSlots: 10, hubId: 'HUB-001' });
  };

  const handleDelete = (id: string) => {
    if (confirm('Are you sure you want to delete this station?')) {
      setStations(stations.filter(s => s.id !== id));
    }
    setSelectedStation(null);
  };

  const openEdit = (station: SwapStation) => {
    setEditingStation(station);
    setFormData({
      name: station.name,
      address: station.address,
      city: station.city,
      phone: station.phone,
      status: station.status,
      totalSlots: station.totalSlots,
      hubId: station.hubId || 'HUB-001'
    });
    setShowCreateModal(true);
    setSelectedStation(null);
  };

  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">Swap Stations (P3)</h1>
          <p className="text-sm text-slate-500 mt-1">Manage battery swap stations across Dhaka</p>
        </div>
        <button
          onClick={() => {
            setEditingStation(null);
            setFormData({ name: '', address: '', city: 'Dhaka', phone: '', status: 'active', totalSlots: 10, hubId: 'HUB-001' });
            setShowCreateModal(true);
          }}
          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" /> Add Station
        </button>
      </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">
          <p className="text-2xl font-extrabold text-slate-800">{stats.total}</p>
          <p className="text-sm text-slate-500">Total Stations</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-green-600">{stats.active}</p>
          <p className="text-sm text-slate-500">Active</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-blue-600">{stats.totalSlots}</p>
          <p className="text-sm text-slate-500">Total Slots</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-purple-600">{stats.readyToSwap}</p>
          <p className="text-sm text-slate-500">Ready to Swap</p>
        </div>
        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100">
          <p className="text-2xl font-extrabold text-amber-600">{stats.charging}</p>
          <p className="text-sm text-slate-500">Charging</p>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-100">
        <div className="p-4 border-b border-slate-100">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
              <input
                type="text"
                placeholder="Search stations..."
                value={search}
                onChange={(e) => setSearch(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>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="py-2 px-4 border border-slate-200 rounded-lg text-sm"
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
              <option value="maintenance">Maintenance</option>
            </select>
          </div>
        </div>

        <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">Station</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Location</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Slots</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase">Batteries</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">
              {filteredStations.map(station => (
                <tr key={station.id} className="hover:bg-slate-50 transition-colors">
<td className="px-4 py-3">
                    <Link 
                      href={`/admin/swap-stations/${station.id.toLowerCase()}`}
                      className="text-left hover:text-accent"
                    >
                      <div className="flex items-center gap-2">
                        <Zap className="w-4 h-4 text-amber-500" />
                        <span className="text-sm font-medium text-slate-700">{station.name}</span>
                      </div>
                      <p className="text-xs text-slate-400 pl-6">{station.id}</p>
                    </Link>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm text-slate-600">{station.address}</p>
                    <p className="text-xs text-slate-400">{station.city}</p>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <Battery className="w-4 h-4 text-blue-400" />
                      <span className="text-sm font-medium text-slate-700">
                        {station.readyToSwap}/{station.totalSlots}
                      </span>
                    </div>
                    <p className="text-xs text-slate-400">{station.charging} charging</p>
                  </td>
                  <td className="px-4 py-3">
                    <p className="text-sm font-medium text-green-600">{station.inUse}</p>
                    <p className="text-xs text-slate-400">in use</p>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-medium px-2 py-1 rounded-full ${statusColors[station.status]}`}>
                      {statusLabels[station.status]}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <Link
                        href={`/admin/swap-stations/${station.id.toLowerCase()}`}
                        className="p-2 hover:bg-blue-100 rounded-lg"
                      >
                        <Eye className="w-4 h-4 text-blue-400" />
                      </Link>
                      <button onClick={() => openEdit(station)} className="p-2 hover:bg-slate-100 rounded-lg">
                        <Edit className="w-4 h-4 text-slate-400" />
                      </button>
                      <button onClick={() => handleDelete(station.id)} className="p-2 hover:bg-red-50 rounded-lg">
                        <Trash2 className="w-4 h-4 text-red-400" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {showCreateModal && (
        <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-lg max-h-[90vh] overflow-y-auto">
            <div className="p-4 border-b border-slate-100 flex justify-between items-center sticky top-0 bg-white">
              <h3 className="font-semibold text-slate-800">{editingStation ? 'Edit Station' : 'Add New Station'}</h3>
              <button onClick={() => setShowCreateModal(false)} className="text-slate-400 hover:text-slate-600">
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-4 space-y-4">
              <div>
                <label className="text-sm text-slate-600">Station Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  placeholder="e.g., JAIBEN Swap Hub - Gulshan"
                />
              </div>
              <div>
                <label className="text-sm text-slate-600">Address *</label>
                <textarea
                  value={formData.address}
                  onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  rows={2}
                  placeholder="Full address"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-slate-600">City</label>
                  <select
                    value={formData.city}
                    onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  >
                    <option value="Dhaka">Dhaka</option>
                    <option value="Chittagong">Chittagong</option>
                    <option value="Sylhet">Sylhet</option>
                    <option value="Khulna">Khulna</option>
                  </select>
                </div>
                <div>
                  <label className="text-sm text-slate-600">Phone *</label>
                  <input
                    type="text"
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                    placeholder="+8801xxxxxxxxx"
                  />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-slate-600">Total Slots</label>
                  <input
                    type="number"
                    value={formData.totalSlots}
                    onChange={(e) => setFormData({ ...formData, totalSlots: parseInt(e.target.value) || 10 })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                    min={1}
                  />
                </div>
                <div>
                  <label className="text-sm text-slate-600">Status</label>
                  <select
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: e.target.value as SwapStation['status'] })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  >
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                    <option value="maintenance">Maintenance</option>
                  </select>
                </div>
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2 sticky bottom-0 bg-white">
              <button
                onClick={() => setShowCreateModal(false)}
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-sm"
              >
                Cancel
              </button>
              <button
                onClick={handleSave}
                disabled={!formData.name || !formData.address || !formData.phone}
                className="px-4 py-2 bg-accent text-white rounded-lg text-sm disabled:opacity-50"
              >
                {editingStation ? 'Update' : 'Create'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}