import React from "react";
import {
  Dropzone,
  FileMosaic,
  FullScreen,
  ImagePreview,
  VideoPreview,
} from "@files-ui/react";

const BASE_URL = "https://www.myserver.com";

const AdvancedDropzone = ({ value, onChange }) => {
  const [extFiles, setExtFiles] = React.useState(value || []);
  const [imageSrc, setImageSrc] = React.useState(undefined);
  const [videoSrc, setVideoSrc] = React.useState(undefined);

  const updateFiles = (incomingFiles) => {
    console.log("incoming files", incomingFiles);
    setExtFiles(incomingFiles);
    onChange && onChange(incomingFiles); // pass back to parent (e.g. Redux)
  };

  const onDelete = (id) => {
    const updated = extFiles.filter((x) => x.id !== id);
    setExtFiles(updated);
    onChange && onChange(updated);
  };

  const handleSee = (imageSource) => setImageSrc(imageSource);
  const handleWatch = (videoSource) => setVideoSrc(videoSource);

  const handleStart = (filesToUpload) => {
    console.log("advanced demo start upload", filesToUpload);
  };

  const handleFinish = (uploadedFiles) => {
    console.log("advanced demo finish upload", uploadedFiles);
  };

  const handleAbort = (id) => {
    setExtFiles((prev) =>
      prev.map((ef) =>
        ef.id === id ? { ...ef, uploadStatus: "aborted" } : ef
      )
    );
  };

  const handleCancel = (id) => {
    setExtFiles((prev) =>
      prev.map((ef) =>
        ef.id === id ? { ...ef, uploadStatus: undefined } : ef
      )
    );
  };

  return (
    <>
      <Dropzone
        onChange={updateFiles}
        minHeight="195px"
        value={extFiles}
        accept="image/*, video/*"
        maxFiles={3}
        maxFileSize={2 * 1024 * 1024}
        label="Drag'n drop files here or click to browse"
        uploadConfig={{
          url: BASE_URL + "/file",
          cleanOnUpload: true,
        }}
        onUploadStart={handleStart}
        onUploadFinish={handleFinish}
        fakeUpload
        actionButtons={{
          position: "after",
          abortButton: {},
          deleteButton: {},
          uploadButton: {},
        }}
      >
        {extFiles.map((file) => (
          <FileMosaic
            {...file}
            key={file.id}
            onDelete={onDelete}
            onSee={handleSee}
            onWatch={handleWatch}
            onAbort={handleAbort}
            onCancel={handleCancel}
            resultOnTooltip
            alwaysActive
            preview
            info
          />
        ))}
      </Dropzone>

      <FullScreen
        open={imageSrc !== undefined}
        onClose={() => setImageSrc(undefined)}
      >
        <ImagePreview src={imageSrc} />
      </FullScreen>

      <FullScreen
        open={videoSrc !== undefined}
        onClose={() => setVideoSrc(undefined)}
      >
        <VideoPreview src={videoSrc} autoPlay controls />
      </FullScreen>
    </>
  );
};

export default AdvancedDropzone;
