import React from "react";
import { useFormContext } from "react-hook-form";

const toBase64 = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });

export const LogoUpload = ({ preview, setPreview, fileName, setFileName }) => {
  const {
    register,
    setValue,
    formState: { errors },
  } = useFormContext();

  const handleUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (file.size > 5 * 1024 * 1024) {
      alert("File exceeds 5MB limit");
      return;
    }

    const base64 = await toBase64(file);
    setValue("logoImage", base64, { shouldValidate: true });
    setFileName(file.name);
    setPreview(URL.createObjectURL(file));
    e.target.value = "";
  };

  const handleClear = () => {
    setValue("logoImage", "", { shouldValidate: true });
    setPreview(null);
    setFileName("");
  };

  return (
    <div className="col-sm-12 mb-3">
      <div
        className="border border-secondary border-dashed rounded p-2 text-center  position-relative"
        style={{ cursor: "pointer" }}
        onClick={() => document.getElementById("logoImageInput")?.click()}
      >
        <i className="bx bx-cloud-upload d-block bx-lg mb-2"></i>
        <span className="text-muted">Click or browse to upload</span>

        <input
          type="file"
          id="logoImageInput"
          accept="image/png, image/jpeg"
          style={{ display: "none" }}
          {...register("logoImage")}
          onChange={handleUpload}
        />
      </div>

      {errors.logoImage && (
        <small className="danger-text">{errors.logoImage.message}</small>
      )}

      {preview && (
        <div className="mt-2 d-flex align-items-start gap-2">
          <img
            src={preview}
            alt="Preview"
            className="img-thumbnail rounded"
            style={{ maxHeight: "35px" }}
          />
          <div className="d-flex align-items-center gap-2 mt-1">
            <span className="small text-muted">{fileName}</span>
            <i
              className="bx bx-trash bx-sm text-danger"
              style={{ cursor: "pointer" }}
              onClick={handleClear}
            ></i>
          </div>
        </div>
      )}
    </div>
  );
};
