import { useRef, ChangeEvent } from 'react';
import { Camera, Upload, Loader2, Sparkles, Palette, Check, User } from 'lucide-react';
import Button from '@/components/ui/Button';
import Heading from '@/components/ui/Heading';

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

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

interface FormErrors {
  [key: string]: string | undefined;
}

interface AvatarStepProps {
  avatarInfo: AvatarInfo;
  setAvatarInfo: (info: AvatarInfo) => void;
  errors: FormErrors;
  setErrors: (errors: FormErrors) => void;
  onGenerateAvatars: () => void;
}

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' },
];

export function AvatarStep({ avatarInfo, setAvatarInfo, errors, setErrors, onGenerateAvatars }: AvatarStepProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);

  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,
      });
      const newErrors = { ...errors };
      delete newErrors.facePhoto;
      setErrors(newErrors);
    };
    reader.readAsDataURL(file);
  };

  return (
    <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 will 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">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={avatarInfo.facePhoto}
                    alt="Your photo"
                    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 (
                  <>
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src={selectedAvatarUrl} alt="Selected avatar" 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={onGenerateAvatars}
            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'
                }`}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={url} alt={`Avatar option ${index + 1}`} className="w-full h-full 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>
  );
}