import { useRef } from 'react';

import { Button, Flex, Progress, Text } from '@chakra-ui/react';

import {
  DialogBody,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
} from '@/components/ui/dialog';

export type PopUpUploadProgressProps = {
  title: string;
  // current size send or receive
  currentSize: number;
  // in case of error this element is set to != undefined
  error?: string;
  // Total size to transfer
  totalSize: number;
  // index of the file to transfer
  index: number;
  // When finished the boolean is set to true
  isFinished: boolean;
  // List of element to Transfer
  elements: string[];
  onAbort: () => void;
  onClose: () => void;
};

export const PopUpUploadProgress = ({
  currentSize,
  elements,
  error,
  index,
  isFinished,
  onAbort,
  onClose,
  title,
  totalSize,
}: PopUpUploadProgressProps) => {
  const initialRef = useRef<HTMLButtonElement>(null);
  const finalRef = useRef<HTMLButtonElement>(null);
  return (
    <DialogRoot
      //initialFocusRef={initialRef}
      //finalFocusRef={finalRef}
      //closeOnOverlayClick={false}
      onOpenChange={onClose}
      open={true}
      data-testid="upload-progress-edit-pop-up"
    >
      {/* <DialogOverlay /> */}
      <DialogContent>
        <DialogHeader>{title}</DialogHeader>
        {/* <DialogCloseButton ref={finalRef} /> */}

        <DialogBody pb={6} paddingLeft="18px">
          <Flex direction="column" gap="10px">
            {isFinished ? (
              <Text fontSize="20px" fontWeight="bold">
                All {elements.length} element have been sent
              </Text>
            ) : (
              <Text fontSize="20px" fontWeight="bold">
                [{index + 1}/{elements.length}] {elements[index]}
              </Text>
            )}
            <Progress.Root
              colorScheme="green"
              striped
              value={currentSize}
              animated
              max={totalSize}
              height="24px"
              width="full"
              colorPalette="blue"
            >
              <Progress.Track>
                <Progress.Range />
              </Progress.Track>
            </Progress.Root>
            <Flex>
              <Text>{currentSize.toLocaleString('fr-FR')} Bytes</Text>
              <Text marginLeft="auto">
                {totalSize.toLocaleString('fr-FR')} Bytes
              </Text>
            </Flex>
            {error && (
              <Text fontWeight="bold" color="darkred" whiteSpace="pre-wrap">
                {error}
              </Text>
            )}
          </Flex>
        </DialogBody>
        <DialogFooter>
          {isFinished ? (
            <Button onClick={onClose} colorPalette="green">
              Ok
            </Button>
          ) : (
            <Button colorScheme="red" mr={3} onClick={onAbort} ref={initialRef}>
              Abort
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </DialogRoot>
  );
};
