import React, { useState, useRef } from 'react';
import {
  Box,
  Button,
  VStack,
  HStack,
  Text,
  IconButton,
  Progress,
  Badge,
  List,
  ListItem,
  Icon,
  useToast,
  Flex,
} from '@chakra-ui/react';
import { FiUpload, FiX, FiFile, FiImage, FiFileText } from 'react-icons/fi';
import { uploadFile } from '../../services/articles';

export type UploadedFile = {
  url: string;
  name: string;
  type: string;
  size: number;
};

interface MultiFileUploadProps {
  onFilesUploaded: (files: UploadedFile[]) => void;
  existingFiles?: UploadedFile[];
  acceptedTypes?: string;
  maxFiles?: number;
}

const MultiFileUpload: React.FC<MultiFileUploadProps> = ({
  onFilesUploaded,
  existingFiles = [],
  acceptedTypes = 'image/*,application/pdf,.doc,.docx,.xls,.xlsx',
  maxFiles = 10,
}) => {
  const [files, setFiles] = useState<UploadedFile[]>(existingFiles);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const toast = useToast();

  const getFileIcon = (type: string) => {
    if (type.startsWith('image/')) return FiImage;
    if (type.includes('pdf')) return FiFileText;
    return FiFile;
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return Math.round((bytes / Math.pow(k, i)) * 100) / 100 + ' ' + sizes[i];
  };

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = e.target.files;
    if (!selectedFiles || selectedFiles.length === 0) return;

    if (files.length + selectedFiles.length > maxFiles) {
      toast({
        title: 'Příliš mnoho souborů',
        description: `Můžete nahrát maximálně ${maxFiles} souborů`,
        status: 'warning',
      });
      return;
    }

    setUploading(true);
    setUploadProgress(0);

    const uploadedFiles: UploadedFile[] = [];
    const totalFiles = selectedFiles.length;

    try {
      for (let i = 0; i < selectedFiles.length; i++) {
        const file = selectedFiles[i];
        
        // Check file size (max 10MB)
        if (file.size > 10 * 1024 * 1024) {
          toast({
            title: 'Soubor je příliš velký',
            description: `${file.name} překračuje limit 10MB`,
            status: 'error',
          });
          continue;
        }

        try {
          const result = await uploadFile(file);
          uploadedFiles.push({
            url: result.url,
            name: file.name,
            type: file.type,
            size: file.size,
          });
          setUploadProgress(((i + 1) / totalFiles) * 100);
        } catch (error: any) {
          toast({
            title: 'Chyba při nahrávání',
            description: `${file.name}: ${error.message}`,
            status: 'error',
          });
        }
      }

      const updatedFiles = [...files, ...uploadedFiles];
      setFiles(updatedFiles);
      onFilesUploaded(updatedFiles);

      if (uploadedFiles.length > 0) {
        toast({
          title: 'Úspěšně nahráno',
          description: `${uploadedFiles.length} souborů bylo nahráno`,
          status: 'success',
        });
      }
    } finally {
      setUploading(false);
      setUploadProgress(0);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleRemoveFile = (index: number) => {
    const updatedFiles = files.filter((_, i) => i !== index);
    setFiles(updatedFiles);
    onFilesUploaded(updatedFiles);
  };

  const handleCopyUrl = (url: string) => {
    navigator.clipboard.writeText(url);
    toast({
      title: 'Zkopírováno',
      description: 'URL byla zkopírována do schránky',
      status: 'success',
      duration: 2000,
    });
  };

  return (
    <Box>
      <input
        ref={fileInputRef}
        type="file"
        accept={acceptedTypes}
        multiple
        style={{ display: 'none' }}
        onChange={handleFileSelect}
      />

      <Button
        leftIcon={<FiUpload />}
        onClick={() => fileInputRef.current?.click()}
        isLoading={uploading}
        isDisabled={files.length >= maxFiles}
        colorScheme="blue"
        variant="outline"
        size="sm"
      >
        Nahrát soubory ({files.length}/{maxFiles})
      </Button>

      {uploading && (
        <Progress value={uploadProgress} size="sm" colorScheme="blue" mt={2} />
      )}

      {files.length > 0 && (
        <List spacing={2} mt={4}>
          {files.map((file, index) => (
            <ListItem
              key={index}
              p={2}
              borderWidth="1px"
              borderRadius="md"
              bg="gray.50"
              _hover={{ bg: 'gray.100' }}
            >
              <Flex align="center" justify="space-between">
                <HStack spacing={3} flex={1}>
                  <Icon as={getFileIcon(file.type)} boxSize={5} color="blue.500" />
                  <VStack align="start" spacing={0} flex={1}>
                    <Text fontSize="sm" fontWeight="medium" noOfLines={1}>
                      {file.name}
                    </Text>
                    <HStack spacing={2}>
                      <Badge fontSize="xs" colorScheme="gray">
                        {formatFileSize(file.size)}
                      </Badge>
                      {file.type.startsWith('image/') && (
                        <Badge fontSize="xs" colorScheme="blue">Obrázek</Badge>
                      )}
                      {file.type.includes('pdf') && (
                        <Badge fontSize="xs" colorScheme="red">PDF</Badge>
                      )}
                    </HStack>
                  </VStack>
                </HStack>
                <HStack>
                  <Button
                    size="xs"
                    variant="ghost"
                    onClick={() => handleCopyUrl(file.url)}
                  >
                    Kopírovat URL
                  </Button>
                  <IconButton
                    aria-label="Odstranit"
                    icon={<FiX />}
                    size="xs"
                    colorScheme="red"
                    variant="ghost"
                    onClick={() => handleRemoveFile(index)}
                  />
                </HStack>
              </Flex>
            </ListItem>
          ))}
        </List>
      )}

      <Text fontSize="xs" color="gray.600" mt={2}>
        Podporované formáty: obrázky, PDF, Word, Excel (max 10MB na soubor)
      </Text>
    </Box>
  );
};

export default MultiFileUpload;
