'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Search, Plus, Edit, Trash2, Building2, Star, Phone, Mail,
  MapPin, Grid, List, Wrench, ChevronRight, X, Save,
  AlertCircle, ExternalLink, Globe
} from 'lucide-react';
import Link from 'next/link';

// Interface for Service Center data
export interface ServiceCenter {
  id: string;
  name: string;
  address: string;
  googleMapLink: string;
  phone: string;
  email: string;
  rating: number;
  capacity: number;      // Maximum repair slots
  staffCount: number;    // Number of technicians
  specialization: string[];
  status: 'active' | 'inactive' | 'busy';
  activeRepairs: number; // Current repairs in progress
  latitude: number;
  longitude: number;
}

const DEFAULT_CENTERS: ServiceCenter[] = [
  {
    id: 'SC-001',
    name: 'Service Center A',
    address: 'House 45, Road 13, Gulshan 1, Dhaka',
    googleMapLink: 'https://maps.google.com/?q=House+45+Road+13+Gulshan+1+Dhaka',
    phone: '+8801712345670',
    email: 'service.a@jaiben.com',
    rating: 4.8,
    capacity: 20,
    staffCount: 8,
    specialization: ['Battery diagnostics', 'Motor Repair', 'Heavy Mechanical', 'Brake Calibration'],
    status: 'busy',
    activeRepairs: 14,
    latitude: 23.777176,
    longitude: 90.405537
  },
  {
    id: 'SC-002',
    name: 'Service Center B',
    address: 'Road 11, Banani, Dhaka',
    googleMapLink: 'https://maps.google.com/?q=Road+11+Banani+Dhaka',
    phone: '+8801712345671',
    email: 'service.b@jaiben.com',
    rating: 4.5,
    capacity: 15,
    staffCount: 5,
    specialization: ['Battery Swap', 'General Tuning', 'Fast Charging', 'Wiring Fixes'],
    status: 'active',
    activeRepairs: 7,
    latitude: 23.7937,
    longitude: 90.4066
  },
  {
    id: 'SC-003',
    name: 'Authorized Service Center',
    address: 'Sector 3, Uttara, Dhaka',
    googleMapLink: 'https://maps.google.com/?q=Sector+3+Uttara+Dhaka',
    phone: '+8801712345672',
    email: 'auth.service@jaiben.com',
    rating: 4.2,
    capacity: 12,
    staffCount: 4,
    specialization: ['Routine Inspections', 'Tire Replacement', 'Software Updates', 'Brake Tuning'],
    status: 'inactive',
    activeRepairs: 0,
    latitude: 23.8759,
    longitude: 90.3996
  },
  {
    id: 'SC-004',
    name: 'JAIBEN Service Center - Gulshan',
    address: 'Gulshan Link Road, Dhaka',
    googleMapLink: 'https://maps.google.com/?q=Gulshan+Link+Road+Dhaka',
    phone: '+8801712345673',
    email: 'gulshan.hub@jaiben.com',
    rating: 4.6,
    capacity: 25,
    staffCount: 10,
    specialization: ['Heavy Mechanical', 'Chassis Alignment', 'Suspension Rebuild', 'Motor Overhaul'],
    status: 'active',
    activeRepairs: 18,
    latitude: 23.7725,
    longitude: 90.4088
  },
  {
    id: 'SC-005',
    name: 'JAIBEN Service Center - Banani',
    address: 'Banani Block E, Dhaka',
    googleMapLink: 'https://maps.google.com/?q=Banani+Block+E+Dhaka',
    phone: '+8801712345674',
    email: 'banani.hub@jaiben.com',
    rating: 4.7,
    capacity: 18,
    staffCount: 7,
    specialization: ['Battery Diagnostics', 'Cosmetic Repairs', 'Standard Maintenance'],
    status: 'active',
    activeRepairs: 9,
    latitude: 23.7915,
    longitude: 90.4022
  }
];

const ALL_SPECIALIZATIONS = [
  'Battery Swap',
  'Battery diagnostics',
  'Motor Repair',
  'Motor Overhaul',
  'Heavy Mechanical',
  'Brake Calibration',
  'Brake Tuning',
  'General Tuning',
  'Fast Charging',
  'Wiring Fixes',
  'Routine Inspections',
  'Tire Replacement',
  'Software Updates',
  'Chassis Alignment',
  'Suspension Rebuild',
  'Cosmetic Repairs',
  'Standard Maintenance'
];

export default function ServiceCentersDashboard() {
  const router = useRouter();
  const [isMounted, setIsMounted] = useState(false);
  const [centers, setCenters] = useState<ServiceCenter[]>([]);
  
  // Filtering & View states
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [specFilter, setSpecFilter] = useState('all');
  const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid');

  // Modals state
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedCenter, setSelectedCenter] = useState<ServiceCenter | null>(null);

  // Form states
  const [formData, setFormData] = useState({
    name: '',
    address: '',
    googleMapLink: '',
    phone: '',
    email: '',
    capacity: 15,
    staffCount: 5,
    specializations: [] as string[],
    status: 'active' as 'active' | 'inactive' | 'busy',
    activeRepairs: 0,
    rating: 5.0,
    latitude: 23.7771,
    longitude: 90.4055
  });

  // Fetch initial data
  useEffect(() => {
    setIsMounted(true);
    const stored = localStorage.getItem('jaiben_service_centers');
    if (stored) {
      try {
        setCenters(JSON.parse(stored));
      } catch (e) {
        setCenters(DEFAULT_CENTERS);
      }
    } else {
      localStorage.setItem('jaiben_service_centers', JSON.stringify(DEFAULT_CENTERS));
      setCenters(DEFAULT_CENTERS);
    }
  }, []);

  const saveToLocalStorage = (updatedCenters: ServiceCenter[]) => {
    localStorage.setItem('jaiben_service_centers', JSON.stringify(updatedCenters));
    setCenters(updatedCenters);
  };

  if (!isMounted) return null;

  // Filter Centers
  const filteredCenters = centers.filter(c => {
    const matchesSearch = c.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      c.address.toLowerCase().includes(searchQuery.toLowerCase()) ||
      c.phone.includes(searchQuery) ||
      c.id.toLowerCase().includes(searchQuery.toLowerCase());
    
    const matchesStatus = statusFilter === 'all' || c.status === statusFilter;
    const matchesSpec = specFilter === 'all' || c.specialization.some(s => s.toLowerCase() === specFilter.toLowerCase());
    
    return matchesSearch && matchesStatus && matchesSpec;
  });

  // Calculate Statistics (Aligned to Clean and simple parameters)
  const stats = {
    totalCenters: centers.length,
    totalCapacity: centers.reduce((sum, c) => sum + c.capacity, 0),
    totalStaff: centers.reduce((sum, c) => sum + c.staffCount, 0),
    avgRating: centers.length > 0 ? (centers.reduce((sum, c) => sum + c.rating, 0) / centers.length).toFixed(1) : '0.0'
  };

  // Create Center handler
  const handleCreate = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.name.trim() || !formData.address.trim()) return;

    const newId = `SC-${String(centers.length + 1).padStart(3, '0')}`;
    const newCenter: ServiceCenter = {
      id: newId,
      name: formData.name,
      address: formData.address,
      googleMapLink: formData.googleMapLink || `https://maps.google.com/?q=${encodeURIComponent(formData.name + ' ' + formData.address)}`,
      phone: formData.phone || '+8801700000000',
      email: formData.email || 'info@jaiben.com',
      rating: formData.rating,
      capacity: Number(formData.capacity) || 10,
      staffCount: Number(formData.staffCount) || 3,
      specialization: formData.specializations.length > 0 ? formData.specializations : ['General Tuning'],
      status: formData.status,
      activeRepairs: Number(formData.activeRepairs) || 0,
      latitude: formData.latitude,
      longitude: formData.longitude
    };

    const updated = [...centers, newCenter];
    saveToLocalStorage(updated);
    
    // Reset Form & Close Modal
    setFormData({
      name: '',
      address: '',
      googleMapLink: '',
      phone: '',
      email: '',
      capacity: 15,
      staffCount: 5,
      specializations: [],
      status: 'active',
      activeRepairs: 0,
      rating: 5.0,
      latitude: 23.7771,
      longitude: 90.4055
    });
    setShowAddModal(false);
  };

  // Edit Click Handler
  const handleEditClick = (c: ServiceCenter) => {
    setSelectedCenter(c);
    setFormData({
      name: c.name,
      address: c.address,
      googleMapLink: c.googleMapLink || '',
      phone: c.phone,
      email: c.email,
      capacity: c.capacity,
      staffCount: c.staffCount,
      specializations: c.specialization,
      status: c.status,
      activeRepairs: c.activeRepairs,
      rating: c.rating,
      latitude: c.latitude,
      longitude: c.longitude
    });
    setShowEditModal(true);
  };

  // Update Center handler
  const handleUpdate = (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedCenter) return;

    const updated = centers.map(c => {
      if (c.id === selectedCenter.id) {
        return {
          ...c,
          name: formData.name,
          address: formData.address,
          googleMapLink: formData.googleMapLink || `https://maps.google.com/?q=${encodeURIComponent(formData.name + ' ' + formData.address)}`,
          phone: formData.phone,
          email: formData.email,
          capacity: Number(formData.capacity),
          staffCount: Number(formData.staffCount),
          specialization: formData.specializations.length > 0 ? formData.specializations : ['General Tuning'],
          status: formData.status,
          activeRepairs: Number(formData.activeRepairs),
          rating: formData.rating,
          latitude: formData.latitude,
          longitude: formData.longitude
        };
      }
      return c;
    });

    saveToLocalStorage(updated);
    setShowEditModal(false);
    setSelectedCenter(null);
  };

  // Delete handler
  const handleDelete = () => {
    if (!selectedCenter) return;
    const updated = centers.filter(c => c.id !== selectedCenter.id);
    saveToLocalStorage(updated);
    setShowDeleteModal(false);
    setSelectedCenter(null);
  };

  // Specialization checkbox toggling helper
  const handleSpecToggle = (spec: string) => {
    if (formData.specializations.includes(spec)) {
      setFormData({
        ...formData,
        specializations: formData.specializations.filter(s => s !== spec)
      });
    } else {
      setFormData({
        ...formData,
        specializations: [...formData.specializations, spec]
      });
    }
  };

  const statusColors = {
    active: 'bg-emerald-100 text-emerald-700',
    busy: 'bg-amber-100 text-amber-700',
    inactive: 'bg-slate-100 text-slate-700'
  };

  return (
    <div className="p-4 lg:p-6 mb-6 lg:mb-0 space-y-6">
      
      {/* Header aligned like other pages */}
      <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">Service Centers</h1>
          <p className="text-sm text-slate-500 mt-1">Configure and manage EV bikes & battery repair nodes across Dhaka city</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setShowAddModal(true)}
            className="py-2 px-4 bg-accent hover:bg-accent-dark text-white rounded-lg text-sm font-medium flex items-center gap-2 transition-colors duration-200"
          >
            <Plus className="w-4 h-4" /> Register Service Center
          </button>
        </div>
      </div>

      {/* Stats Cards - aligned to style of maintenance page */}
      <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 flex items-center gap-3">
          <div className="w-12 h-12 rounded-xl bg-slate-50 flex items-center justify-center">
            <Building2 className="w-6 h-6 text-slate-600" />
          </div>
          <div>
            <p className="text-2xl font-extrabold text-slate-800">{stats.totalCenters}</p>
            <p className="text-xs text-slate-500 font-medium">Total Centers</p>
          </div>
        </div>

        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100 flex items-center gap-3">
          <div className="w-12 h-12 rounded-xl bg-indigo-50 flex items-center justify-center">
            <Wrench className="w-6 h-6 text-indigo-600" />
          </div>
          <div>
            <p className="text-2xl font-extrabold text-slate-800">{stats.totalCapacity}</p>
            <p className="text-xs text-slate-500 font-medium">Total Capacity</p>
          </div>
        </div>

        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100 flex items-center gap-3">
          <div className="w-12 h-12 rounded-xl bg-emerald-50 flex items-center justify-center">
            <Globe className="w-6 h-6 text-emerald-600" />
          </div>
          <div>
            <p className="text-2xl font-extrabold text-slate-800">{stats.totalStaff}</p>
            <p className="text-xs text-slate-500 font-medium">Technicians</p>
          </div>
        </div>

        <div className="bg-white rounded-xl p-5 shadow-sm border border-slate-100 flex items-center gap-3">
          <div className="w-12 h-12 rounded-xl bg-yellow-50 flex items-center justify-center">
            <Star className="w-6 h-6 text-yellow-500 fill-yellow-500" />
          </div>
          <div>
            <p className="text-2xl font-extrabold text-slate-800">{stats.avgRating}</p>
            <p className="text-xs text-slate-500 font-medium">Average Rating</p>
          </div>
        </div>

      </div>

      {/* Filter and View Toggle Panel - clean, identical spacing and roundings */}
      <div className="bg-white rounded-xl p-4 border border-slate-100 shadow-sm flex flex-col md:flex-row md:items-center justify-between gap-4">
        
        {/* Search */}
        <div className="relative flex-1 max-w-md">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search by ID, name, location, phone..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-9 pr-4 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
          />
        </div>

        {/* Filters */}
        <div className="flex flex-wrap items-center gap-3">
          
          <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 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
          >
            <option value="all">All Statuses</option>
            <option value="active">Active</option>
            <option value="busy">Busy</option>
            <option value="inactive">Inactive</option>
          </select>

          <select
            value={specFilter}
            onChange={(e) => setSpecFilter(e.target.value)}
            className="py-2 px-3 border border-slate-200 rounded-lg text-sm font-medium text-slate-600 bg-white focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all max-w-[180px]"
          >
            <option value="all">All Specializations</option>
            {ALL_SPECIALIZATIONS.map(spec => (
              <option key={spec} value={spec}>{spec}</option>
            ))}
          </select>

          {/* View mode toggle */}
          <div className="bg-slate-100 p-1 rounded-lg flex items-center border border-slate-200/40">
            <button
              onClick={() => setViewMode('grid')}
              className={`p-1.5 rounded-md transition-all ${viewMode === 'grid' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}
              title="Grid View"
            >
              <Grid className="w-4 h-4" />
            </button>
            <button
              onClick={() => setViewMode('table')}
              className={`p-1.5 rounded-md transition-all ${viewMode === 'table' ? 'bg-white text-indigo-600 shadow-sm' : 'text-slate-400 hover:text-slate-600'}`}
              title="Table View"
            >
              <List className="w-4 h-4" />
            </button>
          </div>

        </div>

      </div>

      {/* Main Listing Section */}
      {filteredCenters.length === 0 ? (
        <div className="bg-white rounded-xl p-12 border border-slate-100 shadow-sm text-center">
          <Building2 className="w-12 h-12 text-slate-300 mx-auto mb-4" />
          <h3 className="text-lg font-bold text-slate-700">No service centers found</h3>
          <p className="text-sm text-slate-400 mt-1">Try adjusting your filters or search options</p>
        </div>
      ) : viewMode === 'grid' ? (
        
        // GRID VIEW - Standard rounded-xl styles, matches maintenance records
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredCenters.map(center => {
            return (
              <div
                key={center.id}
                className="bg-white rounded-xl border border-slate-100 shadow-sm overflow-hidden flex flex-col group hover:shadow transition-shadow duration-300 relative"
              >
                
                <div className="p-5 flex-1 space-y-4">
                  
                  <div className="flex items-start justify-between gap-2">
                    <div className="space-y-1">
                      <span className="text-[10px] font-extrabold text-indigo-500 uppercase tracking-widest bg-indigo-50 px-2 py-0.5 rounded">
                        {center.id}
                      </span>
                      <h3 className="font-extrabold text-slate-800 text-base leading-tight group-hover:text-accent transition-colors">
                        {center.name}
                      </h3>
                    </div>

                    <span className={`px-2.5 py-1 text-xs font-semibold rounded-full border ${statusColors[center.status]}`}>
                      {center.status}
                    </span>
                  </div>

                  {/* Rating / Technicians / Address */}
                  <div className="space-y-2 text-sm text-slate-500">
                    <div className="flex items-center gap-1.5 text-yellow-500 font-semibold text-xs">
                      <Star className="w-3.5 h-3.5 fill-yellow-500" />
                      <span>{center.rating.toFixed(1)}</span>
                      <span className="text-slate-300">|</span>
                      <span className="text-slate-400 font-normal">{center.staffCount} Technicians</span>
                    </div>

                    <p className="flex items-start gap-1.5 text-xs text-slate-500 min-h-[32px] line-clamp-2">
                      <MapPin className="w-3.5 h-3.5 text-slate-300 flex-shrink-0 mt-0.5" />
                      <span className="flex-1">{center.address}</span>
                    </p>

                    {/* Google Map Link display in cards */}
                    {center.googleMapLink && (
                      <a
                        href={center.googleMapLink}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-flex items-center gap-1 text-[11px] font-bold text-accent hover:text-accent-dark transition-colors pt-1"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <MapPin className="w-3 h-3 text-accent" /> Google Maps Link <ExternalLink className="w-2.5 h-2.5" />
                      </a>
                    )}
                  </div>

                  {/* Specializations Tag List */}
                  <div className="flex flex-wrap gap-1 pt-1">
                    {center.specialization.slice(0, 3).map((spec) => (
                      <span key={spec} className="px-2 py-0.5 bg-slate-50 border border-slate-100 text-slate-600 text-[10px] font-bold rounded">
                        {spec}
                      </span>
                    ))}
                    {center.specialization.length > 3 && (
                      <span className="px-2 py-0.5 bg-slate-100 border border-slate-200/60 text-slate-500 text-[10px] font-bold rounded">
                        +{center.specialization.length - 3} more
                      </span>
                    )}
                  </div>

                </div>

                {/* Footer buttons */}
                <div className="p-4 border-t border-slate-50 bg-slate-50/50 flex items-center justify-between">
                  <div className="flex items-center gap-1.5">
                    <button
                      onClick={() => handleEditClick(center)}
                      className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-all"
                      title="Edit Service Center"
                    >
                      <Edit className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => { setSelectedCenter(center); setShowDeleteModal(true); }}
                      className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
                      title="Delete Service Center"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>

                  <Link
                    href={`/admin/service-centers/${center.id}`}
                    className="flex items-center gap-1 text-xs font-bold text-accent hover:text-accent-dark group/btn"
                  >
                    <span>View Profile</span>
                    <ChevronRight className="w-3.5 h-3.5 transform group-hover/btn:translate-x-0.5 transition-transform" />
                  </Link>
                </div>

              </div>
            );
          })}
        </div>
      ) : (
        
        // TABLE VIEW
        <div className="bg-white border border-slate-100 rounded-xl shadow-sm overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left border-collapse">
              <thead>
                <tr className="bg-slate-50 border-b border-slate-100 text-xs font-semibold uppercase tracking-wider text-slate-500">
                  <th className="py-3 px-4">ID</th>
                  <th className="py-3 px-4">Name & Location</th>
                  <th className="py-3 px-4">Specializations</th>
                  <th className="py-3 px-4 text-center">Status</th>
                  <th className="py-3 px-4 text-center">Technicians</th>
                  <th className="py-3 px-4 text-center">Rating</th>
                  <th className="py-3 px-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100 text-sm text-slate-700">
                {filteredCenters.map(center => {
                  return (
                    <tr key={center.id} className="hover:bg-slate-50/70 transition-colors">
                      <td className="py-3 px-4 font-bold text-slate-400">{center.id}</td>
                      <td className="py-3 px-4">
                        <div className="space-y-1">
                          <Link href={`/admin/service-centers/${center.id}`} className="font-extrabold text-slate-800 hover:text-accent">
                            {center.name}
                          </Link>
                          <div className="flex items-center flex-wrap gap-x-2 gap-y-1 text-xs text-slate-400">
                            <span className="flex items-center gap-1">
                              <MapPin className="w-3 h-3 text-slate-300" /> {center.address}
                            </span>
                            {center.googleMapLink && (
                              <>
                                <span className="text-slate-300">|</span>
                                <a
                                  href={center.googleMapLink}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                  className="text-accent hover:underline flex items-center gap-0.5"
                                >
                                  Map Link <ExternalLink className="w-2.5 h-2.5" />
                                </a>
                              </>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="flex flex-wrap gap-1 max-w-[280px]">
                          {center.specialization.slice(0, 2).map(spec => (
                            <span key={spec} className="px-2 py-0.5 bg-slate-100 text-slate-600 text-[10px] font-bold rounded">
                              {spec}
                            </span>
                          ))}
                          {center.specialization.length > 2 && (
                            <span className="px-2 py-0.5 bg-indigo-50 text-indigo-600 text-[10px] font-bold rounded">
                              +{center.specialization.length - 2} more
                            </span>
                          )}
                        </div>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <span className={`px-2 py-0.5 text-xs font-semibold rounded-full border inline-block ${statusColors[center.status]}`}>
                          {center.status}
                        </span>
                      </td>
                      <td className="py-3 px-4 text-center font-medium text-slate-700">
                        {center.staffCount}
                      </td>
                      <td className="py-3 px-4 text-center">
                        <div className="flex items-center justify-center gap-1 text-xs font-bold text-yellow-500">
                           <Star className="w-3.5 h-3.5 fill-yellow-500" />
                          <span>{center.rating.toFixed(1)}</span>
                        </div>
                      </td>
                      <td className="py-3 px-4 text-right">
                        <div className="flex items-center justify-end gap-1">
                          <button
                            onClick={() => handleEditClick(center)}
                            className="p-1.5 hover:bg-slate-100 text-slate-400 hover:text-slate-600 rounded-lg transition-colors"
                            title="Edit"
                          >
                            <Edit className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => { setSelectedCenter(center); setShowDeleteModal(true); }}
                            className="p-1.5 hover:bg-red-50 text-slate-400 hover:text-red-600 rounded-lg transition-colors"
                            title="Delete"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                          <Link
                            href={`/admin/service-centers/${center.id}`}
                            className="p-1.5 hover:bg-indigo-50 text-slate-400 hover:text-accent rounded-lg transition-colors"
                            title="View Profile"
                          >
                            <ChevronRight className="w-4 h-4" />
                          </Link>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

      )}

      {/* REGISTER/CREATE MODAL - aligned design like maintenance form modals */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm 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 animate-fadeIn">
            
            <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Building2 className="w-5 h-5 text-slate-600" />
                <h3 className="font-extrabold text-slate-800 text-lg">Register Service Center</h3>
              </div>
              <button
                onClick={() => setShowAddModal(false)}
                className="p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleCreate} className="p-6 space-y-4 overflow-y-auto max-h-[75vh]">
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                
                <div className="col-span-1 md:col-span-2">
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Center Name *</label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. JAIBEN Service Center - Uttara"
                    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 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
                  />
                </div>

                <div className="col-span-1 md:col-span-2">
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Address *</label>
                  <input
                    type="text"
                    required
                    placeholder="e.g. Sector 4, Uttara, Dhaka"
                    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 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
                  />
                </div>

                <div className="col-span-1 md:col-span-2">
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Google Map Link *</label>
                  <input
                    type="url"
                    required
                    placeholder="e.g. https://maps.app.goo.gl/..."
                    value={formData.googleMapLink}
                    onChange={(e) => setFormData({ ...formData, googleMapLink: 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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Phone Number</label>
                  <input
                    type="text"
                    placeholder="e.g. +88017XXXXXXXX"
                    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 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Email Address</label>
                  <input
                    type="email"
                    placeholder="e.g. center@jaiben.com"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: 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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Repair Capacity (Slots) *</label>
                  <input
                    type="number"
                    min="1"
                    required
                    value={formData.capacity}
                    onChange={(e) => setFormData({ ...formData, capacity: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Staff Count (Technicians) *</label>
                  <input
                    type="number"
                    min="1"
                    required
                    value={formData.staffCount}
                    onChange={(e) => setFormData({ ...formData, staffCount: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Status</label>
                  <select
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: 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 focus:border-transparent transition-all bg-white"
                  >
                    <option value="active">Active</option>
                    <option value="busy">Busy</option>
                    <option value="inactive">Inactive</option>
                  </select>
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Rating (Mocked)</label>
                  <input
                    type="number"
                    step="0.1"
                    min="1"
                    max="5"
                    value={formData.rating}
                    onChange={(e) => setFormData({ ...formData, rating: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Latitude</label>
                  <input
                    type="number"
                    step="0.000001"
                    value={formData.latitude}
                    onChange={(e) => setFormData({ ...formData, latitude: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Longitude</label>
                  <input
                    type="number"
                    step="0.000001"
                    value={formData.longitude}
                    onChange={(e) => setFormData({ ...formData, longitude: Number(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 focus:border-transparent transition-all"
                  />
                </div>

              </div>

              {/* Specializations list */}
              <div className="space-y-2">
                <label className="text-xs font-semibold text-slate-600 block">Specializations (Select all that apply)</label>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 bg-slate-50 p-4 rounded-lg border border-slate-100 max-h-48 overflow-y-auto">
                  {ALL_SPECIALIZATIONS.map(spec => (
                    <label key={spec} className="flex items-center gap-2 text-xs text-slate-600 cursor-pointer select-none">
                      <input
                        type="checkbox"
                        checked={formData.specializations.includes(spec)}
                        onChange={() => handleSpecToggle(spec)}
                        className="rounded border-slate-300 text-accent focus:ring-accent"
                      />
                      <span>{spec}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* Action buttons */}
              <div className="pt-4 border-t border-slate-100 flex items-center justify-end gap-2">
                <button
                  type="button"
                  onClick={() => setShowAddModal(false)}
                  className="px-4 py-2 border border-slate-200 text-slate-500 rounded-lg hover:bg-slate-50 text-sm font-semibold transition-all"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-accent text-white rounded-lg hover:bg-accent-dark text-sm font-semibold flex items-center gap-2 transition-all"
                >
                  <Save className="w-4 h-4" /> Save Center
                </button>
              </div>

            </form>
          </div>
        </div>
      )}

      {/* EDIT SERVICE CENTER MODAL - aligned design like maintenance detail forms */}
      {showEditModal && selectedCenter && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm 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 animate-fadeIn">
            
            <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Edit className="w-5 h-5 text-slate-600" />
                <h3 className="font-extrabold text-slate-800 text-lg">Modify Center: {selectedCenter.id}</h3>
              </div>
              <button
                onClick={() => setShowEditModal(false)}
                className="p-1.5 hover:bg-slate-100 rounded-lg transition-colors text-slate-400 hover:text-slate-600"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleUpdate} className="p-6 space-y-4 overflow-y-auto max-h-[75vh]">
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                
                <div className="col-span-1 md:col-span-2">
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Center Name *</label>
                  <input
                    type="text"
                    required
                    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 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
                  />
                </div>

                <div className="col-span-1 md:col-span-2">
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Address *</label>
                  <input
                    type="text"
                    required
                    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 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
                  />
                </div>

                <div className="col-span-1 md:col-span-2">
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Google Map Link *</label>
                  <input
                    type="url"
                    required
                    placeholder="e.g. https://maps.app.goo.gl/..."
                    value={formData.googleMapLink}
                    onChange={(e) => setFormData({ ...formData, googleMapLink: 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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Phone Number</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 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Email Address</label>
                  <input
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: 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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Repair Capacity (Slots) *</label>
                  <input
                    type="number"
                    min="1"
                    required
                    value={formData.capacity}
                    onChange={(e) => setFormData({ ...formData, capacity: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Staff Count (Technicians) *</label>
                  <input
                    type="number"
                    min="1"
                    required
                    value={formData.staffCount}
                    onChange={(e) => setFormData({ ...formData, staffCount: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Status</label>
                  <select
                    value={formData.status}
                    onChange={(e) => setFormData({ ...formData, status: 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 focus:border-transparent transition-all bg-white"
                  >
                    <option value="active">Active</option>
                    <option value="busy">Busy</option>
                    <option value="inactive">Inactive</option>
                  </select>
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Rating</label>
                  <input
                    type="number"
                    step="0.1"
                    min="1"
                    max="5"
                    value={formData.rating}
                    onChange={(e) => setFormData({ ...formData, rating: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Latitude</label>
                  <input
                    type="number"
                    step="0.000001"
                    value={formData.latitude}
                    onChange={(e) => setFormData({ ...formData, latitude: Number(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 focus:border-transparent transition-all"
                  />
                </div>

                <div>
                  <label className="text-xs font-semibold text-slate-600 block mb-1">Longitude</label>
                  <input
                    type="number"
                    step="0.000001"
                    value={formData.longitude}
                    onChange={(e) => setFormData({ ...formData, longitude: Number(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 focus:border-transparent transition-all"
                  />
                </div>

              </div>

              {/* Specializations list */}
              <div className="space-y-2">
                <label className="text-xs font-semibold text-slate-600 block">Specializations</label>
                <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 bg-slate-50 p-4 rounded-lg border border-slate-100 max-h-48 overflow-y-auto">
                  {ALL_SPECIALIZATIONS.map(spec => (
                    <label key={spec} className="flex items-center gap-2 text-xs text-slate-600 cursor-pointer select-none">
                      <input
                        type="checkbox"
                        checked={formData.specializations.includes(spec)}
                        onChange={() => handleSpecToggle(spec)}
                        className="rounded border-slate-300 text-accent focus:ring-accent"
                      />
                      <span>{spec}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* Action buttons */}
              <div className="pt-4 border-t border-slate-100 flex items-center justify-end gap-2">
                <button
                  type="button"
                  onClick={() => setShowEditModal(false)}
                  className="px-4 py-2 border border-slate-200 text-slate-500 rounded-lg hover:bg-slate-50 text-sm font-semibold transition-all"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 bg-accent text-white rounded-lg hover:bg-accent-dark text-sm font-semibold flex items-center gap-2 transition-all"
                >
                  <Save className="w-4 h-4" /> Save Changes
                </button>
              </div>

            </form>
          </div>
        </div>
      )}

      {/* DELETE CONFIRMATION DIALOG - standard modal sizes */}
      {showDeleteModal && selectedCenter && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl shadow-xl w-full max-w-md overflow-hidden animate-fadeIn">
            <div className="p-6 text-center space-y-4">
              <div className="w-14 h-14 bg-red-50 text-red-600 rounded-full flex items-center justify-center mx-auto border border-red-100">
                <AlertCircle className="w-8 h-8" />
              </div>
              <div className="space-y-2">
                <h3 className="text-lg font-extrabold text-slate-800">Deregister Service Center?</h3>
                <p className="text-sm text-slate-500 leading-relaxed">
                  Are you sure you want to delete <span className="font-bold text-slate-700">{selectedCenter.name}</span>?
                  This action is permanent and will remove all local registration data.
                </p>
              </div>
              <div className="pt-4 border-t border-slate-100 flex items-center justify-center gap-2">
                <button
                  onClick={() => setShowDeleteModal(false)}
                  className="flex-1 py-2.5 px-4 border border-slate-200 rounded-lg text-slate-500 text-sm font-semibold hover:bg-slate-50 transition-all"
                >
                  Cancel
                </button>
                <button
                  onClick={handleDelete}
                  className="flex-1 py-2.5 px-4 bg-red-600 text-white rounded-lg text-sm font-semibold hover:bg-red-700 transition-all shadow-sm"
                >
                  Delete Center
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}
