import { useState, useRef } from "react";
import "./FilePicker.css";
import { formData } from "../../features/context/TOD.FormulaireData.js";

const FilePicker = ({
  value,
  setValue,
  accept = "image/*",
  previewStyle = { marginTop: "1rem", maxWidth: "200px" },
  label = {
    choose: "Choose your logo",
    change: "Change logo",
    current: "Current logo",
    cancel: "Cancel",
    dragText: "Drag and drop your logo here",
    orText: "or",
    uploading: "Uploading...",
  },
}) => {
  const [isEditing, setIsEditing] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef(null);

  // TODO handle delete image
  const uploadImage = async (base64Image) => {
    setIsUploading(true);
    try {
      const response = await wp.apiFetch({
        path: "/wb-onboard/v1/upload-image",
        method: "POST",
        data: { image: base64Image },
      });

      if (response.success) {
        setValue({
          url: response.data.url,
          attachment_id: response.data.attachment_id,
        });
        setIsEditing(false);
      }
    } catch (error) {
      console.error("Upload failed:", error);
    } finally {
      setIsUploading(false);
    }
  };

  const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        uploadImage(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const toggleEdit = () => setIsEditing(!isEditing);

  const handleDrag = (e) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDragIn = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  };

  const handleDragOut = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);

    const file = e.dataTransfer.files[0];
    if (file && file.type.match(accept)) {
      const reader = new FileReader();
      reader.onloadend = () => {
        uploadImage(reader.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const displayUrl = typeof value === "object" ? value?.url : value;
  const hasValidImage = displayUrl && displayUrl !== "";

  return (
    <div className="file-picker-container">
      {isUploading ? (
        <div className="uploading-container">
          <p>{label.uploading}</p>
        </div>
      ) : hasValidImage && !isEditing ? (
        <div className="current-image-container">
          <img src={displayUrl} alt="" style={previewStyle} />
          <button
            className="change-button form-button"
            onClick={(e) => {
              e.stopPropagation();
              setIsEditing(true);
            }}
          >
            {label.change}
          </button>
        </div>
      ) : (
        <>
          <div
            className={`upload-zone ${isDragging ? "dragging" : ""}`}
            onDragEnter={handleDragIn}
            onDragLeave={handleDragOut}
            onDragOver={handleDrag}
            onDrop={handleDrop}
            onClick={() => fileInputRef.current.click()}
          >
            <input
              ref={fileInputRef}
              type="file"
              accept={accept}
              onChange={handleFileChange}
              style={{ display: "none" }}
            />
            <div className="upload-content">
              <svg
                className="upload-icon"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                stroke-width="1.5"
                stroke="currentColor"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  d="M9 8.25H7.5a2.25 2.25 0 0 0-2.25 2.25v9a2.25 2.25 0 0 0 2.25 2.25h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25H15M9 12l3 3m0 0 3-3m-3 3V2.25"
                />
              </svg>
              <p className="drag-text">{label.dragText}</p>
              <p className="or-text">{label.orText}</p>
              <div className="buttons-container">
                <button className="browse-button form-button">
                  Browse files
                </button>
              </div>
            </div>
          </div>
          {isEditing && (
            <button
              className="cancel-button form-button"
              style={{ marginTop: "1rem" }}
              onClick={(e) => {
                e.stopPropagation();
                setIsEditing(false);
              }}
            >
              {label.cancel}
            </button>
          )}
        </>
      )}
    </div>
  );
};

export default FilePicker;
