import { PanelBody, SelectControl, TextControl, ToggleControl, ColorPalette } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { ResponsiveTabProvider } from "../../ResponsiveTabContext";
import ResponsiveControl from "../../ResponsiveControl";

/**
 * テキスト基本設定コンポーネント
 *
 * @param {Object} props コンポーネントのプロパティ
 * @param {Object} props.attributes ブロックの属性
 * @param {Function} props.setAttributes 属性を更新する関数
 * @param {string} props.title パネルのタイトル
 * @param {boolean} props.initialOpen パネルの初期状態
 * @param {boolean} props.showTitleTag タイトルタグ選択を表示するか
 * @param {boolean} props.showCaption キャプション設定を表示するか
 * @param {boolean} props.showTitle タイトル設定を表示するか
 * @param {boolean} props.showDescription 説明設定を表示するか
 * @returns {JSX.Element} テキスト設定パネル
 */
const TextBasic = ({ 
  attributes, 
  setAttributes, 
  title = __("Text Settings", "zenblocks"), 
  initialOpen = false,
  showTitleTag = true,
  showCaption = true,
  showTitle = true,
  showDescription = true
}) => {

  // フォントサイズオプション
  const fontSizeOptions = [
    { label: __("Default", "zenblocks"), value: null },
    { label: __("Small (12px)", "zenblocks"), value: 12 },
    { label: __("Normal (16px)", "zenblocks"), value: 16 },
    { label: __("Medium (20px)", "zenblocks"), value: 20 },
    { label: __("Large (24px)", "zenblocks"), value: 24 },
    { label: __("Extra Large (28px)", "zenblocks"), value: 28 },
    { label: __("Custom", "zenblocks"), value: "custom" },
  ];

  const titleFontSizeOptions = [
    { label: __("Default", "zenblocks"), value: null },
    { label: __("Medium (28px)", "zenblocks"), value: 28 },
    { label: __("Large (32px)", "zenblocks"), value: 32 },
    { label: __("Extra Large (36px)", "zenblocks"), value: 36 },
    { label: __("XXL (48px)", "zenblocks"), value: 48 },
    { label: __("Huge (64px)", "zenblocks"), value: 64 },
    { label: __("Custom", "zenblocks"), value: "custom" },
  ];

  const fontSizeUnitOptions = [
    { label: "px", value: "px" },
    { label: "em", value: "em" },
    { label: "rem", value: "rem" },
    { label: "%", value: "%" },
    { label: "vw", value: "vw" },
  ];

  const titleTagOptions = [
    { label: __("Heading 1 (h1)", "zenblocks"), value: "h1" },
    { label: __("Heading 2 (h2)", "zenblocks"), value: "h2" },
    { label: __("Heading 3 (h3)", "zenblocks"), value: "h3" },
    { label: __("Heading 4 (h4)", "zenblocks"), value: "h4" },
    { label: __("Heading 5 (h5)", "zenblocks"), value: "h5" },
    { label: __("Heading 6 (h6)", "zenblocks"), value: "h6" },
    { label: __("Paragraph (p)", "zenblocks"), value: "p" },
  ];

  // フォントファミリーオプション（テーマのtheme.jsonに基づく）
  const fontFamilyOptions = [
    { label: __("System Font", "zenblocks"), value: "system" },
    { label: __("Noto Sans JP", "zenblocks"), value: "noto-sans-jp" },
    { label: __("Noto Serif JP", "zenblocks"), value: "noto-serif-jp" },
    { label: __("M PLUS 1p", "zenblocks"), value: "m-plus-1p" },
    { label: __("M PLUS Rounded 1c", "zenblocks"), value: "m-plus-rounded-1c" },
    { label: __("Sawarabi Gothic", "zenblocks"), value: "sawarabi-gothic" },
  ];

  return (
    <>
      {showTitleTag && (
        <PanelBody title={__("Basic", "zenblocks")} initialOpen={true}>
          <div style={{ marginTop: "10px" }}>
            <SelectControl 
              label={__("Title Tag", "zenblocks")} 
              value={attributes.titleTagName} 
              options={titleTagOptions} 
              onChange={(value) => setAttributes({ titleTagName: value })} 
            />
          </div>
        </PanelBody>
      )}

      <ResponsiveTabProvider>
        {showCaption && (
          <PanelBody title={__("Caption", "zenblocks")} initialOpen={false}>
            <ResponsiveControl>
              {(activeTab) => (
                <div>
                  <FontSizeControl
                    label={__("Font Size", "zenblocks")}
                    attributes={attributes}
                    setAttributes={setAttributes}
                    type="caption"
                    device={activeTab}
                    options={fontSizeOptions}
                    unitOptions={fontSizeUnitOptions}
                  />
                  <LineHeightControl 
                    label={__("Line Height", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    type="caption" 
                    device={activeTab} 
                  />
                  <MarginControl 
                    label={__("Bottom Margin", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    marginType="captionToTitle" 
                    device={activeTab} 
                  />
                  <ColorControl 
                    label={__("Text Color", "zenblocks")} 
                    colorValue={attributes.captionColor} 
                    onColorChange={(value) => setAttributes({ captionColor: value })} 
                  />
                  <FontFamilyControl 
                    label={__("Font Family", "zenblocks")} 
                    value={attributes.captionFontFamily || "noto-sans-jp"} 
                    options={fontFamilyOptions} 
                    onChange={(value) => setAttributes({ captionFontFamily: value })} 
                  />
                  <TextShadowControl 
                    label={__("Text Shadow", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    type="caption" 
                  />
                </div>
              )}
            </ResponsiveControl>
          </PanelBody>
        )}

        {showTitle && (
          <PanelBody title={__("Title", "zenblocks")} initialOpen={false}>
            <ResponsiveControl>
              {(activeTab) => (
                <div>
                  <FontSizeControl
                    label={__("Font Size", "zenblocks")}
                    attributes={attributes}
                    setAttributes={setAttributes}
                    type="title"
                    device={activeTab}
                    options={titleFontSizeOptions}
                    unitOptions={fontSizeUnitOptions}
                  />
                  <LineHeightControl 
                    label={__("Line Height", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    type="title" 
                    device={activeTab} 
                  />
                  <MarginControl 
                    label={__("Bottom Margin", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    marginType="titleToDescription" 
                    device={activeTab} 
                  />
                  <ColorControl 
                    label={__("Text Color", "zenblocks")} 
                    colorValue={attributes.titleColor} 
                    onColorChange={(value) => setAttributes({ titleColor: value })} 
                  />
                  <FontFamilyControl 
                    label={__("Font Family", "zenblocks")} 
                    value={attributes.titleFontFamily || "noto-sans-jp"} 
                    options={fontFamilyOptions} 
                    onChange={(value) => setAttributes({ titleFontFamily: value })} 
                  />
                  <TextShadowControl 
                    label={__("Text Shadow", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    type="title" 
                  />
                </div>
              )}
            </ResponsiveControl>
          </PanelBody>
        )}

        {showDescription && (
          <PanelBody title={__("Description", "zenblocks")} initialOpen={false}>
            <ResponsiveControl>
              {(activeTab) => (
                <div>
                  <FontSizeControl
                    label={__("Font Size", "zenblocks")}
                    attributes={attributes}
                    setAttributes={setAttributes}
                    type="description"
                    device={activeTab}
                    options={fontSizeOptions}
                    unitOptions={fontSizeUnitOptions}
                  />
                  <LineHeightControl 
                    label={__("Line Height", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    type="description" 
                    device={activeTab} 
                  />
                  <MarginControl 
                    label={__("Bottom Margin", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    marginType="description" 
                    device={activeTab} 
                  />
                  <ColorControl 
                    label={__("Text Color", "zenblocks")} 
                    colorValue={attributes.descriptionColor} 
                    onColorChange={(value) => setAttributes({ descriptionColor: value })} 
                  />
                  <FontFamilyControl 
                    label={__("Font Family", "zenblocks")} 
                    value={attributes.descriptionFontFamily || "noto-sans-jp"} 
                    options={fontFamilyOptions} 
                    onChange={(value) => setAttributes({ descriptionFontFamily: value })} 
                  />
                  <TextShadowControl 
                    label={__("Text Shadow", "zenblocks")} 
                    attributes={attributes} 
                    setAttributes={setAttributes} 
                    type="description" 
                  />
                </div>
              )}
            </ResponsiveControl>
          </PanelBody>
        )}
      </ResponsiveTabProvider>
    </>
  );
};

// フォントサイズコントロールコンポーネント
const FontSizeControl = ({ label, attributes, setAttributes, type, device, options, unitOptions }) => {
  const isPC = device === "pc";
  const currentSize = attributes[`${type}FontSize`];
  const currentUnitAttr = `${type}FontSizeUnit${device.toUpperCase()}`;
  const currentUnit = attributes[currentUnitAttr] || (isPC ? "px" : "vw");
  const customSizeAttr = `custom${type.charAt(0).toUpperCase() + type.slice(1)}FontSize${device.toUpperCase()}`;
  const customSize = attributes[customSizeAttr] || "";
  const isCustom = currentSize === "custom";

  return (
    <div className="responsive-font-size-settings">
      <SelectControl
        label={label}
        value={isCustom ? "custom" : currentSize}
        options={options}
        onChange={(value) => {
          if (value === "custom") {
            setAttributes({
              [`${type}FontSize`]: "custom",
            });
          } else {
            setAttributes({
              [`${type}FontSize`]: value !== null ? Number(value) : null,
            });
          }
        }}
      />

      {isCustom && (
        <div style={{ display: "flex", alignItems: "flex-end", gap: "8px", marginTop: "8px" }}>
          <div style={{ flex: 1 }}>
            <TextControl
              label={__("Custom Size", "zenblocks")}
              value={customSize}
              onChange={(value) => {
                const processedValue = value === "" ? "" : value;
                setAttributes({
                  [customSizeAttr]: processedValue,
                });
              }}
            />
          </div>
          <div style={{ minWidth: "80px" }}>
            <SelectControl
              label={__("Unit", "zenblocks")}
              value={currentUnit}
              options={unitOptions}
              onChange={(value) => {
                setAttributes({
                  [currentUnitAttr]: value,
                });
              }}
            />
          </div>
        </div>
      )}
    </div>
  );
};

// 行間コントロールコンポーネント
const LineHeightControl = ({ label, attributes, setAttributes, type, device }) => {
  const lineHeightAttr = `${type}LineHeight${device.toUpperCase()}`;
  const unitAttr = `lineHeightUnit${device.toUpperCase()}`;
  const currentLineHeight = attributes[lineHeightAttr] || "";
  const currentUnit = attributes[unitAttr] || "";

  const lineHeightUnitOptions = [
    { label: "なし", value: "" },
    { label: "px", value: "px" },
    { label: "em", value: "em" },
    { label: "rem", value: "rem" },
    { label: "%", value: "%" },
  ];

  return (
    <div className="line-height-control" style={{ marginTop: "16px" }}>
      <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
        <div style={{ flex: 1 }}>
          <TextControl
            label={label}
            value={currentLineHeight}
            onChange={(value) => {
              setAttributes({
                [lineHeightAttr]: value,
              });
            }}
          />
        </div>
        <div style={{ minWidth: "80px" }}>
          <SelectControl
            label={__("Unit", "zenblocks")}
            value={currentUnit}
            options={lineHeightUnitOptions}
            onChange={(value) => {
              setAttributes({
                [unitAttr]: value,
              });
            }}
          />
        </div>
      </div>
    </div>
  );
};

// マージンコントロールコンポーネント
const MarginControl = ({ label, attributes, setAttributes, marginType, device }) => {
  const isPC = device === "pc";
  const unitSuffix = isPC ? "PC" : "SP";
  const currentSpacingUnit = attributes[`spacingUnit${unitSuffix}`] || (isPC ? "px" : "vw");

  let marginAttr;
  if (marginType === "captionToTitle") {
    marginAttr = `captionToTitleSpacing${unitSuffix}`;
  } else if (marginType === "titleToDescription") {
    marginAttr = `titleToDescriptionSpacing${unitSuffix}`;
  } else if (marginType === "description") {
    marginAttr = `descriptionMargin${unitSuffix}`;
  }

  const spacingUnitOptions = [
    { label: "px", value: "px" },
    { label: "em", value: "em" },
    { label: "rem", value: "rem" },
    { label: "%", value: "%" },
    { label: "vw", value: "vw" },
  ];

  return (
    <div className="margin-control" style={{ marginTop: "16px" }}>
      <div style={{ display: "flex", alignItems: "flex-end", gap: "8px" }}>
        <div style={{ flex: 1 }}>
          <TextControl
            label={label}
            value={attributes[marginAttr] || ""}
            onChange={(value) => {
              setAttributes({
                [marginAttr]: value,
              });
            }}
          />
        </div>
        <div style={{ minWidth: "80px" }}>
          <SelectControl
            label={__("Unit", "zenblocks")}
            value={currentSpacingUnit}
            options={spacingUnitOptions}
            onChange={(value) => {
              setAttributes({
                [`spacingUnit${unitSuffix}`]: value,
              });
            }}
          />
        </div>
      </div>
    </div>
  );
};

// カラーコントロールコンポーネント
const ColorControl = ({ label, colorValue, onColorChange }) => {
  return (
    <div className="color-control" style={{ marginTop: "16px" }}>
      <label style={{ display: "block", marginBottom: "8px", fontSize: "13px", fontWeight: "500" }}>{label}</label>
      <ColorPalette value={colorValue} onChange={onColorChange} disableCustomColors={false} clearable={false} />
    </div>
  );
};

// テキストシャドウコントロールコンポーネント
const TextShadowControl = ({ label, attributes, setAttributes, type }) => {
  const enabledAttr = `${type}TextShadowEnabled`;
  const offsetXAttr = `${type}TextShadowOffsetX`;
  const offsetYAttr = `${type}TextShadowOffsetY`;
  const blurAttr = `${type}TextShadowBlur`;
  const colorAttr = `${type}TextShadowColor`;

  const isEnabled = attributes[enabledAttr] || false;
  const offsetX = attributes[offsetXAttr] || "0";
  const offsetY = attributes[offsetYAttr] || "0";
  const blur = attributes[blurAttr] || "1";
  const color = attributes[colorAttr] || "#000000";

  return (
    <div className="text-shadow-control" style={{ marginTop: "16px" }}>
      <ToggleControl
        label={label}
        checked={isEnabled}
        onChange={(value) => {
          setAttributes({
            [enabledAttr]: value,
          });
        }}
      />

      {isEnabled && (
        <div style={{ marginTop: "12px", paddingLeft: "16px" }}>
          <div style={{ display: "flex", alignItems: "flex-end", gap: "8px", marginBottom: "12px" }}>
            <div style={{ flex: 1 }}>
              <TextControl
                label={__("Horizontal", "zenblocks")}
                value={offsetX}
                onChange={(value) => {
                  setAttributes({
                    [offsetXAttr]: value,
                  });
                }}
              />
            </div>
            <div style={{ flex: 1 }}>
              <TextControl
                label={__("Vertical", "zenblocks")}
                value={offsetY}
                onChange={(value) => {
                  setAttributes({
                    [offsetYAttr]: value,
                  });
                }}
              />
            </div>
            <div style={{ flex: 1 }}>
              <TextControl
                label={__("Blur", "zenblocks")}
                value={blur}
                onChange={(value) => {
                  setAttributes({
                    [blurAttr]: value,
                  });
                }}
              />
            </div>
          </div>

          <div>
            <label style={{ display: "block", marginBottom: "8px", fontSize: "13px", fontWeight: "500" }}>
              {__("Shadow Color", "zenblocks")}
            </label>
            <ColorPalette
              value={color}
              onChange={(value) => {
                setAttributes({
                  [colorAttr]: value || "#000000",
                });
              }}
              disableCustomColors={false}
              clearable={false}
            />
          </div>
        </div>
      )}
    </div>
  );
};

// フォントファミリーコントロールコンポーネント
const FontFamilyControl = ({ label, value, options, onChange }) => {
  return (
    <div className="font-family-control" style={{ marginTop: "16px" }}>
      <SelectControl
        label={label}
        value={value}
        options={options}
        onChange={onChange}
      />
    </div>
  );
};

export default TextBasic;
