import { MediaUpload, MediaUploadCheck } from "@wordpress/block-editor";

interface CustomLogo {
  url: string;
  id: number;
}

interface CustomLogoUploadProps {
  customLogos: CustomLogo[];
  logoOption: string;
  setAttributes: (attrs: Partial<{
    customLogos: CustomLogo[];
    customLogoUrl: string;
    logoOption: string;
  }>) => void;
}

export const CustomLogoUpload = ({ customLogos, logoOption, setAttributes }: CustomLogoUploadProps) => {
  const handleSelect = (media: { url: string; id: number }) => {
    const existing = customLogos || [];
    const newLogo = { url: media.url, id: media.id };
    const alreadyExists = existing.find((logo) => logo.id === media.id);

    if (!alreadyExists) {
      setAttributes({
        customLogos: [...existing, newLogo],
        customLogoUrl: media.url,
        logoOption: `custom-${media.id}`,
      });
    } else {
      setAttributes({
        customLogoUrl: media.url,
        logoOption: `custom-${media.id}`,
      });
    }
  };

  return (
    <div className="scbc-custom-logo-upload">
      {customLogos && customLogos.map((customLogo) => (
        <button
          key={`custom-${customLogo.id}`}
          className={`scbc-logo-option custom-logo ${logoOption === `custom-${customLogo.id}` ? "is-selected" : ""}`}
          onClick={() => {
            if (logoOption === `custom-${customLogo.id}`) {
              setAttributes({ logoOption: "none" });
            } else {
              setAttributes({
                logoOption: `custom-${customLogo.id}`,
                customLogoUrl: customLogo.url,
              });
            }
          }}
          title="Custom Logo"
        >
          <img src={customLogo.url} alt="Custom Logo" />
          {logoOption === `custom-${customLogo.id}` && (
            <span className="scbc-logo-checkmark">✓</span>
          )}
        </button>
      ))}

      <MediaUploadCheck>
        <MediaUpload
          onSelect={handleSelect}
          allowedTypes={["image"]}
          render={({ open }: { open: () => void }) => (
            <button
              className="scbc-logo-option scbc-logo-upload"
              onClick={open}
              title="Upload Custom Logo"
            >
              <div className="scbc-logo-plus">
                <span>+</span>
              </div>
            </button>
          )}
        />
      </MediaUploadCheck>
    </div>
  );
};
