// components/organisms/ScholarshipApplicationModal.jsx
'use client';

import React, { useState, useEffect } from 'react';
import Swal from 'sweetalert2';
import Image from 'next/image';
import { FaUser, FaGlobe, FaPhone, FaTimes, FaBuilding, FaGraduationCap, FaMoneyBillWave } from 'react-icons/fa';
import { MdOutlineMail, MdSchool } from 'react-icons/md';

// Custom Components
import Heading from '../atoms/Heading';
import Paragraph from '../atoms/Paragraph';
import Button from '../atoms/Button';
import Input from '../atoms/Input';
import Select from '../atoms/Select';

export interface ScholarshipApplicationModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSubmitSuccess?: () => void;
  scholarship: {
    id: number;
    title: string;
    image: string;
    country_name: string;
    amount_min?: number;
    amount_max?: number;
    currency_symbol?: string;
    qualifications?: Array<{ qualification_name: string }>;
    percentage_cover?: number;
  };
}

const ScholarshipApplicationModal: React.FC<ScholarshipApplicationModalProps> = ({
  isOpen,
  onClose,
  onSubmitSuccess,
  scholarship
}) => {
  // Form State
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone_number: '',
    last_education: '',
    office_to_visit: ''
  });

  const [selectedPhoneCode, setSelectedPhoneCode] = useState('92');
  const [isLoading, setIsLoading] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
  const [countriesWithPhone, setCountriesWithPhone] = useState<{ id: number; name: string; phonecode: 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]);

  // Helper functions
  const formatAmountRange = (amount_min, amount_max, currency_symbol = '$') => {
    if (!amount_min && !amount_max) return 'Not specified';
    
    const symbol = currency_symbol || '$';
    
    if (amount_min && amount_max) {
      return `${symbol}${amount_min} - ${symbol}${amount_max}`;
    }
    
    if (amount_min && !amount_max) {
      return `${symbol}${amount_min}+`;
    }
    
    if (!amount_min && amount_max) {
      return `Up to ${symbol}${amount_max}`;
    }
    
    return 'Not specified';
  };

  const formatQualifications = (qualifications) => {
    if (!qualifications || qualifications.length === 0) {
      return 'Not specified';
    }
    
    if (qualifications.length === 1) {
      return qualifications[0].qualification_name;
    }
    
    const firstTwo = qualifications.map(q => q.qualification_name).join(', ');
    return firstTwo;
  };

  const formatPercentage = (percentage) => {
    if (!percentage) return 'Not specified';
    return `${percentage}% covered`;
  };

  // Handlers
  const handleChange = (e: any) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear field error when user starts typing
    if (fieldErrors[name]) {
      setFieldErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  const handlePhoneCodeChange = (e: any) => {
    setSelectedPhoneCode(e.target.value);
  };

  // Submit Handler
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setFieldErrors({});

    try {
      const payload = {
        ...formData,
        phonecode: selectedPhoneCode,
        scholarship_id: scholarship.id,
        scholarship_title: scholarship.title,
        application_type: 'scholarship'
      };

      const response = await fetch('/api/frontend/scholarship-applications', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });

      const data = await response.json();

      if (!response.ok) {
        if (data.errors) {
          // Handle field errors
          const errorMessages = Object.entries(data.errors)
            .map(([field, messages]) => [field, messages[0]])
            .reduce((acc, [field, message]) => {
              acc[field] = message;
              return acc;
            }, {});
          
          setFieldErrors(errorMessages);
          
          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">${Object.values(errorMessages).join('\n')}</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 {
          Swal.fire({
            title: 'Error',
            text: data.message || 'An error occurred while submitting your application',
            icon: 'error',
            confirmButtonText: 'OK'
          });
        }
      } else {
        // SUCCESS
        Swal.fire({
          title: 'Application Submitted!',
          text: data.message || 'Your scholarship application has been submitted successfully! Our team will contact you shortly.',
          icon: 'success',
          confirmButtonText: 'OK',
          customClass: {
            confirmButton: 'bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded'
          }
        });
        
        // Reset form and close modal
        setFormData({
          name: '',
          email: '',
          phone_number: '',
          last_education: '',
          office_to_visit: ''
        });
        setSelectedPhoneCode('92');
        
        // Call the success callback if provided
        if (onSubmitSuccess) {
          onSubmitSuccess();
        }
        
        onClose();
      }
    } catch (err) {
      console.error('Error submitting application:', 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: '',
        office_to_visit: ''
      });
      setSelectedPhoneCode('92');
      setFieldErrors({});
    }
  }, [isOpen]);

  // Options for dropdowns
  const phoneCodeOptions = countriesWithPhone.map(country => ({
    label: `${country.name} (${country.phonecode})`,
    value: country.phonecode
  }));

  const educationOptions = ['Matric', 'Intermediate', 'Bachelor', 'Master', 'PhD'];
  const officeOptions = ['Lahore', 'Islamabad', 'Karachi', 'Faisalabad'];

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-[1px]">
      <div className="bg-white rounded-2xl max-w-4xl w-full max-h-[90vh] overflow-y-auto shadow-2xl border border-gray-200">
        {/* Header with Gradient */}
        <div className="bg-gradient-to-r from-[#0B6F78] to-[#0a306b] text-white rounded-t-2xl p-6">
          <div className="flex justify-between items-start">
            <div className="flex-1">
              <Heading level={3} className="text-white mb-2">
                Apply for Scholarship
              </Heading>
              <Paragraph className="text-white/90">
                Complete your application for this scholarship opportunity
              </Paragraph>
            </div>
            <button
              onClick={onClose}
              className="p-2 hover:bg-white/20 rounded-full transition-colors text-white cursor-pointer ml-4"
            >
              <FaTimes className="text-xl" />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="p-6">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Scholarship Details - Left Side */}
            <div className="lg:col-span-1 bg-gray-50 rounded-xl p-6">
              <div className="text-center mb-6">
                <div className="relative h-32 w-32 mx-auto mb-4">
                  <Image
                    src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${scholarship.image}` || 'https://images.unsplash.com/photo-1523050854058-8df90110c9f1?ixlib=rb-4.0.3&w=1200'}
                    alt={scholarship.title}
                    fill
                    className="object-contain rounded-lg"
                  />
                </div>
                <Heading level={4} className="text-gray-900 mb-2">
                  {scholarship.title}
                </Heading>
              </div>

              {/* Scholarship Details */}
              <div className="space-y-4">
                <div className="flex items-center space-x-3">
                  <FaGlobe className="text-[#0B6F78] flex-shrink-0" />
                  <div>
                    <div className="text-sm text-gray-600">Country</div>
                    <div className="font-semibold text-gray-900">{scholarship.country_name || 'Not specified'}</div>
                  </div>
                </div>

                <div className="flex items-center space-x-3">
                  <FaMoneyBillWave className="text-[#0B6F78] flex-shrink-0" />
                  <div>
                    <div className="text-sm text-gray-600">Scholarship Value</div>
                    <div className="font-semibold text-gray-900">
                      {formatAmountRange(scholarship.amount_min, scholarship.amount_max, scholarship.currency_symbol)}
                    </div>
                  </div>
                </div>

                <div className="flex items-center space-x-3">
                  <FaGraduationCap className="text-[#0B6F78] flex-shrink-0" />
                  <div>
                    <div className="text-sm text-gray-600">Qualification Level</div>
                    <div className="font-semibold text-gray-900" title={formatQualifications(scholarship.qualifications)}>
                      {formatQualifications(scholarship.qualifications)}
                    </div>
                  </div>
                </div>

                <div className="flex items-center space-x-3">
                  <MdSchool className="text-[#0B6F78] flex-shrink-0" />
                  <div>
                    <div className="text-sm text-gray-600">Coverage</div>
                    <div className="font-semibold text-gray-900">
                      {formatPercentage(scholarship.percentage_cover)}
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Application Form - Right Side */}
            <div className="lg:col-span-2">
              <div className="mb-6">
                <Heading level={4} className="text-gray-800 mb-2">
                  Application Form
                </Heading>
                <Paragraph className="text-gray-600 text-sm">
                  Please fill in your details to apply for this scholarship. Our team will contact you within 24 hours.
                </Paragraph>
              </div>

              <form onSubmit={handleSubmit} className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* Name */}
                  <div>
                    <Input 
                      icon={<FaUser className="text-[#0B6F78]" />} 
                      placeholder="Enter Your Full Name" 
                      name="name" 
                      value={formData.name} 
                      onChange={handleChange} 
                      required 
                    />
                    {fieldErrors.name && (
                      <p className="text-red-500 text-sm mt-1 text-left">{fieldErrors.name}</p>
                    )}
                  </div>
                  
                  {/* Email */}
                  <div>
                    <Input 
                      icon={<MdOutlineMail className="text-[#0B6F78]" />} 
                      placeholder="Enter Your Email" 
                      type="email" 
                      name="email" 
                      value={formData.email} 
                      onChange={handleChange} 
                      required 
                    />
                    {fieldErrors.email && (
                      <p className="text-red-500 text-sm mt-1 text-left">{fieldErrors.email}</p>
                    )}
                  </div>
                </div>

                {/* Phone Number with Country Code */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Select
                      name="phone_code"
                      placeholder="Select Country Code"
                      icon={<FaGlobe className="text-[#0B6F78]" />}
                      value={selectedPhoneCode}
                      onChange={handlePhoneCodeChange}
                      options={phoneCodeOptions}
                    />
                  </div>
                  <div>
                    <Input
                      icon={<FaPhone className="text-[#0B6F78]" />}
                      placeholder="Enter Your Phone Number"
                      type="tel"
                      name="phone_number"
                      value={formData.phone_number}
                      onChange={handleChange}
                      required
                    />
                    {fieldErrors.phone_number && (
                      <p className="text-red-500 text-sm mt-1 text-left">{fieldErrors.phone_number}</p>
                    )}
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* Last Education */}
                  <div>
                    <Select 
                      name="last_education" 
                      icon={<FaGraduationCap className="text-[#0B6F78]" />} 
                      placeholder="Select Last Education" 
                      value={formData.last_education} 
                      onChange={handleChange} 
                      options={educationOptions} 
                      required
                    />
                    {fieldErrors.last_education && (
                      <p className="text-red-500 text-sm mt-1 text-left">{fieldErrors.last_education}</p>
                    )}
                  </div>

                  {/* Office to Visit */}
                  <div>
                    <Select 
                      name="office_to_visit" 
                      icon={<FaBuilding className="text-[#0B6F78]" />} 
                      placeholder="Select Office to Visit" 
                      value={formData.office_to_visit} 
                      onChange={handleChange} 
                      options={officeOptions} 
                      required
                    />
                    {fieldErrors.office_to_visit && (
                      <p className="text-red-500 text-sm mt-1 text-left">{fieldErrors.office_to_visit}</p>
                    )}
                  </div>
                </div>

                <Button 
                  type="submit" 
                  disabled={isLoading} 
                  className="w-full bg-gradient-to-r from-[#0B6F78] to-[#0a306b] hover:from-[#0a5a63] hover:to-[#092855] text-white py-3 rounded-xl font-semibold transition-all duration-300 shadow-lg hover:shadow-xl mt-4"
                >
                  {isLoading ? 'Submitting Application...' : 'Submit Application'}
                </Button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ScholarshipApplicationModal;