'use client';

import { useState, useEffect, use } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import ProfileImageUploadModal from '@/components/ProfileImageUploadModal';
import FreelancerLayout from '@/components/layout/FreelancerLayout';
import './profile.css';

interface FreelancerProfilePageProps {
  params: Promise<{
    locale: string;
  }>;
}

interface ProfileData {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string;
  // country: string;
  city: string;
  zipCode: string;
  profileImage: string;
  rating: number;
  reviewCount: number;
  profileCompletion: number;
  bio: string;
  skills: string[];
  hourlyRate: number;
  availability: string;
}

export default function FreelancerProfilePage({ params }: FreelancerProfilePageProps) {
  const { locale } = use(params);
  const router = useRouter();
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  
  const [profileData, setProfileData] = useState<ProfileData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isUpdating, setIsUpdating] = useState(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [countries, setCountries] = useState<any[]>([]);
  
  // Form states
  const [profileForm, setProfileForm] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    country: '',
    city: '',
    zipCode: ''
  });
  
  const [passwordForm, setPasswordForm] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  
  const [showPassword, setShowPassword] = useState({
    old: false,
    new: false,
    confirm: false
  });

  useEffect(() => {
    if (status === 'loading') return;
    
    if (!session) {
      router.push(`/${locale}/login`);
      return;
    }

    fetchProfile();
    //fetchCountries();
  }, [session, status, locale, router]);

  // const fetchCountries = async () => {
  //   try {
  //     const response = await fetch('/api/countries');
  //     if (response.ok) {
  //       const data = await response.json();
  //       setCountries(data.countries || []);
        
  //       // Set default country to Switzerland if available
  //       const switzerland = data.countries?.find((country: any) => 
  //         country.name.toLowerCase() === 'switzerland' || country.code.toLowerCase() === 'ch'
  //       );
  //       if (switzerland && !profileForm.country) {
  //         setProfileForm(prev => ({
  //           ...prev,
  //           country: switzerland.id
  //         }));
  //       }
  //     }
  //   } catch (error) {
  //     console.error('Error fetching countries:', error);
  //     // Fallback to mock countries if API fails
  //     const mockCountries = [
  //       { id: 'switzerland', name: 'Switzerland', code: 'CH' },
  //       { id: 'luxembourg', name: 'Luxembourg', code: 'LU' },
  //       { id: 'belgium', name: 'Belgium', code: 'BE' },
  //       { id: 'france', name: 'France', code: 'FR' },
  //       { id: 'italy', name: 'Italy', code: 'IT' },
  //       { id: 'uk', name: 'United Kingdom', code: 'GB' },
  //       { id: 'portugal', name: 'Portugal', code: 'PT' },
  //       { id: 'spain', name: 'Spain', code: 'ES' },
  //       { id: 'germany', name: 'Germany', code: 'DE' },
  //       { id: 'austria', name: 'Austria', code: 'AT' }
  //     ];
  //     setCountries(mockCountries);
      
  //     // Set default to Switzerland
  //     if (!profileForm.country) {
  //       setProfileForm(prev => ({
  //         ...prev,
  //         country: 'switzerland'
  //       }));
  //     }
  //   }
  // };


  const fetchProfile = async () => {
    try {
      const response = await fetch('/api/freelancer/profile');
      
      if (!response.ok) {
        if (response.status === 401) {
          router.push(`/${locale}/login`);
          return;
        }
        throw new Error('Failed to fetch profile');
      }
      
      const data = await response.json();
      setProfileData(data.data);
      
      // Update form with fetched data
      const profile = data.data;
      setProfileForm({
        firstName: profile.firstName || '',
        lastName: profile.lastName || '',
        email: profile.email || '',
        phone: profile.phone || '',
        country: profile.country || '',
        city: profile.city || '',
        zipCode: profile.zipCode || ''
      });
      
    } catch (error) {
      console.error('Error fetching profile:', error);
      showError('Failed to load profile data');
    } finally {
      setIsLoading(false);
    }
  };

  const handleProfileUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsUpdating(true);

    // Debug logging
    console.log('Sending profile update data:', profileForm);

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

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to update profile');
      }

      const data = await response.json();
      console.log('Profile update response:', data.data);
      setProfileData(data.data);
      showSuccess('Profile updated successfully!');
      
    } catch (error: any) {
      console.error('Error updating profile:', error);
      showError(error.message || 'Failed to update profile');
    } finally {
      setIsUpdating(false);
    }
  };

  const handlePasswordUpdate = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      showError('New passwords do not match');
      return;
    }
    
    if (passwordForm.newPassword.length < 6) {
      showError('New password must be at least 6 characters long');
      return;
    }

    setIsUpdating(true);

    try {
      const response = await fetch('/api/freelancer/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to change password');
      }

      showSuccess('Password changed successfully!');
      setPasswordForm({
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      });
      
    } catch (error: any) {
      console.error('Error changing password:', error);
      // showError(error.message || 'Failed to change password');
    } finally {
      setIsUpdating(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setProfileForm(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handlePasswordInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setPasswordForm(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const togglePasswordVisibility = (field: 'old' | 'new' | 'confirm') => {
    setShowPassword(prev => ({
      ...prev,
      [field]: !prev[field]
    }));
  };

  const handleProfileImageUpdate = (newImageUrl: string) => {
    if (profileData) {
      setProfileData(prev => prev ? { ...prev, profileImage: newImageUrl } : null);
      // Also update the session if possible to reflect changes across the app
      if (session?.user) {
        // This will trigger a session update in NextAuth
        // The image will be reflected in other components that use session.user.image
        fetch('/api/auth/session', { method: 'GET' }).then(() => {
          window.location.reload(); // Force a refresh to update all components
        });
      }
    }
  };

  const renderStars = (rating: number) => {
    return (
      <div className="star-display">
        {[1, 2, 3, 4, 5].map((star) => (
          <svg
            key={star}
            width="13"
            height="12"
            viewBox="0 0 13 12"
            fill={star <= rating ? "#FB6107" : "none"}
            stroke="#FB6107"
            strokeWidth="1"
          >
            <path d="M10.2062 12L6.5 9.96162L2.79241 12L3.50213 7.67959L0.5 4.62053L4.64478 3.99059L6.5 0L8.35522 3.99059L12.5 4.62053L9.49787 7.68107L10.2062 12Z"/>
          </svg>
        ))}
      </div>
    );
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="loading-container">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  }

  if (!profileData) {
    return (
      <div className="error-container">
        <h2>Unable to load profile</h2>
        <p>There was an error loading your profile data. Please try again.</p>
        <button onClick={fetchProfile} className="custom-btn primary-fill">
          Retry
        </button>
      </div>
    );
  }

  return (
    <FreelancerLayout 
      locale={locale}
      userProfile={{
        name: `${profileData.firstName} ${profileData.lastName}`,
        profileImage: profileData.profileImage || "/assets/image/profile03.png",
        rating: profileData.rating,
        reviewCount: profileData.reviewCount
      }}
      unreadMessagesCount={0}
    >
            <div className="content-box">
              <div className="welcome-head">
                <div className="welcome-left">
                  <div className="progress-container">
                    <div className="progress-circle">
                      <svg width="56" height="56">
                        <circle cx="28" cy="28" r="24" className="bg" />
                        <circle 
                          cx="28" 
                          cy="28" 
                          r="24" 
                          className="progress" 
                          style={{
                            strokeDasharray: `${2 * Math.PI * 24}`,
                            strokeDashoffset: `${2 * Math.PI * 24 * (1 - profileData.profileCompletion / 100)}`
                          }}
                        />
                      </svg>
                      <div className="percentage">{profileData.profileCompletion}%</div>
                    </div>
                  </div>
                  <div className="welcome-content">
                    <h6>
                      Hi {profileData.firstName}! Please complete your profile.
                    </h6>
                    <p>
                      Let's spend a few minutes in optimizing your profile to maximize your opportunities.
                    </p>
                  </div>
                </div>
                <div className="welcome-img">
                  <img src="/assets/image/profile-bg.png" alt="profile-bg" />
                </div>
              </div>
              
              <div className="content-box-inner">
                <div className="tab-title">
                  <h5>Edit Profile</h5>
                </div>
                
                {/* Profile Image Upload Section */}
                <div className="profile-image-upload-section mb-4">
                  <div className="profile-image-container">
                    <img 
                      src={profileData.profileImage || "/assets/image/profile03.png"} 
                      alt="Profile" 
                      className="profile-image-preview"
                    />
                    <button 
                      type="button" 
                      className="upload-image-btn"
                      onClick={() => setIsUploadModalOpen(true)}
                    >
                      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M14.5 4H9L7 6H4C2.9 6 2 6.9 2 8V18C2 19.1 2.9 20 4 20H20C21.1 20 22 19.1 22 18V8C22 6.9 21.1 6 20 6H17L15 4H14.5ZM12 17C9.24 17 7 14.76 7 12C7 9.24 9.24 7 12 7C14.76 7 17 9.24 17 12C17 14.76 14.76 17 12 17Z" fill="currentColor"/>
                        <path d="M12 9C10.34 9 9 10.34 9 12C9 13.66 10.34 15 12 15C13.66 15 15 13.66 15 12C15 10.34 13.66 9 12 9Z" fill="currentColor"/>
                      </svg>
                    </button>
                  </div>
                  <p className="upload-hint">Click the icon to upload a new profile image</p>
                </div>
                <div className="form-wrap">
                  <form onSubmit={handleProfileUpdate}>
                    <div className="form-group">
                      <div className="mb-20">
                        <label htmlFor="firstName" className="form-label">First Name <span className='text-danger'>*</span></label>
                        <div className="input-icon">
                          <input 
                            type="text" 
                            className="form-control" 
                            name="firstName" 
                            id="firstName" 
                            placeholder="First Name"
                            value={profileForm.firstName}
                            onChange={handleInputChange}
                            required
                          />
                        </div>
                      </div>
                      <div className="mb-20">
                        <label htmlFor="lastName" className="form-label">Last Name <span className='text-danger'>*</span></label>
                        <div className="input-icon">
                          <input 
                            type="text" 
                            className="form-control" 
                            name="lastName" 
                            id="lastName" 
                            placeholder="Last Name"
                            value={profileForm.lastName}
                            onChange={handleInputChange}
                            required
                          />
                        </div>
                      </div>
                    </div>

                    <div className="form-group">
                      <div className="mb-20">
                        <label htmlFor="email" className="form-label">Email Address <span className='text-danger'>*</span></label>
                        <div className="input-icon">
                          <input 
                            type="email" 
                            className="form-control" 
                            name="email" 
                            id="email" 
                            placeholder="Email Address"
                            value={profileForm.email}
                            onChange={handleInputChange}
                            required
                            readOnly
                          />
                        </div>
                      </div>
                      <div className="mb-20">
                        <label htmlFor="phone" className="form-label">Phone Number <span className='text-danger'>*</span></label>
                        <div className="input-icon">
                          <input 
                            type="tel" 
                            className="form-control" 
                            name="phone" 
                            id="phone" 
                            placeholder="Phone Number"
                            value={profileForm.phone}
                            onChange={handleInputChange}
                            required
                          />
                        </div>
                      </div>
                    </div>
                    
                    <div className="form-group no-icon-box">
                      {/* <div className="mb-20">
                        <label htmlFor="country" className="form-label">Country</label>
                        <div className="input-icon">
                          <div className='custom-sub-select'>
                            <select 
                              name="country" 
                              id="country" 
                              className="form-control"
                              value={profileForm.country}
                              onChange={handleInputChange}
                            >
                              <option value="">Select a country</option>
                              {countries.map((country) => (
                                <option key={country.id} value={country.id}>
                                  {country.name}
                                </option>
                              ))}
                            </select>
                          </div>
                        </div>
                      </div> */}
                      <div className="mb-20">
                        <label htmlFor="city" className="form-label">City</label>
                        <div className="input-icon">
                          <input 
                            type="text" 
                            className="form-control" 
                            name="city" 
                            id="city" 
                            placeholder="Enter City"
                            value={profileForm.city}
                            onChange={handleInputChange}
                          />
                        </div>
                      </div>
                      <div className="mb-20 no-icon-box">
                        <label htmlFor="zipCode" className="form-label">Zip Code</label>
                        <div className="input-icon">
                          <input 
                            type="text" 
                            className="form-control" 
                            name="zipCode" 
                            id="zipCode" 
                            placeholder="Zip Code"
                            value={profileForm.zipCode}
                            onChange={handleInputChange}
                          />
                        </div>
                      </div>
                    </div>
                    
                    <button 
                      type="submit" 
                      className="w-100 custom-btn secondary-btn"
                      disabled={isUpdating}
                    >
                      {isUpdating ? 'Updating...' : 'Update'}
                    </button>
                  </form>
                </div>
              </div>
              
              <div className="content-box-inner">
                <div className="tab-title">
                  <h5>Change Password</h5>
                </div>
                <div className="form-wrap">
                  <form onSubmit={handlePasswordUpdate}>
                    <div className="form-group">
                      <div className="mb-20">
                        <label htmlFor="oldPassword" className="form-label">Old Password <span className='text-danger'>*</span></label>
                        <div className="input-icon">
                          <input 
                            type={showPassword.old ? "text" : "password"}
                            className="form-control" 
                            name="oldPassword" 
                            id="oldPassword" 
                            placeholder="Enter Old Password"
                            value={passwordForm.oldPassword}
                            onChange={handlePasswordInputChange}
                            required
                          />
                          <div className="password-show-hide" onClick={() => togglePasswordVisibility('old')}>
                            {/* <img 
                              src="/assets/image/eye.svg" 
                              className="icon" 
                              alt="toggle password"
                            /> */}
                            <img 
                              src={showPassword.old ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPassword.old ? "hide password" : "show password"}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <div className="form-group">
                      <div className="mb-20">
                        <label htmlFor="newPassword" className="form-label">New Password <span className='text-danger'>*</span></label>
                        <div className="input-icon">
                          <input 
                            type={showPassword.new ? "text" : "password"}
                            className="form-control" 
                            name="newPassword" 
                            id="newPassword" 
                            placeholder="Enter New Password"
                            value={passwordForm.newPassword}
                            onChange={handlePasswordInputChange}
                            required
                          />
                          <div className="password-show-hide" onClick={() => togglePasswordVisibility('new')}>
                            {/* <img 
                              src="/assets/image/eye.svg" 
                              className="icon" 
                              alt="toggle password" 
                            /> */}
                            <img 
                              src={showPassword.new ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPassword.new ? "hide password" : "show password"}
                            />
                          </div>
                        </div>
                      </div>

                      <div className="mb-20">
                        <label htmlFor="confirmPassword" className="form-label">Confirm New Password <span className='text-danger'>*</span></label>
                        <div className="input-icon">
                          <input 
                            type={showPassword.confirm ? "text" : "password"}
                            className="form-control" 
                            name="confirmPassword" 
                            id="confirmPassword" 
                            placeholder="Confirm New Password"
                            value={passwordForm.confirmPassword}
                            onChange={handlePasswordInputChange}
                            required
                          />
                          <div className="password-show-hide" onClick={() => togglePasswordVisibility('confirm')}>
                            {/* <img 
                              src="/assets/image/eye.svg" 
                              className="icon" 
                              alt="toggle password" 
                            /> */}
                            <img 
                              src={showPassword.confirm ? "/assets/image/eye-slash.svg" : "/assets/image/eye.svg"} 
                              className="icon" 
                              alt={showPassword.confirm ? "hide password" : "show password"}
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                    
                    <button 
                      type="submit" 
                      className="w-100 custom-btn secondary-btn"
                      disabled={isUpdating}
                    >
                      {isUpdating ? 'Updating...' : 'Update Password'}
                    </button>
                  </form>
                </div>
              </div>
            </div>
      {/* Profile Image Upload Modal */}
      <ProfileImageUploadModal
        isOpen={isUploadModalOpen}
        onClose={() => setIsUploadModalOpen(false)}
        currentImage={profileData.profileImage}
        onImageUpdated={handleProfileImageUpdate}
      />
    </FreelancerLayout>
  );
}