/**
 * ImageSelector
 *
 * 共通画像セレクターコンポーネント
 * - 画像検索
 * - プリセット画像の選択
 * - メディアライブラリからの選択
 * - URL直接入力
 */

import { createInterpolateElement, useEffect, useState } from "@wordpress/element";
import { Button, TextControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { MediaUpload, MediaUploadCheck } from "@wordpress/block-editor";
import { check, image, link, search } from "@wordpress/icons";
import PresetImageSelector from "./PresetImageSelector";
import OpenverseImageSelector from "./OpenverseImageSelector";
import "./ImageSelector.css";

const PRESET_LICENSE_MSGID = "Preset images are sourced from <source>StockSnap</source>. License: <license>CC0 1.0</license>. Available for commercial use, no attribution required.";

const getPresetLicenseNotice = () => {
  return __(PRESET_LICENSE_MSGID, "zenblocks");
};

/**
 * ImageSelector Component
 *
 * @param {Object} props
 * @param {string} props.value - 現在の画像URL
 * @param {Function} props.onChange - 画像URL変更時のコールバック関数
 * @param {Array} props.presetImages - プリセット画像リスト [{id, url, label, category?}]
 * @param {Array} props.presetCategories - プリセットカテゴリリスト [{id, label}] (オプション)
 * @param {boolean} props.enablePreset - プリセット選択を有効にするか (デフォルト: true)
 * @param {boolean} props.enableMedia - メディアライブラリ選択を有効にするか (デフォルト: true)
 * @param {boolean} props.enableUrl - URL入力を有効にするか (デフォルト: true)
 * @param {boolean} props.showPreview - プレビューを表示するか (デフォルト: false)
 * @param {string} props.presetLabel - プリセットセクションのラベル
 * @param {number} props.presetColumns - プリセットグリッドの列数
 * @param {string} props.mediaButtonLabel - メディア選択ボタンのラベル
 * @param {string} props.mediaChangeButtonLabel - メディア変更ボタンのラベル
 * @param {string} props.removeButtonLabel - 削除ボタンのラベル
 * @param {boolean} props.enableOpenverse - Openverse検索を有効にするか (デフォルト: false)
 * @param {string} props.className - 追加のCSSクラス
 * @returns {JSX.Element}
 */
const ImageSelector = ({
  value = "",
  onChange,
  presetImages = [],
  presetCategories = [],
  enablePreset = true,
  enableMedia = true,
  enableUrl = true,
  showPreview = false,
  presetLabel = __("Preset", "zenblocks"),
  presetColumns = 4,
  mediaButtonLabel = __("Select Image", "zenblocks"),
  mediaChangeButtonLabel = __("Change Image", "zenblocks"),
  removeButtonLabel = __("Remove Image", "zenblocks"),
  enableOpenverse = false,
  className = "",
}) => {
  const [urlInputValue, setUrlInputValue] = useState(value || "");
  const presetListIcon = (
    <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
      <line x1="6" y1="7" x2="18" y2="7" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
      <line x1="6" y1="12" x2="18" y2="12" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
      <line x1="6" y1="17" x2="18" y2="17" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
    </svg>
  );

  const tabItems = [
    enablePreset && presetImages.length > 0 ? { id: "preset", label: __("Preset", "zenblocks"), icon: presetListIcon } : null,
    enableOpenverse ? { id: "search", label: __("Search", "zenblocks"), icon: search } : null,
    enableMedia ? { id: "media", label: __("Media", "zenblocks"), icon: image } : null,
    enableUrl ? { id: "url", label: __("URL", "zenblocks"), icon: link } : null,
  ].filter(Boolean);

  const [activeTab, setActiveTab] = useState(tabItems[0]?.id || "");

  useEffect(() => {
    if (!tabItems.some((item) => item.id === activeTab)) {
      setActiveTab(tabItems[0]?.id || "");
    }
  }, [tabItems, activeTab]);

  useEffect(() => {
    setUrlInputValue(value || "");
  }, [value]);

  const handlePresetSelect = (url) => {
    onChange && onChange(url);
    setUrlInputValue(url);
  };

  const handleMediaSelect = (selectedImage) => {
    if (!selectedImage?.url) {
      return;
    }
    onChange && onChange(selectedImage.url);
    setUrlInputValue(selectedImage.url);
  };

  const handleUrlSubmit = () => {
    onChange && onChange(urlInputValue);
  };

  const handleRemove = () => {
    onChange && onChange("");
    setUrlInputValue("");
  };

  const renderActivePanel = () => {
    if (activeTab === "search") {
      return (
        <OpenverseImageSelector
          onSelect={handlePresetSelect}
          showToggle={false}
          initialOpen={true}
        />
      );
    }

    if (activeTab === "preset") {
      return (
        <PresetImageSelector
          images={presetImages}
          categories={presetCategories}
          selectedUrl={value}
          onSelect={handlePresetSelect}
          label={presetLabel}
          columns={presetColumns}
          showCategories={presetCategories.length > 0}
          initialOpen={true}
          showToggle={false}
          showLicenseNotice={false}
        />
      );
    }

    if (activeTab === "media") {
      return (
        <div className="zenblocks-image-selector__panel-inner">
          <MediaUploadCheck>
            <MediaUpload
              onSelect={handleMediaSelect}
              allowedTypes={["image"]}
              value={value}
              render={({ open }) => (
                <Button
                  onClick={open}
                  variant="primary"
                  icon={image}
                  className="zenblocks-image-selector__media-picker-button"
                >
                  {value ? mediaChangeButtonLabel : mediaButtonLabel}
                </Button>
              )}
            />
          </MediaUploadCheck>
        </div>
      );
    }

    if (activeTab === "url") {
      return (
        <div className="zenblocks-image-selector__panel-inner zenblocks-image-selector__url-input">
          <div className="zenblocks-image-selector__url-row">
            <TextControl
              label={__("Image URL", "zenblocks")}
              hideLabelFromVision={true}
              value={urlInputValue}
              onChange={setUrlInputValue}
              placeholder="https://example.com/image.jpg"
            />
            <div className="zenblocks-image-selector__url-actions">
              <Button
                onClick={handleUrlSubmit}
                variant="primary"
                disabled={!urlInputValue.trim()}
                icon={check}
                label={__("Apply", "zenblocks")}
                showTooltip
                className="zenblocks-image-selector__url-apply-button"
              >
              </Button>
            </div>
          </div>
        </div>
      );
    }

    return null;
  };

  return (
    <div className={`zenblocks-image-selector ${className}`}>
      {tabItems.length > 0 && (
        <div className="zenblocks-media-type-tabs zenblocks-image-selector__tabs" role="tablist" aria-label={__("Image source", "zenblocks")}>
          {tabItems.map((item) => (
            <Button
              role="tab"
              aria-selected={activeTab === item.id}
              key={item.id}
              className={`zenblocks-media-type-tabs__button zenblocks-image-selector__tab-button ${activeTab === item.id ? "is-active" : ""}`}
              onClick={() => setActiveTab(item.id)}
              title={item.label}
              aria-label={item.label}
            >
              <span className="zenblocks-image-selector__tab-button-icon">{item.icon}</span>
            </Button>
          ))}
        </div>
      )}

      {activeTab === "preset" && (
        <p className="zenblocks-image-selector__tab-description">
          {createInterpolateElement(
            getPresetLicenseNotice(),
            {
              source: <a href="https://stocksnap.io/" target="_blank" rel="noopener noreferrer">StockSnap</a>,
              license: <a href="https://creativecommons.org/publicdomain/zero/1.0/" target="_blank" rel="noopener noreferrer">CC0 1.0</a>,
            }
          )}
        </p>
      )}

      {activeTab === "url" && (
        <p className="zenblocks-image-selector__tab-description">
          {__("Enter an image URL and click the check button to apply.", "zenblocks")}
        </p>
      )}

      <div className="zenblocks-image-selector__panel">
        {renderActivePanel()}
      </div>

      {showPreview && value && (
        <div className="zenblocks-image-selector__preview">
          <img src={value} alt={__("Preview", "zenblocks")} />
        </div>
      )}

      {value && (
        <div className="zenblocks-image-selector__remove-link-wrap">
          <button
            type="button"
            className="zenblocks-image-selector__remove-link"
            onClick={handleRemove}
          >
            {removeButtonLabel}
          </button>
        </div>
      )}
    </div>
  );
};

export default ImageSelector;
