'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { ArrowLeft, Plus, Edit, Trash2, Loader2, X, MapPin } from 'lucide-react';
import toast from 'react-hot-toast';
import { fetchCountry } from '@/lib/services/countries';
import {
  createState,
  deleteState,
  fetchStates,
  updateState,
  type State,
} from '@/lib/services/countries';

type ModalMode = 'create' | 'edit';

export default function AdminStates() {
  const params = useParams();
  const router = useRouter();
  const countryId = params?.id as string;

  const [country, setCountry] = useState<any>(null);
  const [states, setStates] = useState<State[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [modalMode, setModalMode] = useState<ModalMode | null>(null);
  const [selectedState, setSelectedState] = useState<State | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    code: '',
    isActive: true,
    order: '0',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

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

    async function loadData() {
      if (!countryId) {
        setError('Country ID is required');
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      setError(null);

      try {
        const [countryData, statesData] = await Promise.all([
          fetchCountry(countryId),
          fetchStates(countryId),
        ]);

        if (!isMounted) return;

        setCountry(countryData);
        setStates(statesData);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Unable to load country and states');
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadData();

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

  const handleOpenModal = (mode: ModalMode, state?: State) => {
    setModalMode(mode);
    if (mode === 'edit' && state) {
      setSelectedState(state);
      setFormData({
        name: state.name,
        code: state.code || '',
        isActive: state.isActive,
        order: state.order.toString(),
      });
    } else {
      setSelectedState(null);
      setFormData({
        name: '',
        code: '',
        isActive: true,
        order: '0',
      });
    }
  };

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

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

    try {
      setIsSubmitting(true);

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

      if (modalMode === 'create') {
        const newState = await createState(payload);
        setStates((prev) => [...prev, newState].sort((a, b) => a.order - b.order || a.name.localeCompare(b.name)));
        toast.success('State created successfully');
      } else if (modalMode === 'edit' && selectedState) {
        const updatedState = await updateState(selectedState.id, payload);
        setStates((prev) =>
          prev.map((state) => (state.id === selectedState.id ? updatedState : state)).sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))
        );
        toast.success('State updated successfully');
      }

      handleCloseModal();
    } catch (err: any) {
      console.error(err);
      toast.error(err?.message || 'Unable to save state');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async (state: State) => {
    if (!confirm(`Delete state "${state.name}"?`)) {
      return;
    }

    try {
      await deleteState(state.id);
      setStates((prev) => prev.filter((s) => s.id !== state.id));
      toast.success('State deleted successfully');
    } catch (err: any) {
      console.error(err);
      toast.error(err?.message || 'Unable to delete state');
    }
  };

  const toggleActive = async (state: State) => {
    try {
      const updatedState = await updateState(state.id, {
        isActive: !state.isActive,
      });
      setStates((prev) =>
        prev.map((s) => (s.id === state.id ? updatedState : s))
      );
      toast.success(`State ${updatedState.isActive ? 'enabled' : 'disabled'}`);
    } catch (err) {
      console.error(err);
      toast.error('Unable to update state');
    }
  };

  if (isLoading) {
    return (
      <div className="flex h-64 items-center justify-center text-gray-500">
        <Loader2 className="mr-2 h-5 w-5 animate-spin" />
        Loading states…
      </div>
    );
  }

  if (!country) {
    return (
      <div className="space-y-6">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 text-center">
          <h2 className="text-xl font-semibold text-gray-900 mb-2">{error ?? 'Country Not Found'}</h2>
          <Link
            href="/admin/countries"
            className="inline-block bg-gray-900 text-white px-6 py-2 rounded-lg hover:bg-gray-800 transition-colors mt-4"
          >
            Back to Countries
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/admin/countries" className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-3xl font-bold text-gray-900">States for {country.name}</h1>
          <p className="text-gray-600 mt-1">Manage states/provinces for this country</p>
        </div>
      </div>

      <div className="flex items-center justify-end">
        <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 State
        </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">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">
            {states.length === 0 ? (
              <tr>
                <td colSpan={5} className="px-6 py-12 text-center text-sm text-gray-500">
                  <MapPin className="w-12 h-12 text-gray-400 mx-auto mb-4" />
                  <p>No states found for this country.</p>
                </td>
              </tr>
            ) : (
              states.map((state) => (
                <tr key={state.id} className={state.isActive ? '' : 'opacity-60'}>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{state.name}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-500">{state.code || '—'}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-gray-500">{state.order}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <button
                      onClick={() => toggleActive(state)}
                      className={`px-3 py-1 rounded-full text-xs font-medium ${
                        state.isActive
                          ? 'bg-green-100 text-green-800 hover:bg-green-200'
                          : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                      }`}
                    >
                      {state.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', state)}
                        className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(state)}
                        className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded"
                      >
                        <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 State' : 'Edit State'}
              </h2>
              <button
                onClick={handleCloseModal}
                className="p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">State Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g., California"
                  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">State Code (optional)</label>
                <input
                  type="text"
                  value={formData.code}
                  onChange={(e) => setFormData((prev) => ({ ...prev, code: e.target.value.toUpperCase() }))}
                  placeholder="e.g., CA"
                  maxLength={10}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent uppercase"
                />
              </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"
                />
              </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 State'
                ) : (
                  'Update State'
                )}
              </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>
  );
}

