'use client';

import React, { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import { 
  User, 
  Mail, 
  Phone, 
  Globe, 
  GraduationCap, 
  Building2, 
  MapPin,
  X,
  Sparkles
} from 'lucide-react';

// Import Shared Components
import CustomInput from '../shared/CustomInput';
import CustomSelect from '../shared/CustomSelect';
import PhoneInput from '../shared/PhoneInput';
import SubmitButton from '../shared/SubmitButton';

// Storage utility
import { consultationStorage } from '../../../lib/consultationStorage';

// -------------------------
// Types
// -------------------------
type CountryPhone = { id: number; name: string; phonecode: string };
type ApiErrorResponse = {
  success: boolean;
  message?: string;
  errors?: Record<string, string[]>;
};

export interface FreeConsultationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmitSuccess?: () => void;
  title?: string;
  description?: string;
}

const FreeConsultationModal: React.FC<FreeConsultationModalProps> = ({
  isOpen,
  onClose,
  onSubmitSuccess,
  title = "Free Consultation",
  description = "Get expert guidance for studying abroad — completely free of charge!"
}) => {
  // -------------------------
  // Form State
  // -------------------------
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone_number: '',
    last_education: '',
    interested_country: '',
    apply_for: '',
    office_to_visit: ''
  });

  const [countriesWithPhone, setCountriesWithPhone] = useState<CountryPhone[]>([]);
  const [selectedPhoneCode, setSelectedPhoneCode] = useState('92');
  const [isLoading, setIsLoading] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});

  // -------------------------
  // Fetch Countries with Phone Codes
  // -------------------------
  useEffect(() => {
    if (!isOpen) return;
    
    const controller = new AbortController();
    const fetchCountriesWithPhone = async () => {
      try {
        const res = await fetch(`/api/frontend/countries-with-phone`, { signal: controller.signal });
        if (!res.ok) throw new Error(`Failed to fetch countries: ${res.status}`);
        const data = await res.json();
        setCountriesWithPhone(data.data || []);
      } catch (err: any) {
        if (err.name === 'AbortError') return;
        console.error('Error fetching countries with phone codes:', err);
        setCountriesWithPhone([]);
      }
    };
    fetchCountriesWithPhone();
    return () => controller.abort();
  }, [isOpen]);

  // -------------------------
  // Handlers
  // -------------------------
  const handleChange = (e: any) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    if (fieldErrors[name]) {
      setFieldErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handleSelectChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    if (fieldErrors[name]) {
      setFieldErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handlePhoneCodeChange = (e: any) => {
    setSelectedPhoneCode(e.target.value);
  };

  const handlePhoneInputChange = (e: any) => {
    const { value } = e.target;
    const cleanedValue = value.replace(/\D/g, '');
    setFormData(prev => ({ 
      ...prev, 
      phone_number: cleanedValue
    }));
  };

  const getDisplayPhoneNumber = () => {
    if (!formData.phone_number) return '';
    
    const phoneWithoutZero = formData.phone_number.replace(/^0+/, '');
    
    if (selectedPhoneCode === '92') {
      if (phoneWithoutZero.length <= 3) {
        return `${phoneWithoutZero}`;
      } else {
        return `${phoneWithoutZero.slice(0, 3)} ${phoneWithoutZero.slice(3)}`;
      }
    } else {
      return `${phoneWithoutZero}`;
    }
  };

  // -------------------------
  // Error Display Functions
  // -------------------------
  const displayFieldErrors = (errors: Record<string, string[]>) => {
    setFieldErrors(
      Object.fromEntries(
        Object.entries(errors).map(([field, messages]) => [field, messages[0]])
      )
    );
  };

  const displaySweetAlertError = (errorData: ApiErrorResponse) => {
    if (errorData.errors) {
      const errorMessages = Object.entries(errorData.errors)
        .map(([field, messages]) => `• ${messages.join(', ')}`)
        .join('\n');
      
      Swal.fire({
        title: 'Validation Error',
        html: `<div class="text-left"><p class="mb-3">Please correct the following errors:</p><pre class="text-sm text-red-600 whitespace-pre-wrap">${errorMessages}</pre></div>`,
        icon: 'error',
        confirmButtonText: 'OK',
        customClass: {
          popup: 'rounded-lg',
          confirmButton: 'bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded'
        }
      });
    } else if (errorData.message) {
      Swal.fire({
        title: 'Error',
        text: errorData.message,
        icon: 'error',
        confirmButtonText: 'OK'
      });
    } else {
      Swal.fire({
        title: 'Error',
        text: 'An unexpected error occurred',
        icon: 'error',
        confirmButtonText: 'OK'
      });
    }
  };

  // -------------------------
  // Submit Handler
  // -------------------------
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setFieldErrors({});

    try {
      const payload = {
        ...formData,
        phonecode: `${selectedPhoneCode}`
      };

      const response = await fetch('/api/frontend/free-consultations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const data: ApiErrorResponse = await response.json();

      if (!response.ok) {
        if (data.errors) {
          displayFieldErrors(data.errors);
          displaySweetAlertError(data);
        } else {
          const errorMessage = data.message || 'An error occurred while submitting the form';
          Swal.fire({
            title: 'Error',
            text: errorMessage,
            icon: 'error',
            confirmButtonText: 'OK'
          });
        }
      } else {
        consultationStorage.setSubmitted();
        
        Swal.fire({
          title: 'Success!',
          text: data.message || 'Your consultation request has been submitted successfully!',
          icon: 'success',
          confirmButtonText: 'OK',
          timer: 3000,
          background: '#ffffff',
          color: '#1f2937',
          customClass: {
            confirmButton: 'bg-linear-to-r from-teal-600 to-blue-500 text-white px-6 py-3 rounded-xl font-semibold'
          }
        });
        
        setFormData({
          name: '',
          email: '',
          phone_number: '',
          last_education: '',
          interested_country: '',
          apply_for: '',
          office_to_visit: ''
        });
        setSelectedPhoneCode('92');
        
        if (onSubmitSuccess) {
          onSubmitSuccess();
        }
        
        onClose();
      }
    } catch (err) {
      console.error('Error submitting form:', err);
      Swal.fire({
        title: 'Network Error',
        text: 'Submission failed. Please check your internet connection and try again.',
        icon: 'error',
        confirmButtonText: 'OK'
      });
    } finally {
      setIsLoading(false);
    }
  };

  // -------------------------
  // Reset form when modal closes
  // -------------------------
  useEffect(() => {
    if (!isOpen) {
      setFormData({
        name: '',
        email: '',
        phone_number: '',
        last_education: '',
        interested_country: '',
        apply_for: '',
        office_to_visit: ''
      });
      setSelectedPhoneCode('92');
      setFieldErrors({});
    }
  }, [isOpen]);

  // -------------------------
  // Options
  // -------------------------
  const phoneCodeOptions = countriesWithPhone.map(country => ({
    label: `${country.name} (+${country.phonecode})`,
    value: country.phonecode
  }));

  const educationOptions = ['Matric', 'Intermediate', 'Bachelor', 'Master'];
  const interestedCountryOptions = ['Italy', 'France', 'Turkey', 'China', 'Cyprus', 'Sweden', 'Finland', 'South Korea', 'UK'];
  const officeOptions = ['Lahore', 'Islamabad', 'Karachi', 'Faisalabad'];
  const applyForOptions = ['Study Visa', 'Visit Visa', 'IELTS'];

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-start md:items-center justify-center p-2 md:p-4 bg-black/70 backdrop-blur-sm overflow-y-auto">
      {/* Modal Container */}
      <div className="relative bg-white rounded-2xl md:rounded-3xl max-w-md md:max-w-2xl w-full shadow-2xl border border-gray-100 overflow-hidden my-auto">
        {/* Header with Gradient */}
        <div className="bg-linear-to-r from-teal-600 to-blue-500 p-4 md:p-6">
          <div className="flex justify-between items-center">
            <div>
              <div className="inline-flex items-center gap-2 bg-white/20 backdrop-blur-sm px-3 py-1 rounded-full mb-2">
                <Sparkles className="w-3 h-3 md:w-4 md:h-4" />
                <span className="text-xs md:text-sm font-semibold text-white">Free Consultation</span>
              </div>
              <h2 className="text-xl md:text-2xl font-bold text-white">
                Get Expert Study Abroad Guidance
              </h2>
            </div>
            <button
              onClick={onClose}
              className="p-1 md:p-2 hover:bg-white/20 rounded-full transition-colors text-white cursor-pointer flex-shrink-0"
              aria-label="Close modal"
            >
              <X className="w-5 h-5 md:w-6 md:h-6" />
            </button>
          </div>
        </div>

        {/* Form Content */}
        <div className="p-4 md:p-6 max-h-[calc(100vh-200px)] md:max-h-none overflow-y-auto">
          <form onSubmit={handleSubmit} className="space-y-4 md:space-y-6">
            {/* Row 1: Name & Email */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
              <div className="modal-input-wrapper">
                <CustomInput 
                  Icon={User}
                  placeholder="Enter Your Name" 
                  name="name" 
                  value={formData.name} 
                  onChange={handleChange}
                  error={fieldErrors.name}
                />
              </div>
              
              <div className="modal-input-wrapper">
                <CustomInput 
                  Icon={Mail}
                  placeholder="Enter Your Email" 
                  type="email"
                  name="email" 
                  value={formData.email} 
                  onChange={handleChange}
                  error={fieldErrors.email}
                />
              </div>
            </div>

            {/* Row 2: Phone Number (Full width) */}
            <div className="grid grid-cols-1">
              <div className="modal-input-wrapper">
                <PhoneInput
                  phoneCodeOptions={phoneCodeOptions}
                  selectedPhoneCode={selectedPhoneCode}
                  onPhoneCodeChange={handlePhoneCodeChange}
                  phoneNumber={formData.phone_number}
                  onPhoneNumberChange={handlePhoneInputChange}
                  getDisplayPhoneNumber={getDisplayPhoneNumber}
                  error={fieldErrors.phone_number}
                />
              </div>
            </div>

            {/* Row 3: Last Education & Interested Country */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
              <div className="modal-input-wrapper">
                <CustomSelect 
                  Icon={GraduationCap}
                  name="last_education" 
                  value={formData.last_education} 
                  onChange={handleSelectChange} 
                  options={educationOptions} 
                  placeholder="Select Last Education"
                  error={fieldErrors.last_education}
                />
              </div>

              <div className="modal-input-wrapper">
                <CustomSelect 
                  Icon={Globe}
                  name="interested_country" 
                  value={formData.interested_country} 
                  onChange={handleSelectChange} 
                  options={interestedCountryOptions} 
                  placeholder="Select Country"
                  error={fieldErrors.interested_country}
                />
              </div>
            </div>

            {/* Row 4: Apply For & Office to Visit */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4">
              <div className="modal-input-wrapper">
                <CustomSelect 
                  Icon={Building2}
                  name="apply_for" 
                  value={formData.apply_for} 
                  onChange={handleSelectChange} 
                  options={applyForOptions} 
                  placeholder="Select Apply For"
                  error={fieldErrors.apply_for}
                />
              </div>

              <div className="modal-input-wrapper">
                <CustomSelect 
                  Icon={MapPin}
                  name="office_to_visit" 
                  value={formData.office_to_visit} 
                  onChange={handleSelectChange} 
                  options={officeOptions} 
                  placeholder="Select Office"
                  error={fieldErrors.office_to_visit}
                />
              </div>
            </div>

            {/* Submit Button */}
            <div className="pt-2 md:pt-4">
              <SubmitButton 
                isLoading={isLoading}
              />
            </div>
          </form>
        </div>

        {/* Footer Gradient */}
        <div className="h-1 md:h-2 bg-linear-to-r from-teal-600 to-blue-500"></div>
      </div>

      {/* Add CSS for smaller inputs */}
      <style jsx>{`
        .modal-input-wrapper :global(.custom-input),
        .modal-input-wrapper :global(.custom-select),
        .modal-input-wrapper :global(.phone-input) {
          padding-top: 0.5rem;
          padding-bottom: 0.5rem;
          min-height: 48px;
        }
        
        .modal-input-wrapper :global(.custom-input svg),
        .modal-input-wrapper :global(.custom-select svg),
        .modal-input-wrapper :global(.phone-input svg) {
          width: 16px;
          height: 16px;
        }
        
        .modal-input-wrapper :global(input),
        .modal-input-wrapper :global(select) {
          font-size: 14px;
        }
        
        @media (min-width: 768px) {
          .modal-input-wrapper :global(.custom-input),
          .modal-input-wrapper :global(.custom-select),
          .modal-input-wrapper :global(.phone-input) {
            padding-top: 0.75rem;
            padding-bottom: 0.75rem;
            min-height: 56px;
          }
          
          .modal-input-wrapper :global(.custom-input svg),
          .modal-input-wrapper :global(.custom-select svg),
          .modal-input-wrapper :global(.phone-input svg) {
            width: 18px;
            height: 18px;
          }
          
          .modal-input-wrapper :global(input),
          .modal-input-wrapper :global(select) {
            font-size: 16px;
          }
        }
      `}</style>
    </div>
  );
};

export default FreeConsultationModal;