import { useRef, ChangeEvent } from 'react';
import { Camera, Upload, Loader2, Sparkles, Palette, Check, User } from 'lucide-react';
import { Button } from '@/ui/Button';
import { Heading } from '@/ui/Heading';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Text } from '@/ui/Text';
import { Icon } from '@/ui/Icon';
import { Grid } from '@/ui/Grid';
import { Surface } from '@/ui/Surface';
import { Image } from '@/ui/Image';

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 (
    <Stack gap={6}>
      <Box>
        <Heading level={2} icon={<Icon icon={Camera} size={5} color="text-primary-blue" />}>
          Create Your Racing Avatar
        </Heading>
        <Text size="sm" color="text-gray-400" block mt={1}>
          Upload a photo and we will generate a unique racing avatar for you
        </Text>
      </Box>

      {/* Photo Upload */}
      <Box>
        <Text as="label" size="sm" weight="medium" color="text-gray-300" block mb={3}>
          Upload Your Photo *
        </Text>
        <Stack direction="row" gap={6}>
          {/* Upload Area */}
          <Box
            onClick={() => fileInputRef.current?.click()}
            flex={1}
            display="flex"
            flexDirection="column"
            align="center"
            justify="center"
            padding={6}
            rounded="xl"
            border
            borderColor={avatarInfo.facePhoto ? 'performance-green' : errors.facePhoto ? 'racing-red' : 'charcoal-outline'}
            backgroundColor={avatarInfo.facePhoto ? 'performance-green' : errors.facePhoto ? 'racing-red' : 'transparent'}
            opacity={avatarInfo.facePhoto || errors.facePhoto ? 0.1 : 1}
            className="border-2 border-dashed cursor-pointer transition-all hover:border-primary-blue hover:bg-primary-blue/5"
            position="relative"
          >
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              onChange={handleFileSelect}
              className="hidden"
            />
            
            {avatarInfo.isValidating ? (
              <Stack align="center" center>
                <Icon icon={Loader2} size={10} color="text-primary-blue" className="animate-spin mb-3" />
                <Text size="sm" color="text-gray-400">Validating photo...</Text>
              </Stack>
            ) : avatarInfo.facePhoto ? (
              <Stack align="center" center>
                <Box width={24} height={24} rounded="xl" className="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"
                  />
                </Box>
                <Text size="sm" color="text-performance-green" block>
                  <Stack direction="row" align="center" gap={1}>
                    <Icon icon={Check} size={4} />
                    Photo uploaded
                  </Stack>
                </Text>
                <Text size="xs" color="text-gray-500" mt={1}>Click to change</Text>
              </Stack>
            ) : (
              <Stack align="center" center>
                <Icon icon={Upload} size={10} color="text-gray-500" className="mb-3" />
                <Text size="sm" color="text-gray-300" weight="medium" block mb={1}>
                  Drop your photo here or click to upload
                </Text>
                <Text size="xs" color="text-gray-500">
                  JPEG or PNG, max 5MB
                </Text>
              </Stack>
            )}
          </Box>

          {/* Preview area */}
          <Stack width={32} align="center" center>
            <Surface variant="muted" rounded="xl" border width={24} height={24} display="flex" center className="overflow-hidden">
              {(() => {
                  const selectedAvatarUrl =
                    avatarInfo.selectedAvatarIndex !== null
                      ? avatarInfo.generatedAvatars[avatarInfo.selectedAvatarIndex]
                      : undefined;
                if (!selectedAvatarUrl) {
                  return <Icon icon={User} size={8} color="text-gray-600" />;
                }
                return (
                  <Image src={selectedAvatarUrl} alt="Selected avatar" width={96} height={96} className="w-full h-full object-cover" />
                );
              })()}
            </Surface>
            <Text size="xs" color="text-gray-500" mt={2} align="center" block>Your avatar</Text>
          </Stack>
        </Stack>
        {errors.facePhoto && (
          <Text size="sm" color="text-error-red" block mt={2}>{errors.facePhoto}</Text>
        )}
      </Box>

      {/* Suit Color Selection */}
      <Box>
        <Text as="label" size="sm" weight="medium" color="text-gray-300" block mb={3}>
          <Stack direction="row" align="center" gap={2}>
            <Icon icon={Palette} size={4} />
            Racing Suit Color
          </Stack>
        </Text>
        <Stack direction="row" 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 p-0 ${
                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 && (
                <Icon icon={Check} size={5} className={
                  ['white', 'yellow', 'cyan'].includes(color.value) ? 'text-gray-800' : 'text-white'
                } />
              )}
            </Button>
          ))}
        </Stack>
        <Text size="xs" color="text-gray-500" block mt={2}>
          Selected: {SUIT_COLORS.find(c => c.value === avatarInfo.suitColor)?.label}
        </Text>
      </Box>

      {/* Generate Button */}
      {avatarInfo.facePhoto && !errors.facePhoto && (
        <Box>
          <Button
            type="button"
            variant="primary"
            onClick={onGenerateAvatars}
            disabled={avatarInfo.isGenerating || avatarInfo.isValidating}
            fullWidth
            icon={avatarInfo.isGenerating ? <Icon icon={Loader2} size={5} className="animate-spin" /> : <Icon icon={Sparkles} size={5} />}
          >
            {avatarInfo.isGenerating ? 'Generating your avatars...' : (avatarInfo.generatedAvatars.length > 0 ? 'Regenerate Avatars' : 'Generate Racing Avatars')}
          </Button>
        </Box>
      )}

      {/* Generated Avatars */}
      {avatarInfo.generatedAvatars.length > 0 && (
        <Box>
          <Text as="label" size="sm" weight="medium" color="text-gray-300" block mb={3}>
            Choose Your Avatar *
          </Text>
          <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 p-0 ${
                  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}`} width={200} height={200} className="w-full h-full object-cover" />
                {avatarInfo.selectedAvatarIndex === index && (
                  <Box position="absolute" top={2} right={2} width={6} height={6} rounded="full" backgroundColor="primary-blue" display="flex" center>
                    <Icon icon={Check} size={4} color="text-white" />
                  </Box>
                )}
              </Button>
            ))}
          </Grid>
          {errors.avatar && (
            <Text size="sm" color="text-error-red" block mt={2}>{errors.avatar}</Text>
          )}
        </Box>
      )}
    </Stack>
  );
}
