import { __ } from '@wordpress/i18n';
import { Button, Dropdown, ColorPicker } from '@wordpress/components';
import { link, linkOff, rotateRight } from '@wordpress/icons';
import { getInheritedResponsiveValue, getResponsivePlaceholder } from '../../controls/responsiveValueUtils';
import ResponsiveInheritedNotice from '../../controls/ResponsiveInheritedNotice';
import UnitValueControl from '../../controls/UnitValueControl';

export default function Border({ activeDevice, border, setAttributes }) {
  const deviceVal = border[activeDevice] || { width: '', style: '', color: '', sides: {}, isLinkActive: true };
  const inheritedBorder = getInheritedResponsiveValue(border, activeDevice) || {};

  const updateDeviceAttribute = (value) => {
    setAttributes({
      border: {
        ...border,
        [activeDevice]: value,
      },
    });
  };

  const borderStyleOptions = [
    { label: __('None', 'axcelersblocks'), value: '' },
    { label: __('Solid', 'axcelersblocks'), value: 'solid' },
    { label: __('Dashed', 'axcelersblocks'), value: 'dashed' },
    { label: __('Dotted', 'axcelersblocks'), value: 'dotted' },
    { label: __('Double', 'axcelersblocks'), value: 'double' },
  ];
  const sides = ['top', 'right', 'bottom', 'left'];

  const reset = () => updateDeviceAttribute({ width: '', style: '', color: '', sides: {}, isLinkActive: true });
  const toggleLink = () => updateDeviceAttribute({ ...deviceVal, isLinkActive: !deviceVal.isLinkActive });
  const updateLinked = (patch) => updateDeviceAttribute({ ...deviceVal, ...patch });
  const updateSide = (side, key, value) => {
    const nextSides = { ...(deviceVal.sides || {}), [side]: { ...(deviceVal.sides?.[side] || {}), [key]: value } };
    updateDeviceAttribute({ ...deviceVal, sides: nextSides });
  };
  const getInheritedSideValue = (side, key) =>
    deviceVal.sides?.[side]?.[key] ||
    deviceVal[key] ||
    inheritedBorder.sides?.[side]?.[key] ||
    inheritedBorder[key] ||
    '';
  const getSideResponsiveValue = (side, key) => (value) =>
    value?.sides?.[side]?.[key] || value?.[key] || '';

  const renderBorderStyleOptions = (onSelect, onClose) => (
    <div className="border-style-options">
      {borderStyleOptions.map((opt) => (
        <Button key={opt.value} variant="secondary" onClick={() => { onSelect(opt.value); onClose(); }} style={{ textAlign: 'left' }}>
          {opt.label}
        </Button>
      ))}
    </div>
  );

  return (
    <div className="border-control">
      <div className="border-control-header">
        <h3>{__('Border', 'axcelersblocks')}</h3>
        <div>
          <Button
            icon={deviceVal.isLinkActive ? link : linkOff}
            onClick={toggleLink}
            label={deviceVal.isLinkActive ? __('Unlink Sides', 'axcelersblocks') : __('Link Sides', 'axcelersblocks')}
          />
          <Button icon={rotateRight} onClick={reset} label={__('Reset', 'axcelersblocks')} showTooltip />
        </div>
      </div>

      {deviceVal.isLinkActive ? (
				<>
					<div className="border-control-linked">
						<UnitValueControl
							label={__('All Side', 'axcelersblocks')}
							value={deviceVal.width || ''}
							onChange={(value) => updateLinked({ width: value })}
							placeholder={getResponsivePlaceholder({
								values: border,
								activeDevice,
								selector: (value) => value?.width || '',
								fallback: 'e.g., 1px',
							})}
							preset="borderWidth"
						/>
						<Dropdown
							className="border-style"
							position="bottom right"
							renderToggle={({ isOpen, onToggle }) => (
								<Button variant="secondary" onClick={onToggle} aria-expanded={isOpen}>
									{deviceVal.style || inheritedBorder.style || __('Select Style', 'axcelersblocks')}
								</Button>
							)}
							renderContent={({ onClose }) =>
								renderBorderStyleOptions((val) => updateLinked({ style: val }), onClose)
							}
						/>
						<Dropdown
							className="border-color"
							position="bottom right"
							renderToggle={({ isOpen, onToggle }) => (
								<Button variant="secondary" onClick={onToggle} aria-expanded={isOpen}>
									<span style={{ backgroundColor: deviceVal.color || 'transparent' }} />
								</Button>
							)}
							renderContent={() => (
								<ColorPicker
									color={deviceVal.color || '#000000'}
									onChangeComplete={(color) => updateLinked({ color: color.hex })}
								/>
							)}
						/>
					</div>
					<ResponsiveInheritedNotice
						values={ border }
						activeDevice={ activeDevice }
						selector={( value ) => value?.style || ''}
						options={ borderStyleOptions }
					/>
					<ResponsiveInheritedNotice
						values={ border }
						activeDevice={ activeDevice }
						selector={( value ) => value?.color || ''}
					/>
				</>
      ) : (
				<div className="border-control-unlinked">
					{sides.map((side) => (
						<div key={side}>
							<div className="border-side-control">
								<UnitValueControl
                label={__(`${side.charAt(0).toUpperCase() + side.slice(1)}`, 'axcelersblocks')}
                value={deviceVal.sides?.[side]?.width || ''}
                onChange={(value) => updateSide(side, 'width', value)}
                placeholder={getResponsivePlaceholder({
                  values: border,
                  activeDevice,
                  selector: getSideResponsiveValue(side, 'width'),
                  fallback: 'e.g., 1px',
                })}
								preset="borderWidth"
              />
              <Dropdown
                className="border-style"
                position="bottom right"
                renderToggle={({ isOpen, onToggle }) => (
                  <Button variant="secondary" onClick={onToggle} aria-expanded={isOpen}>
                    {getInheritedSideValue(side, 'style') || __('Select Style', 'axcelersblocks')}
                  </Button>
                )}
                renderContent={({ onClose }) =>
                  renderBorderStyleOptions((val) => updateSide(side, 'style', val), onClose)
                }
              />
              <Dropdown
                className="border-color"
                position="bottom right"
                renderToggle={({ isOpen, onToggle }) => (
                  <Button variant="secondary" onClick={onToggle} aria-expanded={isOpen}>
                    <span style={{ backgroundColor: getInheritedSideValue(side, 'color') || 'transparent' }} />
                  </Button>
                )}
                renderContent={() => (
                  <ColorPicker
                    color={getInheritedSideValue(side, 'color') || '#000000'}
                    onChangeComplete={(color) => updateSide(side, 'color', color.hex)}
                  />
                )}
              />
							</div>
							<ResponsiveInheritedNotice
								values={ border }
								activeDevice={ activeDevice }
								selector={getSideResponsiveValue(side, 'style')}
								options={ borderStyleOptions }
							/>
							<ResponsiveInheritedNotice
								values={ border }
								activeDevice={ activeDevice }
								selector={getSideResponsiveValue(side, 'color')}
							/>
						</div>
					))}
				</div>
      )}
    </div>
  );
}
