/**
 * Download Form Component
 * URL input form for social media video downloads
 * Supports MP4 video and MP3 audio for YouTube
 */

'use client';

import * as React from 'react';
import { useState, useCallback, useEffect } from 'react';
import { Box, Flex, Text, VStack, Spinner, HStack, ButtonGroup } from '@chakra-ui/react';
import { FiDownload, FiLink, FiX, FiYoutube, FiInstagram, FiMusic, FiVideo } from 'react-icons/fi';
import { FaTiktok, FaFacebook, FaTwitter } from 'react-icons/fa';
import { useTranslations } from 'next-intl';
import { Button } from '@/components/ui/buttons/button';
import { InputGroup } from '@/components/ui/forms/input-group';
import { Field } from '@/components/ui/forms/field';
import { Input } from '@chakra-ui/react';
import { IconButton } from '@chakra-ui/react';
import { Platform, PLATFORM_INFO, AudioFormat, VideoQuality } from '@/types/download';
import { NativeSelectRoot, NativeSelectField } from '@/components/ui/forms/native-select';

interface DownloadFormProps {
  onSubmit: (url: string, audioFormat?: AudioFormat, videoQuality?: VideoQuality, audioBitrate?: "320" | "256" | "128" | "64") => Promise<void>;
  onUrlChange?: (url: string) => void;
  isLoading: boolean;
  detectedPlatform: Platform | null;
}

const YOUTUBE_VIDEO_QUALITIES = [
  { value: '1080', label: '1080p (FHD)' },
  { value: '720', label: '720p (HD)' },
  { value: '480', label: '480p' },
  { value: '360', label: '360p' },
];

const YOUTUBE_AUDIO_BITRATES = [
  { value: '320', label: '320 kbps (High)' },
  { value: '256', label: '256 kbps' },
  { value: '128', label: '128 kbps (Normal)' },
  { value: '92', label: '92 kbps (Low)' },
];

export function DownloadForm({ onSubmit, onUrlChange, isLoading, detectedPlatform }: DownloadFormProps) {
  const t = useTranslations('download');
  const [url, setUrl] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [downloadingFormat, setDownloadingFormat] = useState<'video' | 'audio' | null>(null);
  
  // Quality states
  const [videoQuality, setVideoQuality] = useState<VideoQuality>('720');
  const [audioBitrate, setAudioBitrate] = useState<"320" | "256" | "128" | "64" | "92">('128');

  const handleDownload = useCallback(async (format: 'video' | 'audio') => {
    if (!url.trim()) {
      setError(t('errors.urlRequired'));
      return;
    }

    setError(null);
    setDownloadingFormat(format);
    
    // Pass audio format if downloading audio from YouTube
    const audioFormat = format === 'audio' ? 'mp3' : undefined;
    const vQuality = format === 'video' ? videoQuality : undefined;
    const aBitrate = format === 'audio' ? (audioBitrate as "320" | "256" | "128" | "64") : undefined;

    await onSubmit(url.trim(), audioFormat, vQuality, aBitrate);
    setDownloadingFormat(null);
  }, [url, onSubmit, t, videoQuality, audioBitrate]);

  const handleClear = useCallback(() => {
    setUrl('');
    setError(null);
  }, []);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === 'Enter' && !isLoading && url.trim()) {
        handleDownload('video');
      }
    },
    [handleDownload, isLoading, url]
  );

  const getPlatformIcon = (platform: Platform) => {
    switch (platform) {
      case 'youtube':
        return FiYoutube;
      case 'instagram':
        return FiInstagram;
      case 'tiktok':
        return FaTiktok;
      case 'twitter':
        return FaTwitter;
      case 'facebook':
        return FaFacebook;
      default:
        return FiLink;
    }
  };

  const PlatformIcon = detectedPlatform ? getPlatformIcon(detectedPlatform) : FiLink;

  return (
    <Box as="form" onSubmit={(e) => e.preventDefault()}>
      <VStack gap={4} align="stretch">
        <Field errorText={error || undefined} >
          <InputGroup
          width={'100%'}
            startElement={
              isLoading ? (
                <Spinner size="sm" color="primary.500" />
              ) : (
                <Box as={PlatformIcon} color={detectedPlatform ? PLATFORM_INFO[detectedPlatform]?.color : 'gray.500'} />
              )
            }
            endElement={
              url && !isLoading ? (
                <IconButton aria-label="Clear" variant="ghost" size="xs" onClick={handleClear}>
                  <Box as={FiX} />
                </IconButton>
              ) : undefined
            }
          >
            <Input
              placeholder={t('placeholder')}
              value={url}
              onChange={(e) => {
                const newUrl = e.target.value;
                setUrl(newUrl);
                setError(null);
                onUrlChange?.(newUrl);
              }}
              onKeyDown={handleKeyDown}
              borderRadius="xl"
              disabled={isLoading}
              size={'xl'}

            />
          </InputGroup>
        </Field>

        {/* YouTube: MP4 and MP3 buttons side by side */}
        {detectedPlatform === 'youtube' ? (
          <VStack gap={4} align="stretch" width="full">
            <Flex gap={4} direction={{ base: 'column', sm: 'row' }} width="full">
              {/* Video Download Section */}
              <VStack align="stretch" flex={1} gap={2} p={4} borderWidth="1px" borderRadius="xl" borderColor="border.subtle" bg="bg.muted">
                <Text fontSize="sm" fontWeight="medium" color="fg.muted">Video Quality</Text>
                <NativeSelectRoot size="md" disabled={isLoading}>
                  <NativeSelectField 
                    value={videoQuality}
                    onChange={(e) => setVideoQuality(e.currentTarget.value as VideoQuality)}
                    items={YOUTUBE_VIDEO_QUALITIES}
                  />
                </NativeSelectRoot>
                <Button
                  type="button"
                  size="md"
                  colorPalette="primary"
                  fontWeight="semibold"
                  onClick={() => handleDownload('video')}
                  loading={downloadingFormat === 'video'}
                  disabled={isLoading || !url.trim()}
                  mt={2}
                >
                  <Box as={FiVideo} mr={2} />
                  MP4 Video
                </Button>
              </VStack>

              {/* Audio Download Section */}
              <VStack align="stretch" flex={1} gap={2} p={4} borderWidth="1px" borderRadius="xl" borderColor="border.subtle" bg="bg.muted">
                <Text fontSize="sm" fontWeight="medium" color="fg.muted">Audio Quality</Text>
                <NativeSelectRoot size="md" disabled={isLoading}>
                  <NativeSelectField 
                    value={audioBitrate}
                    onChange={(e) => setAudioBitrate(e.currentTarget.value as any)}
                    items={YOUTUBE_AUDIO_BITRATES}
                  />
                </NativeSelectRoot>
                <Button
                  type="button"
                  size="md"
                  colorPalette="green"
                  fontWeight="semibold"
                  onClick={() => handleDownload('audio')}
                  loading={downloadingFormat === 'audio'}
                  disabled={isLoading || !url.trim()}
                  mt={2}
                >
                  <Box as={FiMusic} mr={2} />
                  MP3 Audio
                </Button>
              </VStack>
            </Flex>
          </VStack>
        ) : (
          /* Other platforms: Single download button */
          <Button
            type="submit"
            size="lg"
            width="full"
            colorPalette="primary"
            borderRadius="xl"
            fontWeight="semibold"
            onClick={() => handleDownload('video')}
            loading={isLoading}
            disabled={isLoading || !url.trim()}
          >
            <Box as={FiDownload} mr={2} />
            {isLoading ? t('downloading') : t('download')}
          </Button>
        )}

        <Flex justify="center" gap={4} wrap="wrap">
          {['youtube', 'instagram', 'tiktok', 'twitter', 'facebook'].map((platform) => {
            const IconComponent = getPlatformIcon(platform as Platform);
            return (
              <Flex
                key={platform}
                align="center"
                gap={1}
                opacity={detectedPlatform === platform ? 1 : 0.5}
                transition="opacity 0.2s"
              >
                <Box
                  as={IconComponent}
                  color={PLATFORM_INFO[platform as Platform]?.color}
                  boxSize={4}
                />
                <Text fontSize="xs" color="fg.muted">
                  {PLATFORM_INFO[platform as Platform]?.name}
                </Text>
              </Flex>
            );
          })}
        </Flex>
      </VStack>
    </Box>
  );
}
