'use client';

import React, { useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { useRouter } from 'next/navigation';
import { getCountries, getCities, getStats } from '../../utils/countryStateCityAPI';
import { useUserStore } from '../../../store/useUserStore';
import { 
  User, Mail, Phone, Globe, MapPin, BookOpen, 
  ChevronDown, Loader2, Save
} from 'lucide-react';

// Custom Heading Component
const CustomHeading = ({ level = 2, children, className = '' }) => {
  const Tag = `h${level}`;
  return (
    <Tag className={`font-bold text-gray-900 ${className}`}>
      {children}
    </Tag>
  );
};

// Custom Button Component
const CustomButton = ({ 
  children, 
  type = 'button', 
  variant = 'primary',
  isLoading = false,
  disabled = false,
  className = '',
  ...props 
}) => {
  const baseStyles = 'inline-flex items-center justify-center font-medium rounded-xl transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed';
  
  const variants = {
    primary: 'bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white hover:shadow-lg hover:shadow-blue-500/25 focus:ring-blue-500',
    secondary: 'bg-gray-100 text-gray-700 hover:bg-gray-200 focus:ring-gray-400',
    outline: 'border-2 border-blue-600 text-blue-600 hover:bg-blue-50 focus:ring-blue-500',
  };

  return (
    <button
      type={type}
      disabled={disabled || isLoading}
      className={`${baseStyles} ${variants[variant]} ${className}`}
      {...props}
    >
      {isLoading ? (
        <>
          <Loader2 className="w-5 h-5 mr-2 animate-spin" />
          Processing...
        </>
      ) : (
        children
      )}
    </button>
  );
};

const StudentProfile = () => {
  const { user } = useUserStore();
  const router = useRouter();
  
  const [form, setForm] = useState({
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    nationality: '',
    gender: '',
    program_type: '',
    city: '',
    state: '',
  });

  const [countries, setCountries] = useState([]);
  const [cities, setCities] = useState([]);
  const [states, setStates] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isFetchingCountries, setIsFetchingCountries] = useState(false);
  const [isFetchingCities, setIsFetchingCities] = useState(false);

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

  function toOptions(rows) {
    if (!Array.isArray(rows)) return [];
    return rows.map(r => ({ label: r.name, value: String(r.id) }));
  }

  function readSelectValue(eOrValue) {
    if (eOrValue?.target?.value !== undefined) return eOrValue.target.value;
    return String(eOrValue ?? '');
  }

  const handleCountryChange = (eOrValue) => {
    const value = readSelectValue(eOrValue);
    setForm(prev => ({
      ...prev,
      nationality: value,
      state: '',
      city: ''
    }));
  };

  const handleStateChange = (eOrValue) => {
    const value = readSelectValue(eOrValue);
    setForm(prev => ({
      ...prev,
      state: value,
      city: ''
    }));
  };

  const handleCityChange = (eOrValue) => {
    const value = readSelectValue(eOrValue);
    setForm(prev => ({ ...prev, city: value }));
  };

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

  // Fetch states
  useEffect(() => {
    if (!countryId) {
      setStates([]);
      setCities([]);
      return;
    }

    const fetchStates = async () => {
      try {
        setStates([]);
        setCities([]);
        const res = await getStats(countryId);
        setStates(res || []);
      } catch (err) {
        console.error('Error fetching states:', err);
        setStates([]);
      }
    };

    fetchStates();
  }, [countryId]);

  // Fetch cities
  useEffect(() => {
    if (!stateId) {
      setCities([]);
      return;
    }

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

    fetchCities();
  }, [stateId]);

  // Fetch student data
  useEffect(() => {
    const fetchStudentData = async () => {
      try {
        setIsLoading(true);
        const response = await fetch(`/api/frontend/userdashboard/profile/`, {
          method: "POST"
        });
        
        if(!response.ok) {
          const data = await response.json();
          Swal.fire({ icon: 'error', title: 'Error', text: data.message });
        }

        const data = await response.json();

        const studentData = {
          first_name: data.data?.first_name || '',
          last_name: data.data?.last_name || '',
          email: data.data?.email || '',
          phone: data.data?.phone || '',
          nationality: data.data?.nationality ? String(data.data.nationality) : '',
          gender: data.data?.gender || '',
          program_type: data.data?.prefered_program || '',
          city: data.data?.city ? String(data.data.city) : '',
          state: data.data?.state ? String(data.data.state) : '',
        };

        setForm(studentData);
      } catch (error) {
        console.error('Error fetching student data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchStudentData();
  }, [user?.id]);

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

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

    try {
      // Prepare the data with proper type conversions
      const submitData = {
        first_name: form.first_name,
        last_name: form.last_name,
        email: form.email,
        phone: form.phone || null,
        nationality: form.nationality ? Number(form.nationality) : null,
        state: form.state ? Number(form.state) : null,
        city: form.city ? Number(form.city) : null,
        gender: form.gender || null,
        program_type: form.program_type || null
      };

      const response = await fetch(`/api/frontend/userdashboard/profile/`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(submitData),
      });

      const data = await response.json();

      if (response.ok) {
        await Swal.fire({ 
          icon: 'success', 
          title: 'Success', 
          text: 'Profile updated successfully!',
          timer: 2000,
          showConfirmButton: false,
          background: '#f8fafc',
          color: '#1e293b'
        });
        router.refresh();
      } else {
        const errorMessages = data.message || {};
        if (typeof errorMessages === 'object') {
          const errorMessagesString = Object.values(errorMessages).join('\n');
          Swal.fire({
            icon: 'error',
            title: 'Error',
            text: errorMessagesString,
            confirmButtonColor: '#3b82f6',
            background: '#f8fafc',
            color: '#1e293b'
          });
        } else {
          throw new Error(errorMessages);
        }
      }
    } catch (err) {
      console.error('Profile update error:', err);
      await Swal.fire({ 
        icon: 'error', 
        title: 'Error', 
        text: 'Network error',
        timer: 3000,
        background: '#f8fafc',
        color: '#1e293b'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const countryOptions = toOptions(countries);
  const stateOptions = toOptions(states);
  const cityOptions = toOptions(cities);

  // Custom Select Component
  const CustomSelect = ({ 
    label, 
    name, 
    value, 
    onChange, 
    options, 
    icon: Icon, 
    disabled = false,
    isLoading = false,
    placeholder = "Select an option" 
  }) => (
    <div className="space-y-2">
      {label && (
        <label className="block text-sm font-medium text-gray-700">
          {label}
        </label>
      )}
      <div className="relative">
        {Icon && (
          <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
            <Icon size={18} />
          </div>
        )}
        <select
          name={name}
          value={value}
          onChange={onChange}
          disabled={disabled || isLoading}
          className={`w-full pl-10 pr-10 py-3 rounded-xl border ${disabled ? 'bg-gray-100 cursor-not-allowed' : 'bg-white'} 
                     border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                     appearance-none ${isLoading ? 'opacity-70' : ''}`}
        >
          <option value="">{placeholder}</option>
          {options.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        <div className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400">
          {isLoading ? (
            <Loader2 size={18} className="animate-spin" />
          ) : (
            <ChevronDown size={18} />
          )}
        </div>
      </div>
    </div>
  );

  return (
    <div className="space-y-8 animate-in fade-in duration-500">
      {/* Header */}
      <div className="text-center space-y-4">
        <div className="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-100 to-cyan-100 rounded-2xl mb-4">
          <User className="w-8 h-8 text-blue-600" />
        </div>
        <CustomHeading level={2} className="text-3xl md:text-4xl">
          Edit Profile
        </CustomHeading>
        <p className="text-gray-600 max-w-2xl mx-auto">
          Update your personal information and preferences. All changes are saved automatically.
        </p>
      </div>

      {/* Profile Form */}
      <div className="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
        <form onSubmit={handleSubmit} className="p-6 md:p-8">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* First Name */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                First Name
              </label>
              <div className="relative">
                <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                  <User size={18} />
                </div>
                <input
                  name="first_name"
                  value={form.first_name}
                  onChange={handleChange}
                  className="w-full pl-10 pr-4 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="Enter first name"
                  required
                />
              </div>
            </div>

            {/* Last Name */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Last Name
              </label>
              <div className="relative">
                <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                  <User size={18} />
                </div>
                <input
                  name="last_name"
                  value={form.last_name}
                  onChange={handleChange}
                  className="w-full pl-10 pr-4 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="Enter last name"
                  required
                />
              </div>
            </div>

            {/* Email */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Email Address
              </label>
              <div className="relative">
                <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                  <Mail size={18} />
                </div>
                <input
                  name="email"
                  value={form.email}
                  disabled
                  className="w-full pl-10 pr-4 py-3 rounded-xl border border-gray-300 bg-gray-50 text-gray-500 cursor-not-allowed"
                  placeholder="Email address"
                />
              </div>
            </div>

            {/* Phone */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Phone Number
              </label>
              <div className="relative">
                <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                  <Phone size={18} />
                </div>
                <input
                  name="phone"
                  value={form.phone || ''}
                  onChange={handleChange}
                  className="w-full pl-10 pr-4 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  placeholder="Enter phone number"
                />
              </div>
            </div>

            {/* Country */}
            <CustomSelect
              label="Country"
              name="nationality"
              value={form.nationality}
              onChange={(e) => handleCountryChange(e)}
              options={countryOptions}
              icon={Globe}
              isLoading={isFetchingCountries}
              placeholder="Select your country"
            />

            {/* State */}
            <CustomSelect
              label="State/Province"
              name="state"
              value={form.state}
              onChange={(e) => handleStateChange(e)}
              options={stateOptions}
              icon={MapPin}
              disabled={!form.nationality}
              placeholder={form.nationality ? "Select state" : "Select country first"}
            />

            {/* City */}
            <CustomSelect
              label="City"
              name="city"
              value={form.city}
              onChange={(e) => handleCityChange(e)}
              options={cityOptions}
              icon={MapPin}
              disabled={!form.state}
              isLoading={isFetchingCities}
              placeholder={form.state ? "Select city" : "Select state first"}
            />

            {/* Program Type */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Program Type
              </label>
              <div className="relative">
                <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400">
                  <BookOpen size={18} />
                </div>
                <select
                  name="program_type"
                  value={form.program_type || ''}
                  onChange={handleChange}
                  className="w-full pl-10 pr-10 py-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent appearance-none"
                >
                  <option value="">Select program type</option>
                  <option value="Undergraduate">Undergraduate</option>
                  <option value="Graduate">Graduate</option>
                  <option value="PhD">PhD</option>
                  <option value="Diploma">Diploma</option>
                  <option value="Certificate">Certificate</option>
                </select>
                <ChevronDown className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400" size={18} />
              </div>
            </div>

            {/* Gender */}
            <div className="space-y-2">
              <label className="block text-sm font-medium text-gray-700">
                Gender
              </label>
              <div className="grid grid-cols-3 gap-3">
                {['Male', 'Female', 'Other'].map((gender) => (
                  <label
                    key={gender}
                    className={`flex items-center justify-center p-3 rounded-xl border cursor-pointer transition-all duration-200 ${
                      form.gender === gender
                        ? 'border-blue-500 bg-blue-50 text-blue-700'
                        : 'border-gray-300 hover:border-gray-400 hover:bg-gray-50'
                    }`}
                  >
                    <input
                      type="radio"
                      name="gender"
                      value={gender}
                      checked={form.gender === gender}
                      onChange={handleChange}
                      className="sr-only"
                    />
                    <span className="font-medium">{gender}</span>
                  </label>
                ))}
              </div>
            </div>
          </div>

          {/* Submit Button */}
          <div className="mt-8 pt-6 border-t border-gray-200">
            <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
              <div>
                <p className="text-sm text-gray-600">
                  All changes are saved securely to your account
                </p>
              </div>
              <div className="flex gap-3 w-full sm:w-auto">
                <CustomButton
                  type="button"
                  variant="outline"
                  className="flex-1 sm:flex-none px-8 py-3"
                  onClick={() => window.location.reload()}
                >
                  Cancel
                </CustomButton>
                <CustomButton
                  type="submit"
                  isLoading={isLoading}
                  className="flex-1 sm:flex-none px-8 py-3"
                >
                  <Save className="w-5 h-5 mr-2" />
                  Save Changes
                </CustomButton>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};

export default StudentProfile;