'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { useLocale } from 'next-intl';
import StepIndicator from '@/components/apply/StepIndicator';
import PersonalInfoStep from '@/components/apply/PersonalInfoStep';
import type { FormData } from '@/components/apply/PersonalInfoStep';
import CVUploadStep from '@/components/apply/CVUploadStep';
import TargetCountryStep from '@/components/apply/TargetCountryStep';
import ReviewStep from '@/components/apply/ReviewStep';

const INITIAL_FORM_DATA: FormData = {
  firstName: '',
  lastName: '',
  email: '',
  phone: '',
  countryOfOrigin: '',
  dateOfBirth: '',
  educationLevel: '',
  yearsExperience: '',
  skills: '',
};

export default function ApplyPage() {
  const t = useTranslations('Apply');
  const locale = useLocale();

  const [currentStep, setCurrentStep] = useState(0);
  const [formData, setFormData] = useState<FormData>(INITIAL_FORM_DATA);
  const [cvFile, setCvFile] = useState<File | null>(null);
  const [cvUrl, setCvUrl] = useState('');
  const [targetCountry, setTargetCountry] = useState('');
  const [jobSector, setJobSector] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const steps = [t('step1'), t('step2'), t('step3'), t('step4')];

  const handleFormDataChange = (partial: Partial<FormData>) => {
    setFormData((prev) => ({ ...prev, ...partial }));
  };

  const handleTargetChange = (data: { targetCountry?: string; jobSector?: string }) => {
    if (data.targetCountry !== undefined) setTargetCountry(data.targetCountry);
    if (data.jobSector !== undefined) setJobSector(data.jobSector);
  };

  const canProceed = (): boolean => {
    switch (currentStep) {
      case 0:
        return !!(
          formData.firstName.trim() &&
          formData.lastName.trim() &&
          formData.email.trim() &&
          formData.phone.trim() &&
          formData.countryOfOrigin &&
          formData.dateOfBirth
        );
      case 1:
        return !!cvUrl;
      case 2:
        return !!(targetCountry && jobSector);
      default:
        return true;
    }
  };

  const handleNext = () => {
    if (currentStep < steps.length - 1 && canProceed()) {
      setCurrentStep((prev) => prev + 1);
    }
  };

  const handleBack = () => {
    if (currentStep > 0) {
      setCurrentStep((prev) => prev - 1);
    }
  };

  const handleSubmit = async () => {
    setIsSubmitting(true);

    try {
      const response = await fetch('/api/create-checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...formData,
          cvUrl,
          targetCountry,
          jobSector,
          locale,
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to create checkout session');
      }

      const { url } = await response.json();
      window.location.href = url;
    } catch (error) {
      console.error('Checkout error:', error);
      setIsSubmitting(false);
    }
  };

  const renderStep = () => {
    switch (currentStep) {
      case 0:
        return <PersonalInfoStep data={formData} onChange={handleFormDataChange} />;
      case 1:
        return (
          <CVUploadStep
            file={cvFile}
            onFileChange={setCvFile}
            uploadedUrl={cvUrl}
            onUploadedUrl={setCvUrl}
          />
        );
      case 2:
        return (
          <TargetCountryStep
            targetCountry={targetCountry}
            jobSector={jobSector}
            onChange={handleTargetChange}
          />
        );
      case 3:
        return (
          <ReviewStep
            data={formData}
            cvFileName={cvFile?.name || ''}
            targetCountry={targetCountry}
            jobSector={jobSector}
            isSubmitting={isSubmitting}
            onSubmit={handleSubmit}
          />
        );
      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
        {/* Page header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl sm:text-4xl font-bold text-gray-900">{t('title')}</h1>
          <p className="mt-2 text-base text-gray-600">{t('pageSubtitle')}</p>
        </div>

        {/* Step indicator */}
        <StepIndicator currentStep={currentStep} steps={steps} />

        {/* Step content */}
        <div className="mt-8 bg-white rounded-2xl shadow-sm border border-gray-200 p-6 sm:p-8">
          {renderStep()}
        </div>

        {/* Navigation buttons */}
        {currentStep < 3 && (
          <div className="mt-6 flex items-center justify-between">
            <button
              onClick={handleBack}
              disabled={currentStep === 0}
              className={`
                flex items-center gap-2 px-6 py-3 rounded-lg font-medium transition-all duration-200
                ${currentStep === 0
                  ? 'text-gray-300 cursor-not-allowed'
                  : 'text-gray-700 hover:bg-gray-100 border border-gray-300'
                }
              `}
            >
              <svg className="w-5 h-5 rtl:rotate-180" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
              </svg>
              {t('back')}
            </button>

            <button
              onClick={handleNext}
              disabled={!canProceed()}
              className={`
                flex items-center gap-2 px-8 py-3 rounded-lg font-medium transition-all duration-200
                ${canProceed()
                  ? 'bg-blue-600 text-white hover:bg-blue-700 shadow-md shadow-blue-600/20'
                  : 'bg-gray-200 text-gray-400 cursor-not-allowed'
                }
              `}
            >
              {t('next')}
              <svg className="w-5 h-5 rtl:rotate-180" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 4.5L21 12m0 0l-7.5 7.5M21 12H3" />
              </svg>
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
