import React, { useRef } from "react";
import { useStore } from "../store/store.ts";

export const BackdropUpload: React.FC = () => {
  const backdropUrl = useStore((state) => state.backdropUrl);
  const setBackdrop = useStore((state) => state.setBackdrop);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      if (backdropUrl) {
        URL.revokeObjectURL(backdropUrl);
      }
      const url = URL.createObjectURL(file);
      setBackdrop(url);
    }
  };

  const handleClear = () => {
    if (backdropUrl) {
      URL.revokeObjectURL(backdropUrl);
    }
    setBackdrop(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const handleButtonClick = () => {
    fileInputRef.current?.click();
  };

  return (
    <div className="backdrop-upload">
      <input
        ref={fileInputRef}
        type="file"
        accept="image/png,image/jpeg,image/jpg,image/webp,image/gif"
        onChange={handleFileChange}
        style={{ display: "none" }}
      />
      <button className="upload-backdrop" onClick={handleButtonClick}>
        {backdropUrl ? "Change Backdrop" : "Upload Backdrop"}
      </button>
      {backdropUrl && (
        <button className="clear-backdrop" onClick={handleClear}>
          Clear
        </button>
      )}
    </div>
  );
};
