'use client';

import { useState } from 'react';
import { MapPin, Plus, Search, Eye, Edit, Trash2, Bike, X, Navigation, Phone, Clock } from 'lucide-react';
import Link from 'next/link';

interface Hub {
  id: string;
  name: string;
  address: string;
  phone: string;
  managerName?: string;
  bikeCount: number;
  activeRentals: number;
  status: 'active' | 'inactive';
  coordinates?: { lat: number; lng: number };
  openTime: string;
  closeTime: string;
  isHeadOffice?: boolean;
}

const mockHubs: Hub[] = [
  {
    id: 'HUB-001',
    name: 'JAIBEN Head Office',
    address: 'House 12, Road 17, Gulshan 1, Dhaka',
    phone: '+8801712345678',
    managerName: 'Rahim Ahmed',
    bikeCount: 25,
    activeRentals: 12,
    status: 'active',
    coordinates: { lat: 23.7925, lng: 90.4174 },
    openTime: '06:00',
    closeTime: '23:00',
    isHeadOffice: true
  },
  {
    id: 'HUB-002',
    name: 'Banani Hub',
    address: 'House 5, Road 11, Banani, Dhaka',
    phone: '+8801812345678',
    managerName: 'Karim Hasan',
    bikeCount: 18,
    activeRentals: 8,
    status: 'active',
    coordinates: { lat: 23.7785, lng: 90.4190 },
    openTime: '06:00',
    closeTime: '23:00'
  },
  {
    id: 'HUB-003',
    name: 'Uttara Hub',
    address: 'Sector 11, Uttara, Dhaka',
    phone: '+8801912345678',
    managerName: 'Jamal Uddin',
    bikeCount: 30,
    activeRentals: 15,
    status: 'active',
    coordinates: { lat: 23.8657, lng: 90.4027 },
    openTime: '06:00',
    closeTime: '23:00'
  },
  {
    id: 'HUB-004',
    name: 'Mirpur Hub',
    address: 'Section 10, Mirpur, Dhaka',
    phone: '+8801512345678',
    bikeCount: 0,
    activeRentals: 0,
    status: 'inactive',
    openTime: '06:00',
    closeTime: '23:00'
  }
];

export default function HubsPage() {
  const [hubs, setHubs] = useState<Hub[]>(mockHubs);
  const [search, setSearch] = useState('');
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [editingHub, setEditingHub] = useState<Hub | null>(null);
  
  const [formData, setFormData] = useState({
    name: '',
    address: '',
    phone: '',
    managerName: '',
    openTime: '06:00',
    closeTime: '23:00',
    isHeadOffice: false,
  });

  const filteredHubs = hubs.filter(h => 
    h.name.toLowerCase().includes(search.toLowerCase()) ||
    h.address.toLowerCase().includes(search.toLowerCase())
  );

  const handleSave = () => {
    if (!formData.name || !formData.address) return;
    
    if (editingHub) {
      setHubs(hubs.map(h => h.id === editingHub.id ? { 
        ...h, 
        ...formData,
        status: editingHub.status,
        bikeCount: editingHub.bikeCount,
        activeRentals: editingHub.activeRentals,
      } : h));
    } else {
      const newHub: Hub = {
        id: `HUB-${String(hubs.length + 1).padStart(3, '0')}`,
        ...formData,
        bikeCount: 0,
        activeRentals: 0,
        status: 'active',
      };
      setHubs([...hubs, newHub]);
    }
    
    setShowCreateModal(false);
    setEditingHub(null);
    setFormData({ name: '', address: '', phone: '', managerName: '', openTime: '06:00', closeTime: '23:00', isHeadOffice: false });
  };

  const handleDelete = (id: string) => {
    if (confirm('Are you sure you want to delete this hub?')) {
      setHubs(hubs.filter(h => h.id !== id));
    }
  };

  const openEdit = (hub: Hub) => {
    setEditingHub(hub);
    setFormData({
      name: hub.name,
      address: hub.address,
      phone: hub.phone,
      managerName: hub.managerName || '',
      openTime: hub.openTime,
      closeTime: hub.closeTime,
      isHeadOffice: hub.isHeadOffice || false,
    });
    setShowCreateModal(true);
  };

  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">Hubs</h1>
          <p className="text-sm text-slate-500 mt-1">Manage hub locations and branches</p>
        </div>
        <button 
          onClick={() => {
            setEditingHub(null);
            setFormData({ name: '', address: '', phone: '', managerName: '', openTime: '06:00', closeTime: '23:00', isHeadOffice: false });
            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 New Hub
        </button>
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 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">{hubs.length}</p>
          <p className="text-sm text-slate-500">Total Hubs</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">{hubs.filter(h => h.status === 'active').length}</p>
          <p className="text-sm text-slate-500">Active Hubs</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">{hubs.reduce((a, h) => a + h.bikeCount, 0)}</p>
          <p className="text-sm text-slate-500">Total Bikes</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">{hubs.reduce((a, h) => a + h.activeRentals, 0)}</p>
          <p className="text-sm text-slate-500">Active Rentals</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="relative 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 hubs..." 
              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>
        </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 tracking-wider">Hub Name</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Address</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Phone</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Manager</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Bikes</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Rentals</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Hours</th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</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">
              {filteredHubs.map(hub => (
                <tr key={hub.id} className="hover:bg-slate-50 transition-colors">
                  <td className="px-4 py-3">
                    <Link href={`/admin/hub/${hub.id}`} className="flex items-center gap-3 hover:text-accent">
                      <MapPin className="w-5 h-5 text-accent" />
                      <span className="text-sm font-medium text-slate-700">{hub.name}</span>
                    </Link>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm text-slate-600 max-w-[200px] block truncate">{hub.address}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm text-slate-600">{hub.phone}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm text-slate-600">{hub.managerName || '-'}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm font-medium text-slate-700">{hub.bikeCount}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm font-medium text-amber-700">{hub.activeRentals}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-sm text-slate-600">{hub.openTime} - {hub.closeTime}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-medium px-2.5 py-1 rounded-full ${
                      hub.status === 'active' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'
                    }`}>
                      {hub.status}
                    </span>
                    {hub.isHeadOffice && (
                      <span className="ml-2 text-xs font-medium px-2 py-1 rounded-full bg-purple-100 text-purple-700">
                        Head Office
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1">
                      <Link href={`/admin/hub/${hub.id}`} className="p-2 hover:bg-slate-100 rounded-lg">
                        <Eye className="w-4 h-4 text-slate-400" />
                      </Link>
                      <button onClick={() => openEdit(hub)} className="p-2 hover:bg-slate-100 rounded-lg">
                        <Edit className="w-4 h-4 text-slate-400" />
                      </button>
                      <button onClick={() => handleDelete(hub.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-md">
            <div className="p-4 border-b border-slate-100 flex justify-between items-center">
              <h3 className="font-semibold text-slate-800">{editingHub ? 'Edit Hub' : 'Add New Hub'}</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">Hub 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="Gulshan Hub"
                />
              </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>
                <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>
                <label className="text-sm text-slate-600">Manager Name</label>
                <input
                  type="text"
                  value={formData.managerName}
                  onChange={(e) => setFormData({ ...formData, managerName: e.target.value })}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  placeholder="Manager name"
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="text-sm text-slate-600">Open Time</label>
                  <input
                    type="time"
                    value={formData.openTime}
                    onChange={(e) => setFormData({ ...formData, openTime: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm text-slate-600">Close Time</label>
                  <input
                    type="time"
                    value={formData.closeTime}
                    onChange={(e) => setFormData({ ...formData, closeTime: e.target.value })}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg text-sm mt-1"
                  />
                </div>
                <div className="flex items-center gap-2 mt-3">
                  <input
                    type="checkbox"
                    id="isHeadOffice"
                    checked={formData.isHeadOffice}
                    onChange={(e) => setFormData({ ...formData, isHeadOffice: e.target.checked })}
                    className="w-4 h-4 text-accent rounded"
                  />
                  <label htmlFor="isHeadOffice" className="text-sm text-slate-600">Set as Head Office</label>
                </div>
              </div>
            </div>
            <div className="p-4 border-t border-slate-100 flex justify-end gap-2">
              <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}
                className="px-4 py-2 bg-accent text-white rounded-lg text-sm disabled:opacity-50"
              >
                {editingHub ? 'Update' : 'Create'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}