'use client';

import React, { useState, useEffect } from 'react';
import {
  getCountries, getStates, getCities, getAreas, getCenters,
  createCountry, createState, createCity, createArea, createSatsangCenter, updateSatsangCenter
} from '@/lib/actions/geography';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Card } from '@/components/ui/Card';

interface GeoEntity {
  _id: string;
  name: string;
  code?: string;
  isActive: boolean;
}

export default function GeographyPage() {
  // Navigation states
  const [countries, setCountries] = useState<GeoEntity[]>([]);
  const [states, setStates] = useState<GeoEntity[]>([]);
  const [cities, setCities] = useState<GeoEntity[]>([]);
  const [areas, setAreas] = useState<GeoEntity[]>([]);
  const [centers, setCenters] = useState<any[]>([]);

  // Selection states
  const [selectedCountry, setSelectedCountry] = useState('');
  const [selectedState, setSelectedState] = useState('');
  const [selectedCity, setSelectedCity] = useState('');
  const [selectedArea, setSelectedArea] = useState('');

  // Modals state
  const [activeModal, setActiveModal] = useState<'none' | 'country' | 'state' | 'city' | 'area' | 'center'>('none');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Center form state
  const [centerForm, setCenterForm] = useState({
    name: '',
    address: '',
    longitude: '',
    latitude: '',
    contactPerson: '',
    contactMobile: ''
  });

  // Load countries on load
  useEffect(() => {
    loadCountries();
  }, []);

  const loadCountries = async () => {
    const list = await getCountries();
    setCountries(list);
    if (list.length > 0) {
      setSelectedCountry(list[0]._id);
      loadStates(list[0]._id);
    }
  };

  const loadStates = async (cId: string) => {
    setSelectedState('');
    setStates([]);
    setCities([]);
    setAreas([]);
    setCenters([]);
    if (!cId) return;
    const list = await getStates(cId);
    setStates(list);
    if (list.length > 0) {
      setSelectedState(list[0]._id);
      loadCities(list[0]._id);
    }
  };

  const loadCities = async (sId: string) => {
    setSelectedCity('');
    setCities([]);
    setAreas([]);
    setCenters([]);
    if (!sId) return;
    const list = await getCities(sId);
    setCities(list);
    if (list.length > 0) {
      setSelectedCity(list[0]._id);
      loadAreas(list[0]._id);
    }
  };

  const loadAreas = async (cityId: string) => {
    setSelectedArea('');
    setAreas([]);
    setCenters([]);
    if (!cityId) return;
    const list = await getAreas(cityId);
    setAreas(list);
    if (list.length > 0) {
      setSelectedArea(list[0]._id);
      loadCenters(list[0]._id);
    }
  };

  const loadCenters = async (areaId: string) => {
    setCenters([]);
    if (!areaId) return;
    const list = await getCenters(areaId);
    setCenters(list);
  };

  // --- ACTIONS ---

  const handleCreateCountry = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);
    const data = new FormData(e.currentTarget);
    try {
      await createCountry(data.get('name') as string, data.get('code') as string);
      setActiveModal('none');
      loadCountries();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateState = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);
    const data = new FormData(e.currentTarget);
    try {
      await createState(data.get('name') as string, selectedCountry);
      setActiveModal('none');
      loadStates(selectedCountry);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateCity = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);
    const data = new FormData(e.currentTarget);
    try {
      await createCity(data.get('name') as string, selectedState, selectedCountry);
      setActiveModal('none');
      loadCities(selectedState);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateArea = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);
    const data = new FormData(e.currentTarget);
    try {
      await createArea(data.get('name') as string, selectedCity);
      setActiveModal('none');
      loadAreas(selectedCity);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateCenter = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);
    try {
      await createSatsangCenter({
        name: centerForm.name,
        address: centerForm.address,
        longitude: parseFloat(centerForm.longitude),
        latitude: parseFloat(centerForm.latitude),
        countryId: selectedCountry,
        stateId: selectedState,
        cityId: selectedCity,
        areaId: selectedArea,
        contactPerson: centerForm.contactPerson,
        contactMobile: centerForm.contactMobile
      });
      setActiveModal('none');
      setCenterForm({ name: '', address: '', longitude: '', latitude: '', contactPerson: '', contactMobile: '' });
      loadCenters(selectedArea);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  };

  const handleArchiveCenter = async (centerId: string, currentActive: boolean) => {
    if (!confirm('Are you sure you want to change this center state?')) return;
    try {
      await updateSatsangCenter(centerId, { isActive: !currentActive });
      loadCenters(selectedArea);
    } catch (err: any) {
      alert(err.message);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl md:text-3xl font-bold text-gray-900">Geography & Centers</h1>
          <p className="mt-1 text-sm text-gray-500">Configure geographical hierarchy structures and Satsang Centers.</p>
        </div>
        
        {/* Buttons layout */}
        <div className="flex flex-wrap gap-2">
          <Button onClick={() => setActiveModal('center')} className="bg-brand-primary text-white">
            + Add Center
          </Button>
          <Button onClick={() => setActiveModal('area')} variant="secondary" className="border-gray-200">
            + Add Area
          </Button>
          <Button onClick={() => setActiveModal('city')} variant="secondary" className="border-gray-200">
            + Add City
          </Button>
          <Button onClick={() => setActiveModal('state')} variant="secondary" className="border-gray-200">
            + Add State
          </Button>
        </div>
      </div>

      {/* Cascading Filter selectors layout */}
      <div className="grid grid-cols-1 sm:grid-cols-4 gap-4 bg-white p-4 rounded-xl border border-gray-150 shadow-sm">
        <div>
          <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Country</label>
          <select
            value={selectedCountry}
            onChange={(e) => { setSelectedCountry(e.target.value); loadStates(e.target.value); }}
            className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
          >
            <option value="">Select Country</option>
            {countries.map((c) => <option key={c._id} value={c._id}>{c.name}</option>)}
          </select>
        </div>

        <div>
          <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">State</label>
          <select
            value={selectedState}
            onChange={(e) => { setSelectedState(e.target.value); loadCities(e.target.value); }}
            className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
            disabled={!selectedCountry}
          >
            <option value="">Select State</option>
            {states.map((s) => <option key={s._id} value={s._id}>{s.name}</option>)}
          </select>
        </div>

        <div>
          <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">City</label>
          <select
            value={selectedCity}
            onChange={(e) => { setSelectedCity(e.target.value); loadAreas(e.target.value); }}
            className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
            disabled={!selectedState}
          >
            <option value="">Select City</option>
            {cities.map((ci) => <option key={ci._id} value={ci._id}>{ci.name}</option>)}
          </select>
        </div>

        <div>
          <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Area</label>
          <select
            value={selectedArea}
            onChange={(e) => { setSelectedArea(e.target.value); loadCenters(e.target.value); }}
            className="w-full rounded-lg border border-gray-250 p-2.5 bg-white text-sm"
            disabled={!selectedCity}
          >
            <option value="">Select Area</option>
            {areas.map((ar) => <option key={ar._id} value={ar._id}>{ar.name}</option>)}
          </select>
        </div>
      </div>

      {/* Centers list panel */}
      <Card className="p-6">
        <h2 className="text-lg font-bold text-gray-900 border-b border-gray-150 pb-3 mb-4">
          Satsang Centers in Selected Area
        </h2>
        
        {centers.length === 0 ? (
          <div className="text-center py-12 text-gray-500 font-medium">
            No Satsang Centers found in this area. Select/create an area and click "+ Add Center" to register.
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {centers.map((center) => (
              <div key={center._id} className="p-4 border border-gray-200 rounded-xl bg-gray-50 space-y-3 relative">
                <div className="flex justify-between items-start">
                  <div>
                    <h3 className="font-bold text-gray-900 text-base">{center.name}</h3>
                    <p className="text-xs text-gray-500 mt-0.5">{center.address}</p>
                  </div>
                  <button
                    onClick={() => handleArchiveCenter(center._id, center.isActive)}
                    className={`text-xs font-bold px-2.5 py-1 rounded-full ${
                      center.isActive ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'
                    }`}
                  >
                    {center.isActive ? 'Active' : 'Archived'}
                  </button>
                </div>

                <div className="grid grid-cols-2 gap-2 text-xs pt-2 border-t border-gray-150">
                  <div>
                    <span className="block text-gray-400 font-medium">Contact Person</span>
                    <span className="font-semibold text-gray-800">{center.contactPerson}</span>
                  </div>
                  <div>
                    <span className="block text-gray-400 font-medium">Contact Mobile</span>
                    <span className="font-semibold text-gray-800">{center.contactMobile}</span>
                  </div>
                  <div className="col-span-2 pt-1.5">
                    <span className="block text-gray-400 font-medium">GPS Location</span>
                    <span className="font-mono text-brand-secondary font-semibold">
                      [{center.location.coordinates[0]}, {center.location.coordinates[1]}]
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* --- DIALOG MODALS --- */}

      {activeModal !== 'none' && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
          <div className="fixed inset-0 bg-gray-500 bg-opacity-75" onClick={() => setActiveModal('none')} />

          <div className="relative bg-white rounded-xl shadow-xl max-w-md w-full p-6 border border-gray-150 animate-slide-in">
            <h3 className="text-lg font-bold text-gray-950 mb-4 capitalize">
              Add New {activeModal}
            </h3>

            {error && (
              <div className="mb-4 bg-red-50 border border-red-200 text-red-800 p-3 rounded-lg text-sm font-semibold">
                {error}
              </div>
            )}

            {activeModal === 'center' ? (
              <form onSubmit={handleCreateCenter} className="space-y-4">
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Center Name</label>
                  <Input
                    required
                    value={centerForm.name}
                    onChange={(e) => setCenterForm({ ...centerForm, name: e.target.value })}
                  />
                </div>
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Street Address</label>
                  <Input
                    required
                    value={centerForm.address}
                    onChange={(e) => setCenterForm({ ...centerForm, address: e.target.value })}
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Longitude</label>
                    <Input
                      required
                      type="number"
                      step="0.000001"
                      placeholder="e.g. 75.8577"
                      value={centerForm.longitude}
                      onChange={(e) => setCenterForm({ ...centerForm, longitude: e.target.value })}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Latitude</label>
                    <Input
                      required
                      type="number"
                      step="0.000001"
                      placeholder="e.g. 22.7196"
                      value={centerForm.latitude}
                      onChange={(e) => setCenterForm({ ...centerForm, latitude: e.target.value })}
                    />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Contact Person</label>
                    <Input
                      required
                      value={centerForm.contactPerson}
                      onChange={(e) => setCenterForm({ ...centerForm, contactPerson: e.target.value })}
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">Contact Mobile</label>
                    <Input
                      required
                      value={centerForm.contactMobile}
                      onChange={(e) => setCenterForm({ ...centerForm, contactMobile: e.target.value })}
                    />
                  </div>
                </div>

                <div className="flex justify-end gap-2 pt-2">
                  <Button type="button" variant="secondary" onClick={() => setActiveModal('none')}>
                    Cancel
                  </Button>
                  <Button type="submit" isLoading={isLoading} className="bg-brand-primary text-white">
                    Save Center
                  </Button>
                </div>
              </form>
            ) : (
              <form
                onSubmit={
                  activeModal === 'country' ? handleCreateCountry :
                  activeModal === 'state' ? handleCreateState :
                  activeModal === 'city' ? handleCreateCity :
                  handleCreateArea
                }
                className="space-y-4"
              >
                <div>
                  <label className="block text-sm font-semibold text-gray-700 mb-1">Name</label>
                  <Input required name="name" />
                </div>
                {activeModal === 'country' && (
                  <div>
                    <label className="block text-sm font-semibold text-gray-700 mb-1">ISO Code</label>
                    <Input required name="code" placeholder="e.g. IN" />
                  </div>
                )}

                <div className="flex justify-end gap-2 pt-2">
                  <Button type="button" variant="secondary" onClick={() => setActiveModal('none')}>
                    Cancel
                  </Button>
                  <Button type="submit" isLoading={isLoading} className="bg-brand-primary text-white">
                    Add
                  </Button>
                </div>
              </form>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
