import { PanelBody, Button, SelectControl, ToggleControl, RangeControl, TextControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { MediaUpload, MediaUploadCheck } from "@wordpress/block-editor";
import { FocalPointPicker } from "@wordpress/components";
import ResponsiveControl from "../../ResponsiveControl";
import { useResponsiveTab } from "../../ResponsiveTabContext";
import { __experimentalUnitControl as UnitControl } from "@wordpress/components";

const ImageBasicSetting = ({ attributes, setAttributes, title, initialOpen = false }) => {
  // PC/SP同期設定の状態
  const syncImage = attributes.syncImage !== undefined ? attributes.syncImage : true;
  const { activeTab } = useResponsiveTab();

  const handleImageChange = (image) => {
    // imageIdとsizeSlugが属性に存在するかチェック
    const hasImageIdAttr = attributes.hasOwnProperty('imageId');
    const hasSizeSlugAttr = attributes.hasOwnProperty('sizeSlug');
    
    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      const updates = {
        imageUrl: image.url,
        imageUrlSP: image.url,
        altText: image.alt || "",
      };
      
      // imageId属性が存在する場合のみ設定
      if (hasImageIdAttr) {
        updates.imageId = image.id || null;
      }
      
      // sizeSlug属性が存在する場合のみ設定
      if (hasSizeSlugAttr) {
        updates.sizeSlug = 'large';
      }
      
      setAttributes(updates);
    } else if (activeTab === "sp") {
      // SP設定の場合
      const updates = {
        imageUrlSP: image.url,
        altText: image.alt || ""
      };
      
      // imageId属性が存在する場合のみ設定（SP設定でも同じimageIdを使用）
      if (hasImageIdAttr) {
        updates.imageId = image.id || null;
      }
      
      setAttributes(updates);
    } else {
      // PC設定（非同期モード）
      const updates = {
        imageUrl: image.url,
        altText: image.alt || "",
      };
      
      // imageId属性が存在する場合のみ設定
      if (hasImageIdAttr) {
        updates.imageId = image.id || null;
      }
      
      // sizeSlug属性が存在する場合のみ設定
      if (hasSizeSlugAttr) {
        updates.sizeSlug = 'large';
      }
      
      setAttributes(updates);
    }
  };

  const handleObjectPositionChange = (focalPoint) => {
    const { x, y } = focalPoint;
    const position = `${x * 100}% ${y * 100}%`;

    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        imageObjectPositionPC: position,
        imageObjectPositionSP: position,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`imageObjectPosition${activeTab.toUpperCase()}`]: position });
    }
  };

  const handleObjectFitChange = (value) => {
    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        imageObjectFitPC: value,
        imageObjectFitSP: value,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`imageObjectFit${activeTab.toUpperCase()}`]: value });
    }
  };

  const handleWidthChange = (value, unit) => {
    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      if (value !== undefined) {
        setAttributes({
          imageWidthPC: value.toString(),
          imageWidthSP: value.toString(),
        });
      }
      if (unit !== undefined) {
        setAttributes({
          imageWidthUnitPC: unit,
          imageWidthUnitSP: unit,
        });
      }
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      if (value !== undefined) {
        setAttributes({ [`imageWidth${activeTab.toUpperCase()}`]: value.toString() });
      }
      if (unit !== undefined) {
        setAttributes({ [`imageWidthUnit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };

  const handleHeightChange = (value, unit) => {
    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      if (value !== undefined) {
        setAttributes({
          imageHeightPC: value.toString(),
          imageHeightSP: value.toString(),
        });
      }
      if (unit !== undefined) {
        setAttributes({
          imageHeightUnitPC: unit,
          imageHeightUnitSP: unit,
        });
      }
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      if (value !== undefined) {
        setAttributes({ [`imageHeight${activeTab.toUpperCase()}`]: value.toString() });
      }
      if (unit !== undefined) {
        setAttributes({ [`imageHeightUnit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };

  const handleAutoSizeToggle = (property) => {
    const currentValue = attributes[`imageAuto${property}${activeTab.toUpperCase()}`];

    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        [`imageAuto${property}PC`]: !currentValue,
        [`imageAuto${property}SP`]: !currentValue,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`imageAuto${property}${activeTab.toUpperCase()}`]: !currentValue });
    }
  };

  const handleContainerModeToggle = (value) => {
    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      setAttributes({
        imageContainerModePC: value,
        imageContainerModeSP: value,
      });
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      setAttributes({ [`imageContainerMode${activeTab.toUpperCase()}`]: value });
    }
  };

  const handleContainerSizeChange = (property, value, unit) => {
    if (syncImage && activeTab === "pc") {
      // 同期モードで、PC設定の場合はSP設定も更新
      if (value !== undefined) {
        setAttributes({
          [`imageContainer${property}PC`]: value.toString(),
          [`imageContainer${property}SP`]: value.toString(),
        });
      }
      if (unit !== undefined) {
        setAttributes({
          [`imageContainer${property}UnitPC`]: unit,
          [`imageContainer${property}UnitSP`]: unit,
        });
      }
    } else {
      // 非同期モードまたはSP設定の場合は個別に更新
      if (value !== undefined) {
        setAttributes({ [`imageContainer${property}${activeTab.toUpperCase()}`]: value.toString() });
      }
      if (unit !== undefined) {
        setAttributes({ [`imageContainer${property}Unit${activeTab.toUpperCase()}`]: unit });
      }
    }
  };


  // 同期設定の切り替え
  const handleSyncToggle = (value) => {
    setAttributes({ syncImage: value });

    // 同期モードに切り替えた場合、SPの設定をPCの設定に合わせる
    if (value) {
      const syncAttrs = {};

      // ベース設定
      if (attributes.imageUrl) {
        syncAttrs.imageUrlSP = attributes.imageUrl;
      }
      if (attributes.imageObjectPositionPC) {
        syncAttrs.imageObjectPositionSP = attributes.imageObjectPositionPC;
      }
      if (attributes.imageObjectFitPC) {
        syncAttrs.imageObjectFitSP = attributes.imageObjectFitPC;
      }
      if (attributes.imageWidthPC) {
        syncAttrs.imageWidthSP = attributes.imageWidthPC;
      }
      if (attributes.imageHeightPC) {
        syncAttrs.imageHeightSP = attributes.imageHeightPC;
      }
      if (attributes.imageWidthUnitPC) {
        syncAttrs.imageWidthUnitSP = attributes.imageWidthUnitPC;
      }
      if (attributes.imageHeightUnitPC) {
        syncAttrs.imageHeightUnitSP = attributes.imageHeightUnitPC;
      }

      if (Object.keys(syncAttrs).length > 0) {
        setAttributes(syncAttrs);
      }
    }
  };

  const renderImageControls = () => {
    const imageUrl = activeTab === "sp" ? (attributes.imageUrlSP || attributes.imageUrl) : attributes.imageUrl;
    const objectPosition = attributes[`imageObjectPosition${activeTab.toUpperCase()}`] || "50% 50%";
    const objectFit = attributes[`imageObjectFit${activeTab.toUpperCase()}`] || "cover";
    const imageWidth = attributes[`imageWidth${activeTab.toUpperCase()}`] || "100";
    const imageHeight = attributes[`imageHeight${activeTab.toUpperCase()}`] || "auto";
    const imageWidthUnit = attributes[`imageWidthUnit${activeTab.toUpperCase()}`] || "%";
    const imageHeightUnit = attributes[`imageHeightUnit${activeTab.toUpperCase()}`] || "px";
    const isWidthAuto = attributes[`imageAutoWidth${activeTab.toUpperCase()}`];
    const isHeightAuto = attributes[`imageAutoHeight${activeTab.toUpperCase()}`] !== false; // デフォルトtrue
    
    // コンテナモード設定
    const isContainerMode = attributes[`imageContainerMode${activeTab.toUpperCase()}`] !== undefined ? attributes[`imageContainerMode${activeTab.toUpperCase()}`] : true;
    const containerWidth = attributes[`imageContainerWidth${activeTab.toUpperCase()}`] || "100";
    const containerHeight = attributes[`imageContainerHeight${activeTab.toUpperCase()}`] || "280";
    const containerWidthUnit = attributes[`imageContainerWidthUnit${activeTab.toUpperCase()}`] || "%";
    const containerHeightUnit = attributes[`imageContainerHeightUnit${activeTab.toUpperCase()}`] || "px";

    const [x, y] = objectPosition.split(" ").map((val) => parseFloat(val) / 100);

    const units = [
      { label: "px", value: "px" },
      { label: "%", value: "%" },
      { label: "vw", value: "vw" },
      { label: "vh", value: "vh" },
      { label: "auto", value: "auto" },
    ];

    return (
      <div className="image-basic-controls">
        <div className="button-container">
          <MediaUploadCheck>
            <MediaUpload
              onSelect={handleImageChange}
              allowedTypes={["image"]}
              value={imageUrl}
              render={({ open }) => (
                <Button onClick={open} isPrimary className="set-image-button">
                  {imageUrl ? __("Replace Image", "zenblocks") : __("Select Image", "zenblocks")}
                </Button>
              )}
            />
          </MediaUploadCheck>
          {imageUrl && (
            <Button isSecondary onClick={() => handleImageChange({ url: "", alt: "" })} className="remove-image-button">
              {__("Remove Image", "zenblocks")}
            </Button>
          )}
        </div>


        {imageUrl && (
          <div className="image-settings">
            <FocalPointPicker 
              url={imageUrl} 
              value={{ x, y }} 
              onChange={handleObjectPositionChange} 
              label={__("Image Position", "zenblocks")}
            />

            <ToggleControl
              label={__("Fixed Container Mode", "zenblocks")}
              help={__("Fixes container size to enable image position control", "zenblocks")}
              checked={isContainerMode}
              onChange={handleContainerModeToggle}
            />

            {isContainerMode && (
              <div className="container-size-controls">
                <h4>{__("Container Size", "zenblocks")}</h4>
                <div className="container-width-controls">
                  <UnitControl
                    label={__("Container Width", "zenblocks")}
                    value={`${containerWidth}${containerWidthUnit}`}
                    onChange={(value) => {
                      const numValue = parseFloat(value);
                      const unit = value.replace(/[\d.-]/g, "");
                      handleContainerSizeChange("Width", numValue, unit || containerWidthUnit);
                    }}
                    units={units}
                    min={0}
                  />
                </div>
                <div className="container-height-controls">
                  <UnitControl
                    label={__("Container Height", "zenblocks")}
                    value={`${containerHeight}${containerHeightUnit}`}
                    onChange={(value) => {
                      const numValue = parseFloat(value);
                      const unit = value.replace(/[\d.-]/g, "");
                      handleContainerSizeChange("Height", numValue, unit || containerHeightUnit);
                    }}
                    units={units}
                    min={0}
                  />
                </div>
              </div>
            )}

            {isContainerMode && (
              <SelectControl
                label={__("Object Fit", "zenblocks")}
                value={objectFit}
                options={[
                  { label: __("Cover", "zenblocks"), value: "cover" },
                  { label: __("Contain", "zenblocks"), value: "contain" },
                  { label: __("Fill", "zenblocks"), value: "fill" },
                  { label: __("Scale-down", "zenblocks"), value: "scale-down" },
                  { label: __("None", "zenblocks"), value: "none" },
                ]}
                onChange={handleObjectFitChange}
                className="object-fit-select"
              />
            )}

            {!isContainerMode && (
              <div className="size-controls">
                <h4>{__("Image Size", "zenblocks")}</h4>
                
                <div className="height-controls">
                  <ToggleControl 
                    label={__("Auto-adjust height", "zenblocks")} 
                    checked={isHeightAuto} 
                    onChange={() => handleAutoSizeToggle("Height")} 
                  />
                  {!isHeightAuto && (
                    <div className="unit-control-wrapper">
                      <UnitControl
                        label={__("Height", "zenblocks")}
                        value={`${imageHeight}${imageHeightUnit}`}
                        onChange={(value) => {
                          const numValue = parseFloat(value);
                          const unit = value.replace(/[\d.-]/g, "");
                          handleHeightChange(numValue, unit || imageHeightUnit);
                        }}
                        units={units}
                        min={0}
                      />
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <div style={{ paddingTop: "10px" }}>
        <ToggleControl
          label={__("PC/SP Sync Settings", "zenblocks")}
          checked={syncImage}
          onChange={handleSyncToggle}
        />
      </div>
      <ResponsiveControl initialOpen={true}>{renderImageControls}</ResponsiveControl>
      {syncImage && activeTab === "sp" && (
        <div style={{ padding: "10px", backgroundColor: "#f0f0f0", marginTop: "10px", borderRadius: "4px" }}>
          {__("In sync mode, PC settings are applied.", "zenblocks")}
        </div>
      )}
    </PanelBody>
  );
};

export default ImageBasicSetting;