'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Swal from 'sweetalert2';
import { getCountries, getStats, getCities } from '../../../utils/countryStateCityAPI';

export default function VisaApplyNowPage() {
  const params = useParams();
  const slug = params?.slug || '';

  const [form, setForm] = useState({
    givenName: '',
    email: '',
    mobile: '',
    education: '',
    gender: '',
    taxpayer: '',
    bankStatement: '',
    applyFor: '',
    homeCountry: '',
    state: '',
    city: '',
  });

  const [countries, setCountries] = useState([]);
  const [states, setStates] = useState([]);
  const [cities, setCities] = useState([]);
  const [errors, setErrors] = useState({});
  const [submitted, setSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loadingLocations, setLoadingLocations] = useState({
    countries: false,
    states: false,
    cities: false
  });

  // Helper to convert API response to options format
  const toOptions = (rows) => {
    if (!Array.isArray(rows)) return [];
    return rows.map(r => ({ label: r.name, value: String(r.id) }));
  };

  // Derived numeric IDs for fetching
  const countryId = form.homeCountry ? Number(form.homeCountry) : undefined;
  const stateId = form.state ? Number(form.state) : undefined;

  // --- Fetch Countries on mount ---
  useEffect(() => {
    const fetchCountries = async () => {
      setLoadingLocations(prev => ({ ...prev, countries: true }));
      try {
        const res = await getCountries();
        setCountries(res || []);
      } catch (err) {
        console.error('Error fetching countries:', err);
        setCountries([]);
      } finally {
        setLoadingLocations(prev => ({ ...prev, countries: false }));
      }
    };
    
    fetchCountries();
  }, []);

  // --- Fetch States when country changes ---
  useEffect(() => {
    if (!countryId) {
      setStates([]);
      setCities([]);
      setForm(prev => ({ ...prev, state: '', city: '' }));
      return;
    }

    const fetchStates = async () => {
      setLoadingLocations(prev => ({ ...prev, states: true }));
      try {
        setStates([]);
        setCities([]);
        setForm(prev => ({ ...prev, state: '', city: '' }));
        
        const res = await getStats(countryId);
        setStates(res || []);
      } catch (err) {
        console.error('Error fetching states:', err);
        setStates([]);
      } finally {
        setLoadingLocations(prev => ({ ...prev, states: false }));
      }
    };

    fetchStates();
  }, [countryId]);

  // --- Fetch Cities when state changes ---
  useEffect(() => {
    if (!stateId) {
      setCities([]);
      setForm(prev => ({ ...prev, city: '' }));
      return;
    }

    const fetchCities = async () => {
      setLoadingLocations(prev => ({ ...prev, cities: true }));
      try {
        setCities([]);
        setForm(prev => ({ ...prev, city: '' }));
        
        const res = await getCities(stateId);
        setCities(res || []);
      } catch (err) {
        console.error('Error fetching cities:', err);
        setCities([]);
      } finally {
        setLoadingLocations(prev => ({ ...prev, cities: false }));
      }
    };

    fetchCities();
  }, [stateId]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm((prev) => ({ ...prev, [name]: value }));
    setErrors((prev) => ({ ...prev, [name]: '' }));
  };

  const validate = () => {
    const newErrors = {};
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const phoneRegex = /^(?:\+92|92|0)3[0-9]{9}$/;

    Object.entries(form).forEach(([key, value]) => {
      if (!value?.toString().trim()) newErrors[key] = 'This field is required';
    });

    if (form.email && !emailRegex.test(form.email)) {
      newErrors.email = 'Invalid email format';
    }

    if (form.mobile && !phoneRegex.test(form.mobile)) {
      newErrors.mobile = 'Invalid Pakistani mobile number';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!validate()) {
      Swal.fire({
        icon: 'warning',
        title: 'Please fill all fields correctly!',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    setLoading(true);
    try {
      const res = await fetch('/api/frontend/visit-visas', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });

      if (!res.ok) throw new Error('Submission failed');

      setSubmitted(true);
      Swal.fire({
        icon: 'success',
        title: 'Application Submitted Successfully!',
        confirmButtonColor: '#0B6D76',
      });
    } catch (err) {
      console.error(err);
      Swal.fire({
        icon: 'error',
        title: 'Something went wrong!',
        text: 'Please try again later.',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setLoading(false);
    }
  };

  const formatTitle = (text) =>
    text.replace(/-visit-visa$/, '').replace(/-/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase());

  const renderError = (field) =>
    errors[field] && <p className="text-red-500 text-sm mt-1">{errors[field]}</p>;

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 px-4 py-10">
      <div className="w-full max-w-3xl bg-white shadow-2xl rounded-3xl overflow-hidden">
        <div className="bg-[#0B6D76] p-6 text-center">
          <h1 className="text-3xl sm:text-4xl font-bold text-white">
            Apply for <span className="text-yellow-300">{formatTitle(slug)}</span> Visa
          </h1>
          <p className="text-blue-100 mt-2">Complete the form below to start your application</p>
        </div>

        {submitted ? (
          <div className="text-center py-16 px-6">
            <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100 mb-4">
              <svg className="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h2 className="text-2xl font-semibold text-gray-800 mb-2">Application Submitted Successfully!</h2>
            <p className="text-gray-600 max-w-md mx-auto">
              Thank you for your application. Our team will contact you within 24-48 hours.
            </p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="p-6 sm:p-8 md:p-10 space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Text/Email/Tel inputs */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Full Name</label>
                <input
                  name="givenName"
                  type="text"
                  value={form.givenName}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                />
                {renderError('givenName')}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Email Address</label>
                <input
                  name="email"
                  type="email"
                  value={form.email}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                />
                {renderError('email')}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Mobile Number</label>
                <input
                  name="mobile"
                  type="tel"
                  value={form.mobile}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                />
                {renderError('mobile')}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Apply For</label>
                <input
                  name="applyFor"
                  type="text"
                  value={form.applyFor}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                />
                {renderError('applyFor')}
              </div>

              {/* Country Dropdown */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Home Country</label>
                <select
                  name="homeCountry"
                  value={form.homeCountry}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
                >
                  <option value="">Select Country</option>
                  {countries.map((country) => (
                    <option key={country.id} value={country.id}>
                      {country.name}
                    </option>
                  ))}
                </select>
                {loadingLocations.countries && <p className="text-sm text-gray-500 mt-1">Loading countries...</p>}
                {renderError('homeCountry')}
              </div>

              {/* State Dropdown */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">State/Province</label>
                <select
                  name="state"
                  value={form.state}
                  onChange={handleChange}
                  required
                  disabled={!form.homeCountry || loadingLocations.states}
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none disabled:opacity-50"
                >
                  <option value="">Select State</option>
                  {states.map((state) => (
                    <option key={state.id} value={state.id}>
                      {state.name}
                    </option>
                  ))}
                </select>
                {loadingLocations.states && <p className="text-sm text-gray-500 mt-1">Loading states...</p>}
                {renderError('state')}
              </div>

              {/* City Dropdown */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">City</label>
                <select
                  name="city"
                  value={form.city}
                  onChange={handleChange}
                  required
                  disabled={!form.state || loadingLocations.cities}
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none disabled:opacity-50"
                >
                  <option value="">Select City</option>
                  {cities.map((city) => (
                    <option key={city.id} value={city.id}>
                      {city.name}
                    </option>
                  ))}
                </select>
                {loadingLocations.cities && <p className="text-sm text-gray-500 mt-1">Loading cities...</p>}
                {renderError('city')}
              </div>

              {/* Education Dropdown */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Last Education</label>
                <select
                  name="education"
                  value={form.education}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
                >
                  <option value="">Select Education</option>
                  <option value="Matric">Matric</option>
                  <option value="Inter">Inter</option>
                  <option value="Bachelor">Bachelor</option>
                  <option value="Master">Master</option>
                  <option value="PhD">PhD</option>
                  <option value="Other">Other</option>
                </select>
                {renderError('education')}
              </div>

              {/* Gender Dropdown */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Gender</label>
                <select
                  name="gender"
                  value={form.gender}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
                >
                  <option value="">Select Gender</option>
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                  <option value="Other">Other</option>
                </select>
                {renderError('gender')}
              </div>

              {/* Taxpayer Status Dropdown */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Taxpayer Status</label>
                <select
                  name="taxpayer"
                  value={form.taxpayer}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
                >
                  <option value="">Select Status</option>
                  <option value="Filer">Filer</option>
                  <option value="Non-Filer">Non-Filer</option>
                </select>
                {renderError('taxpayer')}
              </div>

              {/* Bank Statement Dropdown */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">6 Months Bank Statement?</label>
                <select
                  name="bankStatement"
                  value={form.bankStatement}
                  onChange={handleChange}
                  required
                  className="w-full pl-4 pr-4 py-2 border border-gray-300 rounded-lg text-sm bg-white focus:ring-2 focus:ring-blue-500 focus:outline-none"
                >
                  <option value="">Select Option</option>
                  <option value="Yes">Yes</option>
                  <option value="No">No</option>
                </select>
                {renderError('bankStatement')}
              </div>
            </div>

            <div className="flex items-start">
              <input id="terms" name="terms" type="checkbox" required className="h-4 w-4 text-blue-600 border-gray-300 rounded" />
              <label htmlFor="terms" className="ml-2 block text-sm text-gray-700">
                I agree to the <a href="#" className="text-blue-600 underline hover:text-blue-500">terms and conditions</a>
              </label>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-[#0B6D76] text-white font-semibold py-3 px-4 rounded-lg shadow-md hover:shadow-lg transition disabled:opacity-50"
            >
              {loading ? 'Submitting...' : 'Submit Application'}
            </button>
          </form>
        )}
      </div>
    </div>
  );
}