import React from "react";
import ArrowLeftIcon from "@mui/icons-material/ArrowLeft";
import ArrowRightIcon from "@mui/icons-material/ArrowRight";
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 [hoveredId, setHoveredId] = React.useState(null);

  React.useEffect(() => {
    setExtFiles(value || []);
  }, [value]);

  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
      )
    );
  };

  const moveFile = (fromIndex, toIndex) => {
    setExtFiles((prev) => {
      if (toIndex < 0 || toIndex >= prev.length) return prev;
      const updated = [...prev];
      const [moved] = updated.splice(fromIndex, 1);
      updated.splice(toIndex, 0, moved);
      onChange && onChange(updated);
      return updated;
    });
  };

  return (
    <>
      <Dropzone
        onChange={updateFiles}
        minHeight="195px"
        value={extFiles}
        accept="image/*"
        maxFiles={3}
        maxFileSize={10 * 1024 * 1024}
        label="Drag'n drop up to 3 images (max 10 MB each)"
        uploadConfig={{
          url: BASE_URL + "/file",
          cleanOnUpload: true,
        }}
        onUploadStart={handleStart}
        onUploadFinish={handleFinish}
        fakeUpload
        actionButtons={{
          position: "after",
          abortButton: {},
        }}
      >
        {extFiles.map((file, index) => (
          <div
            key={file.id}
            style={{
              position: "relative",
              display: "inline-block",
              marginBottom: 12,
            }}
            onMouseEnter={() => setHoveredId(file.id)}
            onMouseLeave={() => setHoveredId(null)}
          >
            <FileMosaic
              {...file}
              onDelete={onDelete}
              onSee={handleSee}
              onWatch={handleWatch}
              onAbort={handleAbort}
              onCancel={handleCancel}
              resultOnTooltip
              alwaysActive
              preview
              info={false}
            />
            {hoveredId === file.id && (
            <div
              style={{
                position: "absolute",
                left: 8,
                right: 8,
                bottom: 8,
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
                padding: "6px 8px",
                borderRadius: 8,
                background: "rgba(0,0,0,0.5)",
                pointerEvents: "auto",
                zIndex: 5,
              }}
            >
              <button
                type="button"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  moveFile(index, index - 1);
                }}
                disabled={index === 0}
                style={{
                  width: 32,
                  height: 32,
                  borderRadius: "50%",
                  border: "1px solid rgba(255,255,255,0.6)",
                  background: index === 0 ? "rgba(255,255,255,0.4)" : "#fff",
                  cursor: index === 0 ? "not-allowed" : "pointer",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  boxShadow: "0 2px 6px rgba(0,0,0,0.2)",
                }}
                aria-label="Move left"
              >
                <ArrowLeftIcon fontSize="small" />
              </button>
              <span
                style={{
                  color: "#fff",
                  fontSize: 12,
                  opacity: 0.95,
                  maxWidth: 140,
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                  whiteSpace: "nowrap",
                }}
                title={file.name}
              >
                {file.name}
              </span>
              <button
                type="button"
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  moveFile(index, index + 1);
                }}
                disabled={index === extFiles.length - 1}
                style={{
                  width: 32,
                  height: 32,
                  borderRadius: "50%",
                  border: "1px solid rgba(255,255,255,0.6)",
                  background:
                    index === extFiles.length - 1
                      ? "rgba(255,255,255,0.4)"
                      : "#fff",
                  cursor:
                    index === extFiles.length - 1 ? "not-allowed" : "pointer",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  boxShadow: "0 2px 6px rgba(0,0,0,0.2)",
                }}
                aria-label="Move right"
              >
                <ArrowRightIcon fontSize="small" />
              </button>
            </div>
            )}
          </div>
        ))}
      </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;
