/**
 * Home Page - Video Downloader
 * Main page for social media video downloads
 */

'use client';

import * as React from 'react';
import { useState, useCallback, useEffect } from 'react';
import { Box, Container, Heading, Text, VStack, Flex } from '@chakra-ui/react';
import { FiDownloadCloud } from 'react-icons/fi';
import { useTranslations } from 'next-intl';
import { DownloadForm } from '@/components/site/download/download-form';
import { DownloadResult } from '@/components/site/download/download-result';
import { detectPlatform } from '@/lib/download/platform-detector';
import { Platform, DownloadResponse, AudioFormat } from '@/types/download';
import { toaster } from '@/components/ui/feedback/toaster';

export default function HomePage() {
  const t = useTranslations('download');
  const [url, setUrl] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [detectedPlatform, setDetectedPlatform] = useState<Platform | null>(null);
  const [result, setResult] = useState<DownloadResponse | null>(null);

  // Detect platform when URL changes
  useEffect(() => {
    if (url.trim()) {
      const detection = detectPlatform(url);
      setDetectedPlatform(detection.platform);
    } else {
      setDetectedPlatform(null);
    }
  }, [url]);

  // Handle download submission
  const handleSubmit = useCallback(async (
    inputUrl: string, 
    audioFormat?: AudioFormat, 
    videoQuality?: string, 
    audioBitrate?: string
  ) => {
    setUrl(inputUrl);
    setIsLoading(true);
    setResult(null);

    try {
      const response = await fetch('/api/download', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          url: inputUrl,
          audioFormat: audioFormat,
          quality: videoQuality,
          audioBitrate: audioBitrate,
        }),
      });

      const data = await response.json();
      setResult(data);
      
      // Show error toaster if request failed
      if (!data.success && data.error) {
        toaster.error({
          title: t('errors.downloadFailed'),
          description: data.error.message,
        });
      }
    } catch (error) {
      console.error('Download error:', error);
      const errorResponse = {
        success: false,
        error: {
          code: 'NETWORK_ERROR',
          message: 'Network error. Please check your connection.',
        },
      };
      setResult(errorResponse);
      
      // Show error toaster
      toaster.error({
        title: t('errors.networkError'),
        description: errorResponse.error.message,
      });
    } finally {
      setIsLoading(false);
    }
  }, [t]);

  // Handle URL change for platform detection
  const handleUrlChange = useCallback((newUrl: string) => {
    setUrl(newUrl);
  }, []);

  // Reset state
  const handleReset = useCallback(() => {
    setResult(null);
    setUrl('');
    setDetectedPlatform(null);
  }, []);

  return (
    <Container maxW="container.md" py={{ base: 8, md: 16 }}>
      <VStack gap={8} align="stretch">
        {/* Header */}
        <VStack gap={4} textAlign="center">
          <Flex
            w={16}
            h={16}
            borderRadius="full"
            bg="primary.100"
            _dark={{ bg: 'primary.900' }}
            align="center"
            justify="center"
            mx="auto"
          >
            <Box as={FiDownloadCloud} boxSize={8} color="primary.500" />
          </Flex>
          <Heading size={{ base: 'xl', md: '2xl' }} fontWeight="bold">
            {t('title')}
          </Heading>
          <Text fontSize="lg" color="fg.muted" maxW="md" mx="auto">
            {t('subtitle')}
          </Text>
        </VStack>

        {/* Main Card */}
        <Box
          p={{ base: 4, md: 8 }}
          borderRadius="2xl"
          bg="bg.panel"
          border="1px solid"
          borderColor="border.emphasized"
          boxShadow={{ base: 'none', md: 'lg' }}
        >
          <VStack gap={6} align="stretch">
            {/* Form or Result */}
            {result ? (
              <DownloadResult result={result} onReset={handleReset} />
            ) : (
              <DownloadForm
                onSubmit={handleSubmit}
                onUrlChange={handleUrlChange}
                isLoading={isLoading}
                detectedPlatform={detectedPlatform}
              />
            )}
          </VStack>
        </Box>

        {/* Help Section */}
        <VStack gap={4} textAlign="center">
          <Text fontSize="sm" color="fg.muted">
            {t('supportedPlatforms')}
          </Text>
          <Flex
            gap={6}
            wrap="wrap"
            justify="center"
            fontSize="sm"
            color="fg.subtle"
          >
            <Text>YouTube</Text>
            <Text>Instagram</Text>
            <Text>TikTok</Text>
            <Text>X (Twitter)</Text>
            <Text>Facebook</Text>
          </Flex>
        </VStack>

        {/* Disclaimer */}
        <Text
          fontSize="xs"
          color="fg.muted"
          textAlign="center"
          maxW="md"
          mx="auto"
        >
          {t('disclaimer')}
        </Text>
      </VStack>
    </Container>
  );
}
