import React from 'react';
import { __ } from '@wordpress/i18n';
import { PanelBody, RangeControl, ToggleControl, SelectControl } from '@wordpress/components';
import ResponsiveControl from '../../ResponsiveControl';
import { useResponsiveTab } from '../../ResponsiveTabContext';

const StylingRadiusSetting = ({ attributes, setAttributes, title, initialOpen = false }) => {
  const { activeTab } = useResponsiveTab();

  const handleRadiusChange = (value, position = '') => {
    const attributeName = position ? `stylingRadius${position}${activeTab.toUpperCase()}` : `stylingRadius${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: value });
  };

  const handleUnitChange = (unit, position = '') => {
    const attributeName = position ? `stylingRadiusUnit${position}${activeTab.toUpperCase()}` : `stylingRadiusUnit${activeTab.toUpperCase()}`;
    setAttributes({ [attributeName]: unit });
  };

  const getUnit = (position = '') => {
    const attributeName = position ? `stylingRadiusUnit${position}${activeTab.toUpperCase()}` : `stylingRadiusUnit${activeTab.toUpperCase()}`;
    return attributes[attributeName] || 'px';
  };

  const renderRadiusControls = (tabName) => {
    const positions = ['TopLeft', 'TopRight', 'BottomRight', 'BottomLeft'];
    const useIndividualAttr = `stylingRadiusUseIndividual${tabName.toUpperCase()}`;
    const useIndividual = attributes[useIndividualAttr];

    return (
      <>
        <ToggleControl
          label={__(`Use individual border radius settings`, 'zenblocks')}
          checked={useIndividual}
          onChange={(value) => {
            setAttributes({ [useIndividualAttr]: value });
            if (value) {
              // 個別設定に切り替えた時、一括指定の値を個別の値に反映
              const bulkValue = attributes[`stylingRadius${tabName.toUpperCase()}`] || 0;
              const bulkUnit = getUnit();
              positions.forEach((pos) => {
                handleRadiusChange(bulkValue, pos);
                handleUnitChange(bulkUnit, pos);
              });
            } else {
              // 一括設定に戻す時、左上の値を一括指定の値として使用
              const topLeftValue = attributes[`stylingRadiusTopLeft${tabName.toUpperCase()}`] || 0;
              handleRadiusChange(topLeftValue);
            }
          }}
        />
        {useIndividual ? (
          positions.map((pos) => {
            const currentUnit = getUnit(pos);
            const maxValue = currentUnit === '%' ? 50 : 500;
            const stepValue = currentUnit === '%' ? 0.1 : 1;
            
            return (
              <div key={pos} className="styling-radius-control">
                <div className="styling-radius-label">
                  {__(`Border Radius ${pos} ${tabName.toUpperCase()}`, 'zenblocks')}
                </div>
                <div className="styling-radius-controls">
                  <RangeControl
                    value={attributes[`stylingRadius${pos}${tabName.toUpperCase()}`] || 0}
                    onChange={(value) => handleRadiusChange(value, pos)}
                    min={0}
                    max={maxValue}
                    step={stepValue}
                    withInputField={true}
                  />
                  <SelectControl
                    value={currentUnit}
                    options={[
                      { label: 'px', value: 'px' },
                      { label: '%', value: '%' },
                    ]}
                    onChange={(unit) => handleUnitChange(unit, pos)}
                    className="unit-select"
                  />
                </div>
              </div>
            );
          })
        ) : (
          <div className="styling-radius-control">
            <div className="styling-radius-label">
              {__(`Border Radius ${tabName.toUpperCase()}`, 'zenblocks')}
            </div>
            <div className="styling-radius-controls">
              <RangeControl
                value={attributes[`stylingRadius${tabName.toUpperCase()}`] || 0}
                onChange={(value) => handleRadiusChange(value)}
                min={0}
                max={getUnit() === '%' ? 50 : 500}
                step={getUnit() === '%' ? 0.1 : 1}
                withInputField={true}
              />
              <SelectControl
                value={getUnit()}
                options={[
                  { label: 'px', value: 'px' },
                  { label: '%', value: '%' },
                ]}
                onChange={(unit) => handleUnitChange(unit)}
                className="unit-select"
              />
            </div>
          </div>
        )}

        {/* CSS styles for proper layout */}
        <style>
          {`
          .styling-radius-control
          .components-base-control{
            padding-top: 0 !important;
            margin-bottom: 0.5em !important;
          }

          .styling-radius-control
          .components-base-control
          .components-base-control{
            padding-left: 0 !important;
            padding-right: 0 !important;
          }

          .styling-radius-label {
            margin-bottom: 8px;
            font-size: 11px;
            font-weight: 500;
            text-transform: uppercase;
            color: #1e1e1e;
          }

          .styling-radius-controls {
            display: flex;
            align-items: flex-start;
            gap: 8px;
          }

          .styling-radius-controls .components-range-control {
            flex: 1;
            margin-bottom: 0;
          }

          .styling-radius-controls .components-range-control .components-base-control__field {
            margin-bottom: 0;
          }

          .styling-radius-controls .unit-select {
            flex: 0 0 70px;
            margin-bottom: 0;
          }

          .styling-radius-controls .unit-select .components-base-control__field {
            margin-bottom: 0;
          }
          `}
        </style>
      </>
    );
  };

  return (
    <PanelBody title={title} initialOpen={initialOpen}>
      <ResponsiveControl initialOpen={true}>{(tabName) => renderRadiusControls(tabName)}</ResponsiveControl>
    </PanelBody>
  );
};

export default StylingRadiusSetting;
