'use client';

import { useState, useRef, FormEvent, ChangeEvent } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import {
  User,
  Flag,
  Camera,
  Clock,
  Check,
  ChevronRight,
  ChevronLeft,
  AlertCircle,
  Upload,
  Loader2,
  Sparkles,
  Palette,
} from 'lucide-react';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import Heading from '@/components/ui/Heading';
import CountrySelect from '@/components/ui/CountrySelect';
import { useServices } from '@/lib/services/ServiceProvider';

// ============================================================================
// TYPES
// ============================================================================

type OnboardingStep = 1 | 2;

interface PersonalInfo {
  firstName: string;
  lastName: string;
  displayName: string;
  country: string;
  timezone: string;
}

interface AvatarInfo {
  facePhoto: string | null;
  suitColor: RacingSuitColor;
  generatedAvatars: string[];
  selectedAvatarIndex: number | null;
  isGenerating: boolean;
  isValidating: boolean;
}

interface FormErrors {
  firstName?: string;
  lastName?: string;
  displayName?: string;
  country?: string;
  facePhoto?: string;
  avatar?: string;
  submit?: string;
}

type RacingSuitColor = 
  | 'red' 
  | 'blue' 
  | 'green' 
  | 'yellow' 
  | 'orange' 
  | 'purple' 
  | 'black' 
  | 'white' 
  | 'pink'
  | 'cyan';

// ============================================================================
// CONSTANTS
// ============================================================================

const TIMEZONES = [
  { value: 'America/New_York', label: 'Eastern Time (ET)' },
  { value: 'America/Chicago', label: 'Central Time (CT)' },
  { value: 'America/Denver', label: 'Mountain Time (MT)' },
  { value: 'America/Los_Angeles', label: 'Pacific Time (PT)' },
  { value: 'Europe/London', label: 'Greenwich Mean Time (GMT)' },
  { value: 'Europe/Berlin', label: 'Central European Time (CET)' },
  { value: 'Europe/Paris', label: 'Central European Time (CET)' },
  { value: 'Australia/Sydney', label: 'Australian Eastern Time (AET)' },
  { value: 'Asia/Tokyo', label: 'Japan Standard Time (JST)' },
  { value: 'America/Sao_Paulo', label: 'Brasília Time (BRT)' },
];

const SUIT_COLORS: { value: RacingSuitColor; label: string; hex: string }[] = [
  { value: 'red', label: 'Racing Red', hex: '#EF4444' },
  { value: 'blue', label: 'Motorsport Blue', hex: '#3B82F6' },
  { value: 'green', label: 'Racing Green', hex: '#22C55E' },
  { value: 'yellow', label: 'Championship Yellow', hex: '#EAB308' },
  { value: 'orange', label: 'Papaya Orange', hex: '#F97316' },
  { value: 'purple', label: 'Royal Purple', hex: '#A855F7' },
  { value: 'black', label: 'Stealth Black', hex: '#1F2937' },
  { value: 'white', label: 'Clean White', hex: '#F9FAFB' },
  { value: 'pink', label: 'Hot Pink', hex: '#EC4899' },
  { value: 'cyan', label: 'Electric Cyan', hex: '#06B6D4' },
];

// ============================================================================
// HELPER COMPONENTS
// ============================================================================

function StepIndicator({ currentStep }: { currentStep: number }) {
  const steps = [
    { id: 1, label: 'Personal', icon: User },
    { id: 2, label: 'Avatar', icon: Camera },
  ];

  return (
    <div className="flex items-center justify-center gap-2 mb-8">
      {steps.map((step, index) => {
        const Icon = step.icon;
        const isCompleted = step.id < currentStep;
        const isCurrent = step.id === currentStep;

        return (
          <div key={step.id} className="flex items-center">
            <div className="flex flex-col items-center">
              <div
                className={`flex h-12 w-12 items-center justify-center rounded-full transition-all duration-300 ${
                  isCurrent
                    ? 'bg-primary-blue text-white shadow-lg shadow-primary-blue/30'
                    : isCompleted
                    ? 'bg-performance-green text-white'
                    : 'bg-iron-gray border border-charcoal-outline text-gray-500'
                }`}
              >
                {isCompleted ? (
                  <Check className="w-5 h-5" />
                ) : (
                  <Icon className="w-5 h-5" />
                )}
              </div>
              <span
                className={`mt-2 text-xs font-medium ${
                  isCurrent ? 'text-white' : isCompleted ? 'text-performance-green' : 'text-gray-500'
                }`}
              >
                {step.label}
              </span>
            </div>
            {index < steps.length - 1 && (
              <div
                className={`w-16 h-0.5 mx-4 mt-[-20px] ${
                  isCompleted ? 'bg-performance-green' : 'bg-charcoal-outline'
                }`}
              />
            )}
          </div>
        );
      })}
    </div>
  );
}

// ============================================================================
// MAIN COMPONENT
// ============================================================================

export default function OnboardingWizard() {
  const router = useRouter();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { onboardingService, sessionService } = useServices();
  const [step, setStep] = useState<OnboardingStep>(1);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<FormErrors>({});

  // Form state
  const [personalInfo, setPersonalInfo] = useState<PersonalInfo>({
    firstName: '',
    lastName: '',
    displayName: '',
    country: '',
    timezone: '',
  });

  const [avatarInfo, setAvatarInfo] = useState<AvatarInfo>({
    facePhoto: null,
    suitColor: 'blue',
    generatedAvatars: [],
    selectedAvatarIndex: null,
    isGenerating: false,
    isValidating: false,
  });

  // Validation
  const validateStep = (currentStep: OnboardingStep): boolean => {
    const newErrors: FormErrors = {};

    if (currentStep === 1) {
      if (!personalInfo.firstName.trim()) {
        newErrors.firstName = 'First name is required';
      }
      if (!personalInfo.lastName.trim()) {
        newErrors.lastName = 'Last name is required';
      }
      if (!personalInfo.displayName.trim()) {
        newErrors.displayName = 'Display name is required';
      } else if (personalInfo.displayName.length < 3) {
        newErrors.displayName = 'Display name must be at least 3 characters';
      }
      if (!personalInfo.country) {
        newErrors.country = 'Please select your country';
      }
    }

    if (currentStep === 2) {
      if (!avatarInfo.facePhoto) {
        newErrors.facePhoto = 'Please upload a photo of your face';
      }
      if (avatarInfo.generatedAvatars.length > 0 && avatarInfo.selectedAvatarIndex === null) {
        newErrors.avatar = 'Please select one of the generated avatars';
      }
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleNext = () => {
    const isValid = validateStep(step);
    if (isValid && step < 2) {
      setStep((step + 1) as OnboardingStep);
    }
  };

  const handleBack = () => {
    if (step > 1) {
      setStep((step - 1) as OnboardingStep);
    }
  };

  const handleFileSelect = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    if (!file.type.startsWith('image/')) {
      setErrors({ ...errors, facePhoto: 'Please upload an image file' });
      return;
    }

    // Validate file size (max 5MB)
    if (file.size > 5 * 1024 * 1024) {
      setErrors({ ...errors, facePhoto: 'Image must be less than 5MB' });
      return;
    }

    // Convert to base64
    const reader = new FileReader();
    reader.onload = async (event) => {
      const base64 = event.target?.result as string;
      setAvatarInfo({
        ...avatarInfo,
        facePhoto: base64,
        generatedAvatars: [],
        selectedAvatarIndex: null,
      });
      setErrors((prev) => {
        const { facePhoto, ...rest } = prev;
        return rest;
      });

      // Validate face
      await validateFacePhoto(base64);
    };
    reader.readAsDataURL(file);
  };

  const validateFacePhoto = async (photoData: string) => {
    setAvatarInfo(prev => ({ ...prev, isValidating: true }));
    setErrors(prev => {
      const { facePhoto, ...rest } = prev;
      return rest;
    });

    try {
      const result = await onboardingService.validateFacePhoto(photoData);

      if (!result.isValid) {
        setErrors(prev => ({
          ...prev,
          facePhoto: result.errorMessage || 'Face validation failed'
        }));
        setAvatarInfo(prev => ({ ...prev, facePhoto: null, isValidating: false }));
      } else {
        setAvatarInfo(prev => ({ ...prev, isValidating: false }));
      }
    } catch (error) {
      // For now, just accept the photo if validation fails
      setAvatarInfo(prev => ({ ...prev, isValidating: false }));
    }
  };

  const generateAvatars = async () => {
    if (!avatarInfo.facePhoto) {
      setErrors({ ...errors, facePhoto: 'Please upload a photo first' });
      return;
    }

    setAvatarInfo(prev => ({ ...prev, isGenerating: true, generatedAvatars: [], selectedAvatarIndex: null }));
    setErrors(prev => {
      const { avatar, ...rest } = prev;
      return rest;
    });

    try {
      // Get current user ID from session
      const session = await sessionService.getSession();
      if (!session?.user?.userId) {
        throw new Error('User not authenticated');
      }

      const result = await onboardingService.generateAvatars(
        session.user.userId,
        avatarInfo.facePhoto,
        avatarInfo.suitColor
      );

      if (result.success && result.avatarUrls) {
        setAvatarInfo(prev => ({
          ...prev,
          generatedAvatars: result.avatarUrls,
          isGenerating: false,
        }));
      } else {
        setErrors(prev => ({ ...prev, avatar: result.errorMessage || 'Failed to generate avatars' }));
        setAvatarInfo(prev => ({ ...prev, isGenerating: false }));
      }
    } catch (error) {
      setErrors(prev => ({ ...prev, avatar: 'Failed to generate avatars. Please try again.' }));
      setAvatarInfo(prev => ({ ...prev, isGenerating: false }));
    }
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (loading) return;

    // Validate step 2 - must have selected an avatar
    if (!validateStep(2)) {
      return;
    }

    if (avatarInfo.selectedAvatarIndex === null) {
      setErrors({ ...errors, avatar: 'Please select an avatar' });
      return;
    }

    setLoading(true);
    setErrors({});

    try {
      // Note: The current API doesn't support avatarUrl in onboarding
      // This would need to be handled separately or the API would need to be updated
      const result = await onboardingService.completeOnboarding({
        firstName: personalInfo.firstName.trim(),
        lastName: personalInfo.lastName.trim(),
        displayName: personalInfo.displayName.trim(),
        country: personalInfo.country,
        timezone: personalInfo.timezone || undefined,
      });

      if (result.success) {
        // TODO: Handle avatar assignment separately if needed
        router.push('/dashboard');
        router.refresh();
      } else {
        throw new Error(result.errorMessage || 'Failed to create profile');
      }
    } catch (error) {
      setErrors({
        submit: error instanceof Error ? error.message : 'Failed to create profile',
      });
      setLoading(false);
    }
  };

  const getCountryFlag = (countryCode: string): string => {
    const code = countryCode.toUpperCase();
    if (code.length === 2) {
      const codePoints = [...code].map(char => 127397 + char.charCodeAt(0));
      return String.fromCodePoint(...codePoints);
    }
    return '🏁';
  };

  return (
    <div className="max-w-3xl mx-auto px-4 py-10">
      {/* Header */}
      <div className="text-center mb-8">
        <div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-primary-blue/20 to-purple-600/10 border border-primary-blue/30 mx-auto mb-4">
          <Flag className="w-8 h-8 text-primary-blue" />
        </div>
        <Heading level={1} className="mb-2">Welcome to GridPilot</Heading>
        <p className="text-gray-400">
          Let's set up your racing profile
        </p>
      </div>

      {/* Progress Indicator */}
      <StepIndicator currentStep={step} />

      {/* Form Card */}
      <Card className="relative overflow-hidden">
        {/* Background accent */}
        <div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-bl from-primary-blue/10 to-transparent rounded-bl-full" />

        <form onSubmit={handleSubmit} className="relative">
          {/* Step 1: Personal Information */}
          {step === 1 && (
            <div className="space-y-6">
              <div>
                <Heading level={2} className="text-xl mb-1 flex items-center gap-2">
                  <User className="w-5 h-5 text-primary-blue" />
                  Personal Information
                </Heading>
                <p className="text-sm text-gray-400">
                  Tell us a bit about yourself
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label htmlFor="firstName" className="block text-sm font-medium text-gray-300 mb-2">
                    First Name *
                  </label>
                  <Input
                    id="firstName"
                    type="text"
                    value={personalInfo.firstName}
                    onChange={(e) =>
                      setPersonalInfo({ ...personalInfo, firstName: e.target.value })
                    }
                    error={!!errors.firstName}
                    errorMessage={errors.firstName}
                    placeholder="John"
                    disabled={loading}
                  />
                </div>

                <div>
                  <label htmlFor="lastName" className="block text-sm font-medium text-gray-300 mb-2">
                    Last Name *
                  </label>
                  <Input
                    id="lastName"
                    type="text"
                    value={personalInfo.lastName}
                    onChange={(e) =>
                      setPersonalInfo({ ...personalInfo, lastName: e.target.value })
                    }
                    error={!!errors.lastName}
                    errorMessage={errors.lastName}
                    placeholder="Racer"
                    disabled={loading}
                  />
                </div>
              </div>

              <div>
                <label htmlFor="displayName" className="block text-sm font-medium text-gray-300 mb-2">
                  Display Name * <span className="text-gray-500 font-normal">(shown publicly)</span>
                </label>
                <Input
                  id="displayName"
                  type="text"
                  value={personalInfo.displayName}
                  onChange={(e) =>
                    setPersonalInfo({ ...personalInfo, displayName: e.target.value })
                  }
                  error={!!errors.displayName}
                  errorMessage={errors.displayName}
                  placeholder="SpeedyRacer42"
                  disabled={loading}
                />
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label htmlFor="country" className="block text-sm font-medium text-gray-300 mb-2">
                    Country *
                  </label>
                  <CountrySelect
                    value={personalInfo.country}
                    onChange={(value) =>
                      setPersonalInfo({ ...personalInfo, country: value })
                    }
                    error={!!errors.country}
                    errorMessage={errors.country ?? ''}
                    disabled={loading}
                  />
                </div>

                <div>
                  <label htmlFor="timezone" className="block text-sm font-medium text-gray-300 mb-2">
                    Timezone
                  </label>
                  <div className="relative">
                    <Clock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 z-10" />
                    <select
                      id="timezone"
                      value={personalInfo.timezone}
                      onChange={(e) =>
                        setPersonalInfo({ ...personalInfo, timezone: e.target.value })
                      }
                      className="block w-full rounded-md border-0 px-4 py-3 pl-10 bg-iron-gray text-white shadow-sm ring-1 ring-inset ring-charcoal-outline placeholder:text-gray-500 focus:ring-2 focus:ring-inset focus:ring-primary-blue transition-all duration-150 sm:text-sm appearance-none cursor-pointer"
                      disabled={loading}
                    >
                      <option value="">Select timezone</option>
                      {TIMEZONES.map((tz) => (
                        <option key={tz.value} value={tz.value}>
                          {tz.label}
                        </option>
                      ))}
                    </select>
                    <ChevronRight className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-500 rotate-90" />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 2: Avatar Generation */}
          {step === 2 && (
            <div className="space-y-6">
              <div>
                <Heading level={2} className="text-xl mb-1 flex items-center gap-2">
                  <Camera className="w-5 h-5 text-primary-blue" />
                  Create Your Racing Avatar
                </Heading>
                <p className="text-sm text-gray-400">
                  Upload a photo and we'll generate a unique racing avatar for you
                </p>
              </div>

              {/* Photo Upload */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-3">
                  Upload Your Photo *
                </label>
                <div className="flex gap-6">
                  {/* Upload Area */}
                  <div 
                    onClick={() => fileInputRef.current?.click()}
                    className={`relative flex-1 flex flex-col items-center justify-center p-6 rounded-xl border-2 border-dashed cursor-pointer transition-all ${
                      avatarInfo.facePhoto
                        ? 'border-performance-green bg-performance-green/5'
                        : errors.facePhoto
                        ? 'border-red-500 bg-red-500/5'
                        : 'border-charcoal-outline hover:border-primary-blue hover:bg-primary-blue/5'
                    }`}
                  >
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept="image/*"
                      onChange={handleFileSelect}
                      className="hidden"
                    />
                    
                    {avatarInfo.isValidating ? (
                      <>
                        <Loader2 className="w-10 h-10 text-primary-blue animate-spin mb-3" />
                        <p className="text-sm text-gray-400">Validating photo...</p>
                      </>
                    ) : avatarInfo.facePhoto ? (
                      <>
                        <div className="w-24 h-24 rounded-xl overflow-hidden mb-3 ring-2 ring-performance-green">
                          <Image
                            src={avatarInfo.facePhoto}
                            alt="Your photo"
                            width={96}
                            height={96}
                            className="w-full h-full object-cover"
                          />
                        </div>
                        <p className="text-sm text-performance-green flex items-center gap-1">
                          <Check className="w-4 h-4" />
                          Photo uploaded
                        </p>
                        <p className="text-xs text-gray-500 mt-1">Click to change</p>
                      </>
                    ) : (
                      <>
                        <Upload className="w-10 h-10 text-gray-500 mb-3" />
                        <p className="text-sm text-gray-300 font-medium mb-1">
                          Drop your photo here or click to upload
                        </p>
                        <p className="text-xs text-gray-500">
                          JPEG or PNG, max 5MB
                        </p>
                      </>
                    )}
                  </div>

                  {/* Preview area */}
                  <div className="w-32 flex flex-col items-center justify-center">
                    <div className="w-24 h-24 rounded-xl bg-iron-gray border border-charcoal-outline flex items-center justify-center overflow-hidden">
                      {(() => {
                        const selectedAvatarUrl =
                          avatarInfo.selectedAvatarIndex !== null
                            ? avatarInfo.generatedAvatars[avatarInfo.selectedAvatarIndex]
                            : undefined;
                        if (!selectedAvatarUrl) {
                          return <User className="w-8 h-8 text-gray-600" />;
                        }
                        return (
                          <Image
                            src={selectedAvatarUrl}
                            alt="Selected avatar"
                            width={96}
                            height={96}
                            className="w-full h-full object-cover"
                          />
                        );
                      })()}
                    </div>
                    <p className="text-xs text-gray-500 mt-2 text-center">Your avatar</p>
                  </div>
                </div>
                {errors.facePhoto && (
                  <p className="mt-2 text-sm text-red-400">{errors.facePhoto}</p>
                )}
              </div>

              {/* Suit Color Selection */}
              <div>
                <label className="block text-sm font-medium text-gray-300 mb-3 flex items-center gap-2">
                  <Palette className="w-4 h-4" />
                  Racing Suit Color
                </label>
                <div className="flex flex-wrap gap-2">
                  {SUIT_COLORS.map((color) => (
                    <button
                      key={color.value}
                      type="button"
                      onClick={() => setAvatarInfo({ ...avatarInfo, suitColor: color.value })}
                      className={`relative w-10 h-10 rounded-lg transition-all ${
                        avatarInfo.suitColor === color.value
                          ? 'ring-2 ring-primary-blue ring-offset-2 ring-offset-iron-gray scale-110'
                          : 'hover:scale-105'
                      }`}
                      style={{ backgroundColor: color.hex }}
                      title={color.label}
                    >
                      {avatarInfo.suitColor === color.value && (
                        <Check className={`absolute inset-0 m-auto w-5 h-5 ${
                          ['white', 'yellow', 'cyan'].includes(color.value) ? 'text-gray-800' : 'text-white'
                        }`} />
                      )}
                    </button>
                  ))}
                </div>
                <p className="mt-2 text-xs text-gray-500">
                  Selected: {SUIT_COLORS.find(c => c.value === avatarInfo.suitColor)?.label}
                </p>
              </div>

              {/* Generate Button */}
              {avatarInfo.facePhoto && !errors.facePhoto && (
                <div>
                  <Button
                    type="button"
                    variant="primary"
                    onClick={generateAvatars}
                    disabled={avatarInfo.isGenerating || avatarInfo.isValidating}
                    className="w-full flex items-center justify-center gap-2"
                  >
                    {avatarInfo.isGenerating ? (
                      <>
                        <Loader2 className="w-5 h-5 animate-spin" />
                        Generating your avatars...
                      </>
                    ) : (
                      <>
                        <Sparkles className="w-5 h-5" />
                        {avatarInfo.generatedAvatars.length > 0 ? 'Regenerate Avatars' : 'Generate Racing Avatars'}
                      </>
                    )}
                  </Button>
                </div>
              )}

              {/* Generated Avatars */}
              {avatarInfo.generatedAvatars.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-gray-300 mb-3">
                    Choose Your Avatar *
                  </label>
                  <div className="grid grid-cols-3 gap-4">
                    {avatarInfo.generatedAvatars.map((url, index) => (
                      <button
                        key={index}
                        type="button"
                        onClick={() => setAvatarInfo({ ...avatarInfo, selectedAvatarIndex: index })}
                        className={`relative aspect-square rounded-xl overflow-hidden border-2 transition-all ${
                          avatarInfo.selectedAvatarIndex === index
                            ? 'border-primary-blue ring-2 ring-primary-blue/30 scale-105'
                            : 'border-charcoal-outline hover:border-gray-500'
                        }`}
                      >
                        <Image
                          src={url}
                          alt={`Avatar option ${index + 1}`}
                          fill
                          className="object-cover"
                        />
                        {avatarInfo.selectedAvatarIndex === index && (
                          <div className="absolute top-2 right-2 w-6 h-6 rounded-full bg-primary-blue flex items-center justify-center">
                            <Check className="w-4 h-4 text-white" />
                          </div>
                        )}
                      </button>
                    ))}
                  </div>
                  {errors.avatar && (
                    <p className="mt-2 text-sm text-red-400">{errors.avatar}</p>
                  )}
                </div>
              )}
            </div>
          )}

          {/* Error Message */}
          {errors.submit && (
            <div className="mt-6 flex items-start gap-3 p-4 rounded-xl bg-red-500/10 border border-red-500/30">
              <AlertCircle className="w-5 h-5 text-red-400 flex-shrink-0 mt-0.5" />
              <p className="text-sm text-red-400">{errors.submit}</p>
            </div>
          )}

          {/* Navigation Buttons */}
          <div className="mt-8 flex items-center justify-between">
            <Button
              type="button"
              variant="secondary"
              onClick={handleBack}
              disabled={step === 1 || loading}
              className="flex items-center gap-2"
            >
              <ChevronLeft className="w-4 h-4" />
              Back
            </Button>

            {step < 2 ? (
              <Button
                type="button"
                variant="primary"
                onClick={handleNext}
                disabled={loading}
                className="flex items-center gap-2"
              >
                Continue
                <ChevronRight className="w-4 h-4" />
              </Button>
            ) : (
              <Button
                type="submit"
                variant="primary"
                disabled={loading || avatarInfo.selectedAvatarIndex === null}
                className="flex items-center gap-2"
              >
                {loading ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Creating Profile...
                  </>
                ) : (
                  <>
                    <Check className="w-4 h-4" />
                    Complete Setup
                  </>
                )}
              </Button>
            )}
          </div>
        </form>
      </Card>

      {/* Help Text */}
      <p className="text-center text-xs text-gray-500 mt-6">
        Your avatar will be AI-generated based on your photo and chosen suit color
      </p>
    </div>
  );
}