/**
 * MediaPicker Component
 *
 * WordPress media library picker for selecting images.
 */

import { ImageIcon, Cross2Icon } from "@radix-ui/react-icons";
import type { MediaAttachment } from "@/types/wordpress";

export type { MediaAttachment };

interface MediaPickerProps {
  /** Current image URL */
  value?: string | null;
  /** Callback when image is selected */
  onSelect: (attachment: MediaAttachment) => void;
  /** Callback when image is removed */
  onRemove: () => void;
  /** Media library dialog title */
  title?: string;
  /** Allowed media type */
  mediaType?: string;
  /** Button label when no image selected */
  selectLabel?: string;
  /** Button label when image already selected */
  changeLabel?: string;
  /** Helper text below the picker */
  helpText?: string;
  /** Use compact styling */
  compact?: boolean;
  /** Show preview of selected image */
  showPreview?: boolean;
  /** Preview image size */
  previewSize?: "sm" | "md" | "lg";
  /** Disabled state */
  disabled?: boolean;
}

export function MediaPicker({
  value,
  onSelect,
  onRemove,
  title = "Select Image",
  mediaType = "image",
  selectLabel = "Select Image",
  changeLabel = "Change Image",
  helpText,
  compact = false,
  showPreview = true,
  previewSize = "md",
  disabled = false,
}: MediaPickerProps) {
  // Open WordPress media library
  const openMediaLibrary = () => {
    if (disabled) return;

    // Check that wp.media exists and is a function (fully loaded)
    if (!window.wp?.media || typeof window.wp.media !== "function") {
      console.error("WordPress media library not available or not fully loaded");
      return;
    }

    const mediaFrame = window.wp.media({
      title,
      library: { type: mediaType },
      multiple: false,
    });

    mediaFrame.on("select", () => {
      const attachment = mediaFrame.state().get("selection").first().toJSON();
      onSelect(attachment);
    });

    mediaFrame.open();
  };

  // Preview size classes
  const previewSizeClasses = {
    sm: "w-8 h-8",
    md: "w-16 h-16",
    lg: "w-24 h-24",
  };

  const buttonClass = compact ? "floating-settings__media-btn" : "settings-modal-btn";

  const previewClass = compact ? "floating-settings__media-preview" : "media-picker__preview";

  const removeClass = compact ? "floating-settings__media-remove" : "media-picker__remove";

  return (
    <div className="media-picker">
      {/* Preview with remove button */}
      {value && showPreview && (
        <div className={`${previewClass} relative inline-block mb-2`}>
          <img
            src={value}
            alt="Selected media"
            className={`${previewSizeClasses[previewSize]} object-contain rounded border border-gray-200`}
          />
          {!disabled && (
            <button
              type="button"
              className={`${removeClass} absolute -top-2 -right-2 w-5 h-5 rounded-full bg-red-500 text-white flex items-center justify-center hover:bg-red-600 transition-colors`}
              onClick={onRemove}
              title="Remove image"
            >
              <Cross2Icon className="w-3 h-3" />
            </button>
          )}
        </div>
      )}

      {/* Select/Change button */}
      <button type="button" className={`${buttonClass} flex items-center gap-2`} onClick={openMediaLibrary} disabled={disabled}>
        <ImageIcon className="w-4 h-4" />
        <span>{value ? changeLabel : selectLabel}</span>
      </button>

      {/* Help text */}
      {helpText && <p className="text-xs text-gray-500 mt-2">{helpText}</p>}
    </div>
  );
}

export default MediaPicker;
