'use client';

import { useSession } from 'next-auth/react';
import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import Image from 'next/image';
import ClientSidebar from '@/components/client/ClientSidebar';
import ReviewsList from '@/components/reviews/ReviewsList';
import ReviewStats from '@/components/reviews/ReviewStats';
import { useToast } from '@/components/ui/ToastContext';
import './profile.css';

// interface Country {
//   id: string;
//   name: string;
//   code: string;
//   flag?: string;
// }

export default function ClientProfile() {
  const { data: session } = useSession();
  const params = useParams();
  const locale = params.locale as string;
  const { showSuccess, showError } = useToast();

  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
  //  country: 'switzerland',
    country: '',
    city: '',
    zipCode: '',
    address: '',
    bio: '',
    title: ''
  });
  const [isLoading, setIsLoading] = useState(false);
  const [profileImage, setProfileImage] = useState<File | null>(null);
  const [previewImage, setPreviewImage] = useState<string>('');
  // const [countries, setCountries] = useState<Country[]>([]);
  const [, setCurrentProfileImage] = useState<string>('');
  const [activeTab, setActiveTab] = useState<'profile' | 'reviews'>('profile');

  // Fetch countries on component mount
  // useEffect(() => {
  //   const fetchCountries = async () => {
  //     try {
  //       const response = await fetch('/api/countries');
  //       if (response.ok) {
  //         const data = await response.json();
  //         setCountries(data.countries);
  //       }
  //     } catch (error) {
  //       console.error('Error fetching countries:', error);
  //     }
  //   };

  //   fetchCountries();
  // }, []);

  // Fetch user profile data
  useEffect(() => {
    const fetchProfile = async () => {
      if (!session?.user) return;

      try {
        const response = await fetch('/api/profile/update', {
          headers: {
            'x-toast-controlled': 'true'
          }
        });
        if (response.ok) {
          const data = await response.json();
          const profile = data.user.profile; 
          console.log('++++++++++++++++++++++++++++++++',profile)         
          if (profile) {
            setFormData({
              firstName: profile.firstName || '',
              lastName: profile.lastName || '',
              email: data.user.email || '',
              phone: profile.phone || '',
              // country: profile.countryId || 'switzerland',
              country: profile.countryId,
              city: profile.city || '',
              zipCode: profile.zipCode || '',
              address: profile.address || '',
              bio: profile.bio || '',
              title: profile.title || ''
            });
            
            if (profile.profileImage) {
              setCurrentProfileImage(profile.profileImage);
            }
          } else {
            // If no profile exists, use session data
            setFormData(prev => ({
              ...prev,
              firstName: '',
              lastName: '',
              email: session.user?.email || '',
            }));
          }
        }
      } catch (error) {
        console.error('Error fetching profile:', error);
      }
    };

    fetchProfile();
  }, [session]);

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

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // Validate file type
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp'];
      if (!allowedTypes.includes(file.type)) {
        showError('Please select a valid image file (JPEG, PNG, or WebP)', 'Invalid File');
        return;
      }

      // Validate file size (5MB max)
      const maxSize = 5 * 1024 * 1024;
      if (file.size > maxSize) {
        showError('File size too large. Maximum size is 5MB.', 'File Too Large');
        return;
      }

      setProfileImage(file);
      const reader = new FileReader();
      reader.onload = (e) => {
        setPreviewImage(e.target?.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const removeImage = () => {
    setProfileImage(null);
    setPreviewImage('');
    const fileInput = document.getElementById('fileInput') as HTMLInputElement;
    if (fileInput) {
      fileInput.value = '';
    }
  };

  const handleImageUpdate = async () => {
    if (!profileImage) return;
    
    setIsLoading(true);
    try {
      const formDataToSend = new FormData();
      formDataToSend.append('profileImage', profileImage);
      
      // Add current form data to maintain profile info
      Object.entries(formData).forEach(([key, value]) => {
        formDataToSend.append(key, value);
      });

      const response = await fetch('/api/profile/update', {
        method: 'POST',
        headers: {
          'x-toast-controlled': 'true'
        },
        body: formDataToSend,
      });

      if (response.ok) {
        showSuccess('Profile image updated successfully!', 'Success');
        // Close modal
        const modal = document.getElementById('customModal');
        const bootstrapModal = (window as Window & { bootstrap?: { Modal?: { getInstance: (element: Element | null) => { hide: () => void } | null } } }).bootstrap?.Modal?.getInstance(modal);
        bootstrapModal?.hide();
        // Reset image states
        setProfileImage(null);
        setPreviewImage('');
      } else {
        const errorData = await response.json();
        showError(errorData.message || 'Failed to update profile image', 'Error');
      }
    } catch (error) {
      console.error('Profile image update error:', error);
      showError('An error occurred while updating profile image', 'Error');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Client-side validation
    if (!formData.firstName.trim()) {
      showError('First name is required', 'Validation Error');
      return;
    }
    
    if (!formData.lastName.trim()) {
      showError('Last name is required', 'Validation Error');
      return;
    }
    
    if (!formData.email.trim()) {
      showError('Email is required', 'Validation Error');
      return;
    }
    if(!formData.country.trim()){
      showError('Country is required', 'Validation Error');
      return;
    }
    setIsLoading(true);

    try {
      const formDataToSend = new FormData();
      
      // Append all form fields
      Object.entries(formData).forEach(([key, value]) => {
        formDataToSend.append(key, value);
      });

      // Only append profile image if one is selected
      if (profileImage) {
        formDataToSend.append('profileImage', profileImage);
      }

      const response = await fetch('/api/profile/update', {
        method: 'POST',
        headers: {
          'x-toast-controlled': 'true'
        },
        body: formDataToSend,
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
      }

      const responseData = await response.json();
      showSuccess('Profile updated successfully!', 'Success');
      
      // Update current profile image if a new one was uploaded
      if (responseData.profile?.profileImage) {
        setCurrentProfileImage(responseData.profile.profileImage);
      }
      
      // Reset image selection
      setProfileImage(null);
      setPreviewImage('');
      
      // Reset file input
      const fileInput = document.getElementById('fileInput') as HTMLInputElement;
      if (fileInput) {
        fileInput.value = '';
      }

    } catch (error) {
      console.error('Profile update error:', error);
      
      if (error instanceof Error) {
        showError(error.message, 'Error');
      } else {
        showError('An error occurred while updating profile', 'Error');
      }
    } finally {
      setIsLoading(false);
    }
  };
  return (
    <section className="profile-wrapper create-project-wrapper py-60">
      <div className="container">
        <div className="row">
          <div className="col-12 col-md-4 col-xl-3">
            <ClientSidebar locale={locale} />
          </div>
          <div className="col-12 col-md-8 col-xl-9">
            <div className="content-box">
              {/* Tab Navigation */}
              {/* <div className="profile-tabs">
                <button 
                  type="button"
                  className={`tab-btn ${activeTab === 'profile' ? 'active' : ''}`}
                  onClick={() => setActiveTab('profile')}
                >
                  Profile Settings
                </button>
                <button 
                  type="button"
                  className={`tab-btn ${activeTab === 'reviews' ? 'active' : ''}`}
                  onClick={() => setActiveTab('reviews')}
                >
                  My Reviews
                </button>
              </div> */}

              {/* Profile Tab Content */}
              {activeTab === 'profile' && (
                <>
                  <div className="tab-title">
                    <h5>Update Profile</h5>
                  </div>
                  <div className="form-wrap mt-0">
                    <form onSubmit={handleSubmit}>
                  <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={formData.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={formData.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={formData.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={formData.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
                            id="country"
                            name="country"
                            className="form-control"
                            value={formData.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={formData.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={formData.zipCode}
                          onChange={handleInputChange}
                        />
                      </div>
                    </div>
                  </div>

                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="address" className="form-label">Address</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          name="address"
                          id="address"
                          placeholder="Enter Address"
                          value={formData.address}
                          onChange={handleInputChange}
                        />
                      </div>
                    </div>
                    <div className="mb-20">
                      <label htmlFor="title" className="form-label">Professional Title</label>
                      <div className="input-icon">
                        <input
                          type="text"
                          className="form-control"
                          name="title"
                          id="title"
                          placeholder="e.g., Software Developer, Designer"
                          value={formData.title}
                          onChange={handleInputChange}
                        />
                      </div>
                    </div>
                  </div>

                  <div className="form-group">
                    <div className="mb-20">
                      <label htmlFor="bio" className="form-label">Bio</label>
                      <div className="input-icon">
                        <textarea
                          className="form-control"
                          name="bio"
                          id="bio"
                          rows={4}
                          placeholder="Tell us about yourself..."
                          value={formData.bio}
                          onChange={handleInputChange}
                          style={{ resize: 'vertical', minHeight: '100px' }}
                        />
                      </div>
                    </div>
                  </div>

                      <button
                        type="submit"
                        className="w-100 custom-btn secondary-btn"
                        disabled={isLoading}
                      >
                        {isLoading ? 'Updating...' : 'Update'}
                      </button>
                    </form>
                  </div>
                </>
              )}

              {/* Reviews Tab Content */}
              {activeTab === 'reviews' && (
                <div className="reviews-tab-content">
                  <div className="tab-title">
                    <h5>My Reviews</h5>
                  </div>
                  <div className="reviews-section">
                    {/* Reviews Stats */}
                    <ReviewStats 
                      userId={session?.user?.id || ''} 
                      userType="client" 
                      className="mb-4"
                    />
                    
                    {/* Reviews List */}
                    <ReviewsList 
                      freelancerId=""
                      clientId={session?.user?.id || ''}
                      showAll={true}
                      limit={10}
                    />
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Profile Image Modal */}
      <div className="modal fade custom-modal" id="customModal" tabIndex={-1} aria-labelledby="customModalLabel" aria-hidden="true">
        <div className="modal-dialog modal-dialog-centered">
          <div className="modal-content">
            <div className="tab-title mb-4">
              <h5>Update Profile Picture</h5>
              <button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div className="upload-outer">
              <label className="form-label fw-semibold">Upload Profile Picture</label>
              <div 
                className="upload-area position-relative" 
                id="uploadArea"
                onClick={() => document.getElementById('fileInput')?.click()}
              >
                {previewImage ? (
                  <div id="previewBox" className="position-relative d-inline-block">
                    <Image
                      id="previewImage"
                      src={previewImage}
                      className="rounded"
                      style={{ objectFit: 'cover' }}
                      alt="Preview"
                      width={200}
                      height={200}
                    />
                    <button
                      type="button"
                      className="btn btn-sm position-absolute top-0 end-0 rounded-circle p-0 remove-btn"
                      title="Remove"
                      onClick={removeImage}
                    >
                      <span className="text-danger fs-5 fw-bold">&times;</span>
                    </button>
                  </div>
                ) : (
                  <div id="placeholder" className="upload-placeholder">
                    <svg width="69" height="60" viewBox="0 0 69 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M46.208 5.70117C46.6948 5.70117 47.0897 6.09627 47.0898 6.58301C47.0898 7.06987 46.6949 7.46484 46.208 7.46484C42.0957 7.46495 38.405 10.2157 37.2334 14.1523C37.1047 14.5864 36.6701 14.848 36.2324 14.7686L36.2285 14.7734L36.1367 14.7461C35.6703 14.607 35.4039 14.1162 35.543 13.6494C36.9067 9.06679 41.154 5.70127 46.208 5.70117Z" fill="#0E9493" stroke="#787676" strokeWidth="0.3"/>
                      <path d="M56.4522 42.4384H52.0618C51.6578 42.4384 51.3301 42.1107 51.3301 41.7067C51.3301 41.3027 51.6578 40.9749 52.0618 40.9749H56.4522C62.504 40.9749 67.4281 36.0509 67.4281 29.999C67.4281 23.9471 62.504 19.023 56.4522 19.023H56.3466C56.1344 19.023 55.9326 18.9311 55.7936 18.7706C55.6546 18.6101 55.5918 18.3974 55.6222 18.1873C55.6875 17.7315 55.7204 17.2737 55.7204 16.8279C55.7204 11.5829 51.4528 7.31531 46.2079 7.31531C44.1674 7.31531 42.2215 7.95296 40.5803 9.15978C40.2196 9.42478 39.7074 9.30718 39.4989 8.91047C34.8509 0.0596993 22.7107 -1.12887 16.4166 6.57053C13.7652 9.81417 12.7234 14.0336 13.5582 18.146C13.6502 18.6002 13.3026 19.0236 12.8411 19.0236H12.5479C6.496 19.0236 1.57193 23.9477 1.57193 29.9996C1.57193 36.0514 6.496 40.9755 12.5479 40.9755H16.9382C17.3422 40.9755 17.6699 41.3032 17.6699 41.7072C17.6699 42.1113 17.3422 42.439 16.9382 42.439H12.5479C5.6889 42.439 0.108398 36.8585 0.108398 29.9995C0.108398 23.3329 5.37995 17.8742 11.9735 17.5731C11.3541 13.3066 12.5385 9.00295 15.2835 5.64437C22.0222 -2.5996 34.9364 -1.67556 40.3955 7.51707C42.1371 6.42522 44.1299 5.85244 46.2076 5.85244C52.5622 5.85244 57.5976 11.261 57.157 17.58C63.6897 17.9463 68.8913 23.3763 68.8913 29.999C68.8913 36.8585 63.3108 42.4384 56.4518 42.4384L56.4522 42.4384Z" fill="#0E9493"/>
                      <path d="M34.4023 22.8496C44.5721 22.8499 52.8457 31.1242 52.8457 41.2939C52.8454 51.4634 44.5719 59.7371 34.4023 59.7373C24.2327 59.7373 15.9583 51.4637 15.958 41.2939C15.958 31.1241 24.2324 22.8496 34.4023 22.8496ZM34.4023 24.6143C25.2053 24.6143 17.7227 32.097 17.7227 41.2939C17.7229 50.4908 25.2056 57.9736 34.4023 57.9736C43.5989 57.9734 51.0818 50.4905 51.082 41.2939C51.082 32.0971 43.599 24.6145 34.4023 24.6143Z" fill="#0E9493" stroke="#787676" strokeWidth="0.3"/>
                      <path d="M34.7368 34.043C35.1153 34.0432 35.4224 34.351 35.4224 34.7295V48.6572C35.4224 49.0362 35.1152 49.3435 34.7368 49.3438C34.3582 49.3438 34.0503 49.0359 34.0503 48.6572V34.7295C34.0503 34.3509 34.3582 34.043 34.7368 34.043Z" fill="#0E9493" stroke="#0E9493" strokeWidth="0.3"/>
                      <path d="M34.252 34.2461C34.5196 33.9784 34.954 33.9784 35.2217 34.2461L39.5068 38.5322C39.7746 38.8001 39.7747 39.2341 39.5068 39.502L39.5059 39.501C39.372 39.6351 39.197 39.7021 39.0225 39.7021C38.8474 39.7021 38.6708 39.6356 38.5371 39.502L34.7363 35.7002L30.9355 39.502C30.668 39.7696 30.2335 39.7696 29.9658 39.502C29.698 39.2342 29.6982 38.8001 29.9658 38.5322L34.252 34.2461Z" fill="#0E9493" stroke="#0E9493" strokeWidth="0.3"/>
                    </svg>
                    <p>Drag & drop files or <a href="#" className="text-decoration-none">Browse</a></p>
                    <small className="text-muted">Supported formats: .jpg & .png</small>
                  </div>
                )}
                <input
                  type="file"
                  className="d-none"
                  id="fileInput"
                  accept="image/png, image/jpeg"
                  onChange={handleImageChange}
                />
              </div>
            </div>
            <div className="d-flex">
              <button
                className={`custom-btn secondary-btn mt-4 ${!previewImage ? 'd-none' : ''}`}
                id="updateBtn"
                onClick={handleImageUpdate}
                disabled={isLoading}
              >
                {isLoading ? 'Updating...' : 'Update'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}