// app/foreign-student/dashboard/profile/foreign-student-profile.jsx
'use client';

import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import Swal from 'sweetalert2';
import { 
  FaGlobe, 
  FaUserGraduate, 
  FaDollarSign, 
  FaImage,
  FaBriefcase,
  FaUser,
  FaPhone,
  FaEnvelope,
  FaSave,
  FaTimes,
  FaSpinner,
  FaUpload,
  FaCheckCircle
} from 'react-icons/fa';
import { getCountries } from '../../../utils/countryStateCityAPI';

const ForeignStudentProfile = () => {
  const router = useRouter();
  
  const initialFormState = {
    name: '',
    email: '',
    phone: '',
    country_id: '',
    about_me: '',
    profile_picture: '',
    hour_rate: '',
    gender: '',
    experience: '',
    last_education: '',
  };

  const [form, setForm] = useState(initialFormState);
  const [countries, setCountries] = useState([]);
  const [errors, setErrors] = useState({});
  const [isLoading, setIsLoading] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadedImage, setUploadedImage] = useState(null);
  const [hasChanges, setHasChanges] = useState(false);

  // Education and Gender Options
  const educationOptions = useMemo(() => [
    { value: 'high_school', label: 'High School' },
    { value: 'bachelors', label: 'Bachelor\'s Degree' },
    { value: 'masters', label: 'Master\'s Degree' },
    { value: 'phd', label: 'PhD' },
    { value: 'diploma', label: 'Diploma' },
    { value: 'certificate', label: 'Certificate' }
  ], []);

  const genderOptions = useMemo(() => [
    { value: 'male', label: 'Male' },
    { value: 'female', label: 'Female' },
    { value: 'other', label: 'Other' }
  ], []);

  // Image Upload Handler
  const uploadImage = useCallback(async (file) => {
    const formData = new FormData();
    formData.append('image', file);
    formData.append('uploadType', 'student-profile');

    const response = await fetch('/api/frontend/upload', {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error('Failed to upload image');
    }

    const data = await response.json();
    return data.s3Key || data.url;
  }, []);

  const handleFileUpload = useCallback(async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // Validation
    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    const maxSize = 5 * 1024 * 1024; // 5MB

    if (!validTypes.includes(file.type)) {
      Swal.fire({
        icon: 'error',
        title: 'Invalid File',
        text: 'Please upload JPG, PNG, GIF, or WebP images only',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    if (file.size > maxSize) {
      Swal.fire({
        icon: 'error',
        title: 'File Too Large',
        text: 'Maximum file size is 5MB',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    try {
      setIsUploading(true);
      const imageUrl = await uploadImage(file);
      
      const previewUrl = URL.createObjectURL(file);
      setUploadedImage({
        file,
        preview: previewUrl,
        url: imageUrl
      });
      
      setForm(prev => ({
        ...prev,
        profile_picture: imageUrl
      }));
      
      setHasChanges(true);
      if (errors.profile_picture) {
        setErrors(prev => ({ ...prev, profile_picture: null }));
      }

      Swal.fire({
        icon: 'success',
        title: 'Image Uploaded!',
        text: 'Profile picture updated successfully',
        timer: 1500,
        showConfirmButton: false,
      });
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Upload Failed',
        text: error.message || 'Please try again',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setIsUploading(false);
    }
  }, [errors.profile_picture, uploadImage]);

  const removeImage = useCallback(() => {
    if (uploadedImage?.preview) {
      URL.revokeObjectURL(uploadedImage.preview);
    }
    setUploadedImage(null);
    setForm(prev => ({ ...prev, profile_picture: '' }));
    setHasChanges(true);
  }, [uploadedImage]);

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

  const fetchStudentData = useCallback(async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/internal/foreign-student/profile', {
        method: 'GET',
        credentials: 'include'
      });
      
      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.message || 'Failed to fetch profile');
      }

      const data = await response.json();

      if (data.success && data.data) {
        const studentData = {
          name: data.data.name || '',
          email: data.data.email || '',
          phone: data.data.phone || '',
          country_id: data.data.country_id ? String(data.data.country_id) : '',
          about_me: data.data.about_me || '',
          profile_picture: data.data.profile_picture || '',
          hour_rate: data.data.hour_rate || '',
          gender: data.data.gender || '',
          experience: data.data.experience || '',
          last_education: data.data.last_education || '',
        };

        setForm(studentData);
        
        if (data.data.profile_picture) {
          setUploadedImage({
            preview: `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${data.data.profile_picture}`,
            url: `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${data.data.profile_picture}`
          });
        }
      }
    } catch (error) {
      console.error('Error fetching student data:', error);
      Swal.fire({
        icon: 'error',
        title: 'Load Error',
        text: 'Failed to load profile data',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Effects
  useEffect(() => {
    fetchCountries();
    fetchStudentData();
  }, [fetchCountries, fetchStudentData]);

  useEffect(() => {
    return () => {
      if (uploadedImage?.preview) {
        URL.revokeObjectURL(uploadedImage.preview);
      }
    };
  }, [uploadedImage]);

  // Form Handlers
  const handleChange = useCallback((e) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
    setHasChanges(true);
    
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
  }, [errors]);

  const handleCountryChange = useCallback((e) => {
    const value = e.target.value;
    setForm(prev => ({
      ...prev,
      country_id: value
    }));
    setHasChanges(true);
    
    if (errors.country_id) {
      setErrors(prev => ({ ...prev, country_id: null }));
    }
  }, [errors]);

  const handleSubmit = useCallback(async (e) => {
    e.preventDefault();
    setErrors({});
    setIsSubmitting(true);

    try {
      const response = await fetch('/api/internal/foreign-student/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...form,
          hour_rate: form.hour_rate ? parseFloat(form.hour_rate) : 0,
          country_id: form.country_id ? parseInt(form.country_id) : null,
          phone: form.phone || null,
          about_me: form.about_me || null,
          experience: form.experience || null,
        }),
        credentials: 'include'
      });

      const data = await response.json();

      if (response.ok) {
        // Update localStorage
        const currentUserData = JSON.parse(localStorage.getItem('foreignStudentData') || '{}');
        localStorage.setItem('foreignStudentData', JSON.stringify({
          ...currentUserData,
          ...form
        }));

        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Your profile has been updated',
          confirmButtonColor: '#0B6D76',
          timer: 2000,
          showConfirmButton: false,
        });

        setHasChanges(false);
        router.refresh();
      } else {
        if (data.errors) {
          setErrors(data.errors);
          
          const errorMessages = Object.values(data.errors).join('\n');
          Swal.fire({
            icon: 'error',
            title: 'Validation Error',
            html: `<div class="text-left"><p>Please fix the following errors:</p><ul class="mt-2 list-disc pl-4">${Object.values(data.errors).map(err => `<li>${err}</li>`).join('')}</ul></div>`,
            confirmButtonColor: '#0B6D76',
          });
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Update Failed',
            text: data.message || 'Please try again',
            confirmButtonColor: '#0B6D76',
          });
        }
      }
    } catch (err) {
      console.error('Profile update error:', err);
      Swal.fire({
        icon: 'error',
        title: 'Network Error',
        text: 'Please check your connection',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setIsSubmitting(false);
    }
  }, [form, router]);

  // Derived values
  const countryOptions = useMemo(() => 
    countries.map(country => ({
      label: country.name,
      value: String(country.id)
    })), [countries]
  );

  // Loading state
  if (isLoading && Object.keys(form).every(key => form[key] === '')) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-teal-600 mb-4"></div>
          <p className="text-gray-600">Loading your profile...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900">Profile Settings</h1>
          <p className="text-gray-600 mt-2">
            Update your teaching profile to attract more students
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Profile Picture Section */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="flex items-center mb-6">
              <div className="w-10 h-10 bg-teal-100 rounded-lg flex items-center justify-center mr-3">
                <FaUser className="text-teal-600" />
              </div>
              <div>
                <h2 className="text-xl font-semibold text-gray-900">Profile Picture</h2>
                <p className="text-gray-600 text-sm">Upload a professional photo for your teaching profile</p>
              </div>
            </div>
            
            <div className="flex flex-col md:flex-row items-center gap-6">
              {/* Avatar Preview */}
              <div className="relative">
                <div className="relative w-40 h-40 rounded-lg border-2 border-gray-200 overflow-hidden bg-gray-100">
                  {uploadedImage ? (
                    <img
                      src={uploadedImage.preview}
                      alt="Profile preview"
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <FaUser className="text-gray-400 text-6xl" />
                    </div>
                  )}
                </div>
                
                {uploadedImage && (
                  <button
                    type="button"
                    onClick={removeImage}
                    className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full w-8 h-8 flex items-center justify-center text-sm hover:bg-red-600 transition-colors"
                    aria-label="Remove image"
                  >
                    <FaTimes />
                  </button>
                )}
              </div>

              {/* Upload Controls */}
              <div className="flex-1">
                <div className="space-y-4">
                  <label className="block">
                    <div className="inline-flex items-center gap-2 px-5 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors cursor-pointer">
                      {isUploading ? (
                        <FaSpinner className="w-4 h-4 animate-spin" />
                      ) : (
                        <FaUpload className="w-4 h-4" />
                      )}
                      <span>{isUploading ? 'Uploading...' : uploadedImage ? 'Change Photo' : 'Upload Photo'}</span>
                    </div>
                    <input
                      type="file"
                      accept="image/*"
                      onChange={handleFileUpload}
                      className="hidden"
                      disabled={isUploading}
                    />
                  </label>
                  
                  <div className="space-y-1 text-sm text-gray-500">
                    <p>• JPG, PNG, GIF or WebP</p>
                    <p>• Maximum file size: 5MB</p>
                    <p>• Recommended: 400x400 pixels</p>
                  </div>
                </div>
              </div>
            </div>
            
            {errors.profile_picture && (
              <p className="text-sm text-red-600 mt-4">{errors.profile_picture}</p>
            )}
          </div>

          {/* Personal Information Section */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="flex items-center mb-6">
              <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center mr-3">
                <FaUser className="text-blue-600" />
              </div>
              <div>
                <h2 className="text-xl font-semibold text-gray-900">Personal Information</h2>
                <p className="text-gray-600 text-sm">Basic details about yourself</p>
              </div>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Name */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Full Name *
                </label>
                <div className="relative">
                  <input
                    type="text"
                    name="name"
                    value={form.name}
                    onChange={handleChange}
                    placeholder="Your full name"
                    className="w-full px-4 py-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500"
                    required
                  />
                  <FaUser className="absolute left-3 top-3.5 text-gray-400" />
                </div>
                {errors.name && (
                  <p className="text-sm text-red-600 mt-2">{errors.name}</p>
                )}
              </div>

              {/* Email */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Email Address
                </label>
                <div className="relative">
                  <input
                    type="email"
                    name="email"
                    value={form.email}
                    onChange={handleChange}
                    placeholder="Email address"
                    disabled
                    className="w-full px-4 py-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500 bg-gray-50 cursor-not-allowed"
                  />
                  <FaEnvelope className="absolute left-3 top-3.5 text-gray-400" />
                </div>
                <p className="text-xs text-gray-500 mt-2">Contact support to change your email</p>
              </div>

              {/* Phone */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Phone Number
                </label>
                <div className="relative">
                  <input
                    type="tel"
                    name="phone"
                    value={form.phone}
                    onChange={handleChange}
                    placeholder="Your phone number"
                    className="w-full px-4 py-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500"
                  />
                  <FaPhone className="absolute left-3 top-3.5 text-gray-400" />
                </div>
                {errors.phone && (
                  <p className="text-sm text-red-600 mt-2">{errors.phone}</p>
                )}
              </div>

              {/* Country */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Country *
                </label>
                <div className="relative">
                  <select
                    name="country_id"
                    value={form.country_id}
                    onChange={handleCountryChange}
                    className="w-full px-4 py-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500 appearance-none"
                    required
                  >
                    <option value="">Select your country</option>
                    {countryOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  <FaGlobe className="absolute left-3 top-3.5 text-gray-400" />
                  <div className="absolute right-3 top-3.5 pointer-events-none">
                    <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </div>
                </div>
                {errors.country_id && (
                  <p className="text-sm text-red-600 mt-2">{errors.country_id}</p>
                )}
              </div>

              {/* Gender */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Gender *
                </label>
                <select
                  name="gender"
                  value={form.gender}
                  onChange={handleChange}
                  className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500"
                  required
                >
                  <option value="">Select Gender</option>
                  {genderOptions.map(option => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
                {errors.gender && (
                  <p className="text-sm text-red-600 mt-2">{errors.gender}</p>
                )}
              </div>

              {/* Hourly Rate */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Hourly Rate ($)
                </label>
                <div className="relative">
                  <input
                    type="number"
                    name="hour_rate"
                    value={form.hour_rate}
                    onChange={handleChange}
                    placeholder="e.g., 25"
                    step="0.01"
                    min="0"
                    className="w-full px-4 py-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500"
                  />
                  <FaDollarSign className="absolute left-3 top-3.5 text-gray-400" />
                </div>
                <p className="text-xs text-gray-500 mt-2">Set your hourly teaching rate in USD</p>
                {errors.hour_rate && (
                  <p className="text-sm text-red-600 mt-2">{errors.hour_rate}</p>
                )}
              </div>
            </div>
          </div>

          {/* Education Section */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="flex items-center mb-6">
              <div className="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center mr-3">
                <FaUserGraduate className="text-purple-600" />
              </div>
              <div>
                <h2 className="text-xl font-semibold text-gray-900">Education</h2>
                <p className="text-gray-600 text-sm">Your academic background</p>
              </div>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Education Level */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Highest Education *
                </label>
                <div className="relative">
                  <select
                    name="last_education"
                    value={form.last_education}
                    onChange={handleChange}
                    className="w-full px-4 py-3 pl-10 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500 appearance-none"
                    required
                  >
                    <option value="">Select Education Level</option>
                    {educationOptions.map(option => (
                      <option key={option.value} value={option.value}>
                        {option.label}
                      </option>
                    ))}
                  </select>
                  <FaUserGraduate className="absolute left-3 top-3.5 text-gray-400" />
                  <div className="absolute right-3 top-3.5 pointer-events-none">
                    <svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </div>
                </div>
                {errors.last_education && (
                  <p className="text-sm text-red-600 mt-2">{errors.last_education}</p>
                )}
              </div>
            </div>
          </div>

          {/* About Me Section */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="flex items-center mb-6">
              <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center mr-3">
                <span className="text-green-600 font-bold">?</span>
              </div>
              <div>
                <h2 className="text-xl font-semibold text-gray-900">About Me</h2>
                <p className="text-gray-600 text-sm">Tell students about yourself and your teaching style</p>
              </div>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                About Me *
              </label>
              <textarea
                name="about_me"
                value={form.about_me}
                onChange={handleChange}
                placeholder="Share your teaching philosophy, expertise areas, and what makes you unique..."
                rows={5}
                maxLength={2000}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500 resize-none"
                required
              />
              <div className="flex justify-between items-center mt-2">
                <p className="text-xs text-gray-500">
                  {form.about_me.length}/2000 characters
                </p>
                <p className="text-xs text-gray-500">
                  Describe your teaching approach and expertise
                </p>
              </div>
              {errors.about_me && (
                <p className="text-sm text-red-600 mt-2">{errors.about_me}</p>
              )}
            </div>
          </div>

          {/* Experience Section */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="flex items-center mb-6">
              <div className="w-10 h-10 bg-amber-100 rounded-lg flex items-center justify-center mr-3">
                <FaBriefcase className="text-amber-600" />
              </div>
              <div>
                <h2 className="text-xl font-semibold text-gray-900">Teaching Experience</h2>
                <p className="text-gray-600 text-sm">Share your qualifications and teaching background</p>
              </div>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Teaching Experience
              </label>
              <textarea
                name="experience"
                value={form.experience}
                onChange={handleChange}
                placeholder="Describe your teaching experience, years of experience, certifications, success stories..."
                rows={5}
                maxLength={5000}
                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 focus:border-teal-500 resize-none"
              />
              <div className="flex justify-between items-center mt-2">
                <p className="text-xs text-gray-500">
                  {form.experience.length}/5000 characters
                </p>
                <p className="text-xs text-gray-500">
                  Mention years of experience and specializations
                </p>
              </div>
              {errors.experience && (
                <p className="text-sm text-red-600 mt-2">{errors.experience}</p>
              )}
            </div>
          </div>

          {/* Action Section */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <div className="flex flex-col md:flex-row items-center justify-between gap-4">
              <div>
                <h3 className="font-semibold text-gray-900">Save Profile Changes</h3>
                <div className="flex items-center gap-2 mt-1">
                  {hasChanges ? (
                    <>
                      <div className="w-2 h-2 bg-amber-500 rounded-full"></div>
                      <p className="text-sm text-amber-600">You have unsaved changes</p>
                    </>
                  ) : (
                    <>
                      <FaCheckCircle className="w-4 h-4 text-green-500" />
                      <p className="text-sm text-gray-600">All changes are saved</p>
                    </>
                  )}
                </div>
              </div>
              
              <div className="flex items-center gap-4">
                <button
                  type="button"
                  onClick={() => {
                    setForm(initialFormState);
                    setHasChanges(false);
                  }}
                  disabled={!hasChanges || isSubmitting}
                  className="px-5 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Reset
                </button>
                
                <button
                  type="submit"
                  disabled={isSubmitting || isUploading || !hasChanges}
                  className="px-5 py-2.5 bg-teal-600 text-white rounded-lg hover:bg-teal-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                >
                  {isSubmitting ? (
                    <>
                      <FaSpinner className="w-4 h-4 animate-spin" />
                      Saving...
                    </>
                  ) : (
                    <>
                      <FaSave className="w-4 h-4" />
                      Save Changes
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  );
};

export default ForeignStudentProfile;