'use client';

import { useState, useEffect, use } from 'react';
import { useSession } from 'next-auth/react';
import { useToast } from '@/components/ui/ToastContext';
import FreelancerLayout from '@/components/layout/FreelancerLayout';
import { useFreelancerProfile } from '@/hooks/useFreelancerProfile';

interface ProfileData {
  id: string;
  firstName: string;
  lastName: string;
  profileImage: string;
  profileCompletion: number;
}

interface OnBoardData {
  companyName: string;
  currency: string;
  dateOfBirth: string;
  headline: string;
  aboutYourself: string;
}

const CURRENCIES = [
  { value: 'USD', label: '🇺🇸 US Dollar (USD)', flag: '🇺🇸' },
  { value: 'EUR', label: '🇪🇺 Euro (EUR)', flag: '🇪🇺' },
  { value: 'GBP', label: '🇬🇧 British Pound (GBP)', flag: '🇬🇧' },
  { value: 'INR', label: '🇮🇳 Indian Rupee (INR)', flag: '🇮🇳' },
  { value: 'AUD', label: '🇦🇺 Australian Dollar (AUD)', flag: '🇦🇺' },
  { value: 'CAD', label: '🇨🇦 Canadian Dollar (CAD)', flag: '🇨🇦' },
  { value: 'JPY', label: '🇯🇵 Japanese Yen (JPY)', flag: '🇯🇵' },
  { value: 'BRL', label: '🇧🇷 Brazilian Real (BRL)', flag: '🇧🇷' },
  { value: 'ZAR', label: '🇿🇦 South African Rand (ZAR)', flag: '🇿🇦' }
];

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

export default function OnBoardPage({ params }: OnBoardPageProps) {
  const { locale } = use(params);
  const { data: session, status } = useSession();
  const { showError, showSuccess } = useToast();
  const { profile: dynamicProfile } = useFreelancerProfile();
  
  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [formData, setFormData] = useState<OnBoardData>({
    companyName: '',
    currency: '',
    dateOfBirth: '',
    headline: '',
    aboutYourself: ''
  });
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});

  // Fetch profile and onboard data
  useEffect(() => {
    if (status === 'authenticated') {
      fetchProfile();
      fetchOnBoardData();
    }
  }, [status]);

  const fetchProfile = async () => {
    try {
      const response = await fetch('/api/freelancer/profile', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

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

      const data = await response.json();
      if (data.success) {
        setProfile(data.data);
      } else {
        throw new Error(data.error || 'Failed to fetch profile');
      }
    } catch (error: any) {
      console.error('Error fetching profile:', error);
      // Don't show error for profile fetch failure
    }
  };

  const fetchOnBoardData = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/freelancer/onboard', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        if (response.status === 404) {
          // No onboard data exists yet, keep empty form
          return;
        }
        throw new Error('Failed to fetch onboard data');
      }

      const data = await response.json();
      if (data.success && data.data) {
        setFormData({
          companyName: data.data.companyName || '',
          currency: data.data.currency || '',
          dateOfBirth: data.data.dateOfBirth || '',
          headline: data.data.headline || '',
          aboutYourself: data.data.aboutYourself || ''
        });
      }
    } catch (error: any) {
      console.error('Error fetching onboard data:', error);
      // Don't show error for onboard data fetch failure
    } finally {
      setIsLoading(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    
    // Clear error when user starts typing
    if (errors[name]) {
      setErrors(prev => ({
        ...prev,
        [name]: ''
      }));
    }
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    
    if (!formData.dateOfBirth.trim()) {
      newErrors.dateOfBirth = 'Date of Birth/Foundation Day is required';
    }
    
    if (!formData.aboutYourself.trim()) {
      newErrors.aboutYourself = 'About Yourself is required';
    }
    
    if (formData.aboutYourself.trim().length < 50) {
      newErrors.aboutYourself = 'About Yourself should be at least 50 characters';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }
    
    setIsSubmitting(true);

    const submitData = {
      companyName: formData.companyName.trim(),
      currency: formData.currency,
      dateOfBirth: formData.dateOfBirth,
      headline: formData.headline.trim(),
      aboutYourself: formData.aboutYourself.trim()
    };

    // Debug logging
    console.log('Submitting onboard data:', submitData);
    
    try {
      const response = await fetch('/api/freelancer/onboard', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(submitData),
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to save onboard data');
      }
      
      const data = await response.json();
      console.log('Onboard response:', data);
      
      if (data.success) {
        showSuccess('Onboard information saved successfully!');
        // Update form data with saved values to confirm persistence
        if (data.data) {
          setFormData({
            companyName: data.data.companyName || '',
            currency: data.data.currency || '',
            dateOfBirth: data.data.dateOfBirth || '',
            headline: data.data.headline || '',
            aboutYourself: data.data.aboutYourself || ''
          });
        }
        // Refresh profile to get updated completion percentage
        fetchProfile();
      } else {
        throw new Error(data.error || 'Failed to save onboard data');
      }
      
    } catch (error: any) {
      console.error('Error submitting onboard data:', error);
      showError(error.message || 'Failed to save onboard information');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (status === 'loading' || isLoading) {
    return (
      <div className="profile-wrapper">
        <div className="container-fluid">
          <div className="row">
            <div className="col-12">
              <div className="loading-container">
                <div className="spinner-border" role="status">
                  <span className="visually-hidden">Loading...</span>
                </div>
                <p>Loading onboard data...</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  if (status === 'unauthenticated') {
    return (
      <div className="profile-wrapper">
        <div className="container-fluid">
          <div className="row">
            <div className="col-12">
              <div className="error-container">
                <h2>Access Denied</h2>
                <p>Please log in to view your onboard page.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <FreelancerLayout 
      locale={locale}
      userProfile={(dynamicProfile || profile) ? {
        name: dynamicProfile ? `${dynamicProfile.firstName} ${dynamicProfile.lastName}` : `${profile?.firstName} ${profile?.lastName}`,
        profileImage: (dynamicProfile?.profileImage || profile?.profileImage) || "/assets/image/profile03.png",
        rating: dynamicProfile?.rating || 4.5,
        reviewCount: dynamicProfile?.reviewCount || 0
      } : undefined}
      unreadMessagesCount={0}
    >
      <div className="content-box">
        {/* Welcome Header */}
        <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 - (profile?.profileCompletion || 0) / 100 * 2 * Math.PI * 24}`
                    }}
                  />
                </svg>
                <div className="percentage">{profile?.profileCompletion || 0}%</div>
              </div>
            </div>
            <div className="welcome-content">
              <h6>Hi {profile?.firstName || 'User'}! Please complete your profile.</h6>
              <p>Let's spend a few minutes optimizing your profile to maximize opportunities.</p>
            </div>
          </div>
          <div className="welcome-img">
            <img src="/assets/image/profile-bg.png" alt="profile-bg" />
          </div>
        </div>

        {/* OnBoard Form */}
        <div className="content-box-inner">
          <div className="tab-title">
            <h5>On Board</h5>
          </div>
          
          <div className="form-wrap">
            <form onSubmit={handleSubmit}>
              {/* Company Name */}
              <div className="form-group">
                <div className="mb-20">
                  <label htmlFor="companyName" className="form-label">
                    Company Name <span className="optional-text">(Leave Blank to Use Your First & Last name as your Skilled username)</span>
                  </label>
                  <div className="input-icon">
                    <input 
                      type="text" 
                      className="form-control" 
                      name="companyName" 
                      id="companyName" 
                      placeholder="Enter Company Name"
                      value={formData.companyName}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                </div>
              </div>

              {/* Currency and Date of Birth */}
              <div className="form-group">
                <div className="mb-20">
                  <label htmlFor="currency" className="form-label">Select Currency</label>
                  <div className="input-icon">
                    <div className='custom-sub-select'>
                      <select 
                        id="currency" 
                        name="currency"
                        className="form-control"
                        value={formData.currency}
                        onChange={handleInputChange}
                        disabled={isSubmitting}
                      >
                        <option value="">-- Select Currency --</option>
                        {CURRENCIES.map((currency) => (
                          <option key={currency.value} value={currency.value}>
                            {currency.label}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>
                </div>
                
                <div className="mb-20">
                  <label htmlFor="dateOfBirth" className="form-label">Date of Birth/Foundation Day <span className='text-danger'>*</span></label>
                  <div className="input-icon">
                    <input 
                      type="date" 
                      className={`form-control ${errors.dateOfBirth ? 'error' : ''}`}
                      name="dateOfBirth"
                      id="dateOfBirth"
                      value={formData.dateOfBirth}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                  {errors.dateOfBirth && <div className="error-message">{errors.dateOfBirth}</div>}
                </div>
              </div>

              {/* Headline */}
              <div className="form-group no-icon-box">
                <div className="mb-20">
                  <label htmlFor="headline" className="form-label">Headline</label>
                  <div className="input-icon">
                    <input 
                      type="text" 
                      className="form-control" 
                      name="headline"
                      id="headline"
                      placeholder="Enter Headline"
                      value={formData.headline}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                </div>
              </div>

              {/* About Yourself */}
              <div className="form-group no-icon-box">
                <div className="mb-20">
                  <label htmlFor="aboutYourself" className="form-label">About Yourself <span className='text-danger'>*</span></label>
                  <div className="input-icon">
                    <textarea 
                      rows={4} 
                      className={`form-control ${errors.aboutYourself ? 'error' : ''}`}
                      name="aboutYourself"
                      id="aboutYourself"
                      placeholder="Tell us about yourself, your skills, experience, and what makes you unique..."
                      value={formData.aboutYourself}
                      onChange={handleInputChange}
                      disabled={isSubmitting}
                    />
                  </div>
                  <small className="character-count">
                    {formData.aboutYourself.length}/500 characters (minimum 50 required)
                  </small>
                  {errors.aboutYourself && <div className="error-message">{errors.aboutYourself}</div>}
                </div>
              </div>

              <button 
                type="submit" 
                className="w-100 custom-btn secondary-btn"
                disabled={isSubmitting}
              >
                {isSubmitting ? 'Saving...' : 'Update & Save'}
              </button>
            </form>
          </div>
        </div>
      </div>
    </FreelancerLayout>
  );
}