'use client';

import { useEffect, useState } from 'react';
import { Plus, Edit, Trash2, Loader2, Globe, ChevronRight } from 'lucide-react';
import toast from 'react-hot-toast';
import Link from 'next/link';
import {
  createCountry,
  deleteCountry,
  fetchCountries,
  updateCountry,
  type Country,
} from '@/lib/services/countries';

type ModalMode = 'create' | 'edit';

export default function AdminCountries() {
  const [countries, setCountries] = useState<Country[]>([]);
  const [modalMode, setModalMode] = useState<ModalMode | null>(null);
  const [selectedCountry, setSelectedCountry] = useState<Country | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    isActive: true,
    order: '0',
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let isMounted = true;

    async function loadCountries() {
      try {
        setIsLoading(true);
        setError(null);
        const data = await fetchCountries();
        if (!isMounted) return;
        setCountries(data);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Unable to load countries');
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadCountries();

    return () => {
      isMounted = false;
    };
  }, []);

  const handleOpenModal = (mode: ModalMode, country?: Country) => {
    setModalMode(mode);
    if (mode === 'edit' && country) {
      setSelectedCountry(country);
      setFormData({
        name: country.name,
        code: country.code,
        isActive: country.isActive,
        order: country.order.toString(),
      });
    } else {
      setSelectedCountry(null);
      setFormData({
        name: '',
        code: '',
        isActive: true,
        order: '0',
      });
    }
    setError(null);
  };

  const handleCloseModal = () => {
    setModalMode(null);
    setSelectedCountry(null);
    setFormData({
      name: '',
      code: '',
      isActive: true,
      order: '0',
    });
    setError(null);
  };

  const handleSubmit = async () => {
    if (!formData.name.trim()) {
      setError('Country name is required');
      toast.error('Country name is required');
      return;
    }

    if (!formData.code.trim()) {
      setError('Country code is required');
      toast.error('Country code is required');
      return;
    }

    try {
      setIsSubmitting(true);
      setError(null);

      const payload = {
        name: formData.name.trim(),
        code: formData.code.trim().toUpperCase(),
        isActive: formData.isActive,
        order: Number.parseInt(formData.order, 10) || 0,
      };

      if (modalMode === 'create') {
        const newCountry = await createCountry(payload);
        setCountries((prev) => [...prev, newCountry].sort((a, b) => a.order - b.order || a.name.localeCompare(b.name)));
        toast.success('Country created successfully');
      } else if (modalMode === 'edit' && selectedCountry) {
        const updatedCountry = await updateCountry(selectedCountry.id, payload);
        setCountries((prev) =>
          prev.map((country) => (country.id === selectedCountry.id ? updatedCountry : country)).sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))
        );
        toast.success('Country updated successfully');
      }

      handleCloseModal();
    } catch (err: any) {
      console.error(err);
      const errorMessage = err?.message || 'Unable to save country. Please try again.';
      setError(errorMessage);
      toast.error(errorMessage);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async (country: Country) => {
    if (country.states && country.states.length > 0) {
      toast.error('Cannot delete country with existing states. Please delete all states first.');
      return;
    }

    if (!confirm(`Delete country "${country.name}"?`)) {
      return;
    }

    try {
      await deleteCountry(country.id);
      setCountries((prev) => prev.filter((item) => item.id !== country.id));
      toast.success('Country deleted successfully');
    } catch (err: any) {
      console.error(err);
      const errorMessage = err?.message || 'Unable to delete country.';
      setError(errorMessage);
      toast.error(errorMessage);
    }
  };

  const toggleActive = async (country: Country) => {
    try {
      const updatedCountry = await updateCountry(country.id, {
        isActive: !country.isActive,
      });
      setCountries((prev) =>
        prev.map((c) => (c.id === country.id ? updatedCountry : c))
      );
      toast.success(`Country ${updatedCountry.isActive ? 'enabled' : 'disabled'}`);
    } catch (err) {
      console.error(err);
      toast.error('Unable to update country.');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Countries</h1>
          <p className="text-gray-600 mt-1">Manage countries and their states</p>
          {error && <p className="mt-2 text-sm text-red-600">{error}</p>}
        </div>
        <button
          onClick={() => handleOpenModal('create')}
          className="flex items-center gap-2 bg-gray-900 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition-colors"
        >
          <Plus className="w-5 h-5" />
          Add Country
        </button>
      </div>

      <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Code</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">States</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Order</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
              <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
            </tr>
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {isLoading ? (
              <tr>
                <td colSpan={6} className="px-6 py-12 text-center">
                  <Loader2 className="w-6 h-6 animate-spin mx-auto text-gray-400" />
                </td>
              </tr>
            ) : countries.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-6 py-12 text-center text-sm text-gray-500">
                  <Globe className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                  <p>No countries found.</p>
                </td>
              </tr>
            ) : (
              countries.map((country) => (
                <tr key={country.id} className={country.isActive ? '' : 'opacity-60'}>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{country.name}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-500">{country.code}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <Link
                      href={`/admin/countries/${country.id}/states`}
                      className="flex items-center gap-2 text-sm text-gray-900 hover:text-gray-600"
                    >
                      <span>{country.states?.length || 0} state{(country.states?.length || 0) !== 1 ? 's' : ''}</span>
                      <ChevronRight className="w-4 h-4" />
                    </Link>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-500">{country.order}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <button
                      onClick={() => toggleActive(country)}
                      className={`px-3 py-1 rounded-full text-xs font-medium ${
                        country.isActive
                          ? 'bg-green-100 text-green-800 hover:bg-green-200'
                          : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                      }`}
                    >
                      {country.isActive ? 'Active' : 'Inactive'}
                    </button>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => handleOpenModal('edit', country)}
                        className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded"
                        aria-label={`Edit ${country.name}`}
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(country)}
                        disabled={(country.states?.length || 0) > 0}
                        className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded disabled:opacity-50 disabled:cursor-not-allowed"
                        aria-label={`Delete ${country.name}`}
                        title={(country.states?.length || 0) > 0 ? 'Cannot delete country with states' : 'Delete country'}
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {modalMode && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-md w-full p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-2xl font-bold text-gray-900">
                {modalMode === 'create' ? 'Add New Country' : 'Edit Country'}
              </h2>
            </div>
            {error && (
              <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
                {error}
              </div>
            )}
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Country Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g., United States"
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Country Code *</label>
                <input
                  type="text"
                  value={formData.code}
                  onChange={(e) => setFormData((prev) => ({ ...prev, code: e.target.value.toUpperCase() }))}
                  placeholder="e.g., US"
                  maxLength={3}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent uppercase"
                />
                <p className="mt-1 text-xs text-gray-500">ISO country code (2-3 characters, e.g., US, PK, UK)</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Display Order</label>
                <input
                  type="number"
                  value={formData.order}
                  onChange={(e) => setFormData((prev) => ({ ...prev, order: e.target.value }))}
                  placeholder="0"
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                />
                <p className="mt-1 text-xs text-gray-500">Lower numbers appear first</p>
              </div>
              <div className="flex items-center">
                <input
                  type="checkbox"
                  id="isActive"
                  checked={formData.isActive}
                  onChange={(e) => setFormData((prev) => ({ ...prev, isActive: e.target.checked }))}
                  className="w-4 h-4 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
                />
                <label htmlFor="isActive" className="ml-2 text-sm text-gray-700">
                  Active
                </label>
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button
                onClick={handleSubmit}
                disabled={isSubmitting}
                className="flex-1 bg-gray-900 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
              >
                {isSubmitting ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin inline mr-2" />
                    Saving...
                  </>
                ) : modalMode === 'create' ? (
                  'Add Country'
                ) : (
                  'Update Country'
                )}
              </button>
              <button
                onClick={handleCloseModal}
                disabled={isSubmitting}
                className="flex-1 bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

