'use client';

import { useEffect, useState } from 'react';
import { Plus, Edit, Trash2, Loader2, Package } from 'lucide-react';
import toast from 'react-hot-toast';
import Link from 'next/link';
import {
  createShippingMethod,
  deleteShippingMethod,
  fetchShippingMethods,
  updateShippingMethod,
  type ShippingMethod,
} from '@/lib/services/shipping-methods';
import {
  fetchShippingRegions,
  updateShippingRegions,
  type ShippingRegion,
} from '@/lib/services/shipping-regions';
import {
  fetchCountries,
  fetchStates,
  type Country,
  type State,
} from '@/lib/services/countries';

type ModalMode = 'create' | 'edit';

export default function AdminShippingMethods() {
  const [methods, setMethods] = useState<ShippingMethod[]>([]);
  const [modalMode, setModalMode] = useState<ModalMode | null>(null);
  const [selectedMethod, setSelectedMethod] = useState<ShippingMethod | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    isActive: true,
    order: '0',
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [countries, setCountries] = useState<Country[]>([]);
  const [allStates, setAllStates] = useState<State[]>([]);
  const [selectedCountryIds, setSelectedCountryIds] = useState<string[]>([]);
  const [selectedStateIds, setSelectedStateIds] = useState<string[]>([]);
  const [isLoadingRegions, setIsLoadingRegions] = useState(false);

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

    async function loadMethods() {
      try {
        setIsLoading(true);
        setError(null);
        const [methodsData, countriesData, statesData] = await Promise.all([
          fetchShippingMethods(),
          fetchCountries(),
          fetchStates(),
        ]);
        if (!isMounted) return;
        
        setMethods(methodsData);
        // Show all countries and states for region selection (admin needs all options)
        setCountries(countriesData || []);
        setAllStates(statesData || []);
      } catch (err) {
        console.error('Error loading data:', err);
        if (isMounted) {
          setError('Unable to load shipping methods');
        }
        // Set empty arrays on error so modal doesn't break
        setCountries([]);
        setAllStates([]);
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadMethods();

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

  const handleOpenModal = async (mode: ModalMode, method?: ShippingMethod) => {
    // Ensure countries and states are loaded before opening modal
    if (countries.length === 0 || allStates.length === 0) {
      try {
        const [countriesData, statesData] = await Promise.all([
          fetchCountries(),
          fetchStates(),
        ]);
        setCountries(countriesData || []);
        setAllStates(statesData || []);
      } catch (err) {
        console.error('Error loading countries/states:', err);
      }
    }
    
    setModalMode(mode);
    if (mode === 'edit' && method) {
      setSelectedMethod(method);
      setFormData({
        name: method.name,
        description: method.description || '',
        isActive: method.isActive,
        order: method.order.toString(),
      });
      
      // Load regions for editing
      try {
        const regions = await fetchShippingRegions(method.id);
        const countryIds = regions.filter((r) => r.type === 'country' && r.countryId).map((r) => r.countryId!);
        const stateIds = regions.filter((r) => r.type === 'state' && r.stateId).map((r) => r.stateId!);
        setSelectedCountryIds(countryIds);
        setSelectedStateIds(stateIds);
      } catch (err) {
        console.error('Error loading regions:', err);
        setSelectedCountryIds([]);
        setSelectedStateIds([]);
      }
    } else {
      setSelectedMethod(null);
      setFormData({
        name: '',
        description: '',
        isActive: true,
        order: '0',
      });
      setSelectedCountryIds([]);
      setSelectedStateIds([]);
    }
    setError(null);
  };

  const handleCloseModal = () => {
    setModalMode(null);
    setSelectedMethod(null);
    setFormData({
      name: '',
      description: '',
      isActive: true,
      order: '0',
    });
    setSelectedCountryIds([]);
    setSelectedStateIds([]);
    setError(null);
  };

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

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

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

      if (modalMode === 'create') {
        const newMethod = await createShippingMethod(payload);
        
        // Save regions if any are selected
        if (selectedCountryIds.length > 0 || selectedStateIds.length > 0) {
          try {
            const regionsToSave: Array<{
              type: 'country' | 'state';
              countryId?: string;
              stateId?: string;
            }> = [];

            selectedCountryIds.forEach((countryId) => {
              regionsToSave.push({
                type: 'country',
                countryId,
              });
            });

            selectedStateIds.forEach((stateId) => {
              regionsToSave.push({
                type: 'state',
                stateId,
              });
            });

            await updateShippingRegions({
              shippingMethodId: newMethod.id,
              regions: regionsToSave,
            });
          } catch (err) {
            console.error('Error saving regions:', err);
            // Don't fail the whole operation if regions fail
          }
        }
        
        setMethods((prev) => [...prev, newMethod].sort((a, b) => a.order - b.order || a.name.localeCompare(b.name)));
        toast.success('Shipping method created successfully');
      } else if (modalMode === 'edit' && selectedMethod) {
        const updatedMethod = await updateShippingMethod(selectedMethod.id, payload);
        
        // Update regions
        const regionsToSave: Array<{
          type: 'country' | 'state';
          countryId?: string;
          stateId?: string;
        }> = [];

        selectedCountryIds.forEach((countryId) => {
          regionsToSave.push({
            type: 'country',
            countryId,
          });
        });

        selectedStateIds.forEach((stateId) => {
          regionsToSave.push({
            type: 'state',
            stateId,
          });
        });

        await updateShippingRegions({
          shippingMethodId: selectedMethod.id,
          regions: regionsToSave,
        });
        
        setMethods((prev) =>
          prev.map((method) => (method.id === selectedMethod.id ? updatedMethod : method)).sort((a, b) => a.order - b.order || a.name.localeCompare(b.name))
        );
        toast.success('Shipping method updated successfully');
      }

      handleCloseModal();
    } catch (err) {
      console.error(err);
      setError('Unable to save shipping method. Please try again.');
      toast.error('Unable to save shipping method. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async (method: ShippingMethod) => {
    if (method.rules.length > 0) {
      toast.error('Cannot delete shipping method with existing rules. Please delete all rules first.');
      return;
    }

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

    try {
      await deleteShippingMethod(method.id);
      setMethods((prev) => prev.filter((item) => item.id !== method.id));
      toast.success('Shipping method deleted successfully');
    } catch (err) {
      console.error(err);
      setError('Unable to delete shipping method.');
      toast.error('Unable to delete shipping method.');
    }
  };

  const toggleActive = async (method: ShippingMethod) => {
    try {
      const updatedMethod = await updateShippingMethod(method.id, {
        isActive: !method.isActive,
      });
      setMethods((prev) =>
        prev.map((m) => (m.id === method.id ? updatedMethod : m))
      );
      toast.success(`Shipping method ${updatedMethod.isActive ? 'enabled' : 'disabled'}`);
    } catch (err) {
      console.error(err);
      toast.error('Unable to update shipping method.');
    }
  };

  const handleCountryToggle = (countryId: string) => {
    setSelectedCountryIds((prev) => {
      const isCurrentlySelected = prev.includes(countryId);
      
      if (isCurrentlySelected) {
        // Deselect country and all its states
        const statesToRemove = allStates
          .filter((s) => s.countryId === countryId)
          .map((s) => s.id);
        setSelectedStateIds((prevStates) => 
          prevStates.filter((id) => !statesToRemove.includes(id))
        );
        return prev.filter((id) => id !== countryId);
      } else {
        // Select country and all its states
        const statesToAdd = allStates
          .filter((s) => s.countryId === countryId && s.isActive)
          .map((s) => s.id);
        setSelectedStateIds((prevStates) => {
          const newStateIds = [...prevStates];
          statesToAdd.forEach((stateId) => {
            if (!newStateIds.includes(stateId)) {
              newStateIds.push(stateId);
            }
          });
          return newStateIds;
        });
        return [...prev, countryId];
      }
    });
  };

  const handleStateToggle = (stateId: string) => {
    setSelectedStateIds((prev) => {
      if (prev.includes(stateId)) {
        return prev.filter((id) => id !== stateId);
      } else {
        return [...prev, stateId];
      }
    });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Shipping Methods</h1>
          <p className="text-gray-600 mt-1">Manage shipping methods and their rules</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 Method
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {isLoading ? (
          Array.from({ length: 6 }).map((_, index) => (
            <div key={index} className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 animate-pulse">
              <div className="h-6 bg-gray-200 rounded w-2/3 mb-3" />
              <div className="h-4 bg-gray-200 rounded w-full mb-2" />
              <div className="h-4 bg-gray-200 rounded w-1/2" />
            </div>
          ))
        ) : methods.length === 0 ? (
          <div className="col-span-full bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
            <Package className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <p className="text-gray-500 mb-4">No shipping methods found.</p>
            <button
              onClick={() => handleOpenModal('create')}
              className="inline-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" />
              Create First Shipping Method
            </button>
          </div>
        ) : (
          methods.map((method) => (
            <div
              key={method.id}
              className={`bg-white rounded-lg shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow ${
                !method.isActive ? 'opacity-60' : ''
              }`}
            >
              <div className="flex items-start justify-between mb-4">
                <div className="flex-1">
                  <h3 className="text-lg font-semibold text-gray-900 mb-1">{method.name}</h3>
                  {method.description && (
                    <p className="text-sm text-gray-500 mb-2">{method.description}</p>
                  )}
                  <div className="flex items-center gap-4 text-xs text-gray-500">
                    <span>{method.rules.length} rule{method.rules.length !== 1 ? 's' : ''}</span>
                    <span>Order: {method.order}</span>
                  </div>
                </div>
              </div>

              <div className="flex items-center justify-between pt-4 border-t border-gray-200">
                <button
                  onClick={() => toggleActive(method)}
                  className={`px-3 py-1 rounded-full text-xs font-medium ${
                    method.isActive
                      ? 'bg-green-100 text-green-800 hover:bg-green-200'
                      : 'bg-gray-100 text-gray-800 hover:bg-gray-200'
                  }`}
                >
                  {method.isActive ? 'Active' : 'Inactive'}
                </button>
                <div className="flex items-center gap-2">
                  <Link
                    href={`/admin/shipping-methods/${method.id}/edit`}
                    className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded"
                    aria-label={`Edit ${method.name}`}
                  >
                    <Edit className="w-4 h-4" />
                  </Link>
                  <button
                    onClick={() => handleDelete(method)}
                    disabled={method.rules.length > 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 ${method.name}`}
                    title={method.rules.length > 0 ? 'Cannot delete method with rules' : 'Delete method'}
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {modalMode && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 overflow-y-auto">
          <div className="bg-white rounded-lg shadow-xl max-w-2xl w-full p-6 my-8 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-2xl font-bold text-gray-900">
                {modalMode === 'create' ? 'Add New Shipping Method' : 'Edit Shipping Method'}
              </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">Method Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g., Standard Shipping"
                  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">Description</label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData((prev) => ({ ...prev, description: e.target.value }))}
                  rows={3}
                  placeholder="Optional description..."
                  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">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>

              {/* Shipping Regions */}
              <div className="border-t border-gray-200 pt-4 mt-4">
                <label className="block text-sm font-medium text-gray-700 mb-3">Shipping Regions</label>
                <p className="text-xs text-gray-500 mb-4">
                  Select countries or states where this shipping method applies. Leave empty to apply to all locations.
                </p>

                <div className="space-y-4">
                  {/* Countries Selection */}
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-2">Countries</label>
                    <div className="border border-gray-300 rounded-lg p-3 max-h-32 overflow-y-auto">
                      {isLoading ? (
                        <p className="text-xs text-gray-500">Loading countries...</p>
                      ) : countries.length === 0 ? (
                        <p className="text-xs text-gray-500">No countries available</p>
                      ) : (
                        <div className="space-y-1">
                          {countries.map((country) => (
                            <label
                              key={country.id}
                              className="flex items-center space-x-2 cursor-pointer hover:bg-gray-50 p-1 rounded text-xs"
                            >
                              <input
                                type="checkbox"
                                checked={selectedCountryIds.includes(country.id)}
                                onChange={() => handleCountryToggle(country.id)}
                                className="w-3 h-3 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
                              />
                              <span className="text-xs text-gray-700">{country.name} ({country.code})</span>
                            </label>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* States Selection */}
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-2">States/Provinces</label>
                    <div className="border border-gray-300 rounded-lg p-3 max-h-32 overflow-y-auto">
                      {isLoading ? (
                        <p className="text-xs text-gray-500">Loading states...</p>
                      ) : allStates.length === 0 ? (
                        <p className="text-xs text-gray-500">No states available</p>
                      ) : (
                        <div className="space-y-1">
                          {allStates.map((state) => (
                            <label
                              key={state.id}
                              className="flex items-center space-x-2 cursor-pointer hover:bg-gray-50 p-1 rounded text-xs"
                            >
                              <input
                                type="checkbox"
                                checked={selectedStateIds.includes(state.id)}
                                onChange={() => handleStateToggle(state.id)}
                                className="w-3 h-3 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
                              />
                              <span className="text-xs text-gray-700">
                                {state.name}
                                {state.country && ` (${state.country.name})`}
                              </span>
                            </label>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Selected Regions Summary */}
                  {(selectedCountryIds.length > 0 || selectedStateIds.length > 0) && (
                    <div className="bg-gray-50 border border-gray-200 rounded-lg p-2">
                      <p className="text-xs font-medium text-gray-700 mb-1">Selected:</p>
                      <div className="flex flex-wrap gap-1">
                        {selectedCountryIds.map((countryId) => {
                          const country = countries.find((c) => c.id === countryId);
                          return country ? (
                            <span
                              key={`country-${countryId}`}
                              className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-blue-100 text-blue-800 rounded text-xs"
                            >
                              {country.name}
                            </span>
                          ) : null;
                        })}
                        {selectedStateIds.map((stateId) => {
                          const state = allStates.find((s) => s.id === stateId);
                          return state ? (
                            <span
                              key={`state-${stateId}`}
                              className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-green-100 text-green-800 rounded text-xs"
                            >
                              {state.name}
                            </span>
                          ) : null;
                        })}
                      </div>
                    </div>
                  )}
                </div>
              </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 Method'
                ) : (
                  'Update Method'
                )}
              </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>
  );
}

