import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import {
  BaseControl,
  ColorPalette,
  PanelBody,
  RangeControl,
  SelectControl,
  TabPanel,
  TextControl,
  ToggleControl,
  __experimentalNumberControl as NumberControl,
} from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';
import { __ } from '@wordpress/i18n';

import type { PriceBadgeAttributes } from './types';
import { getCurrencies } from '../../currencies';
import { CurrencyRichSelect, CurrencyMultiRichSelect } from '../shared/CurrencyRichSelect';
import { SourceCurrencyNotice } from '../shared/SourceCurrencyNotice';
import {
  DEFAULT_ACCENT_THEME_KEY,
  THEME_SWATCHES,
  THEME_KEY_BY_COLOR,
} from '../shared/accentThemes';
import '../shared/editorGlobals';
import {
  normalizeAmountInput,
  useAvailableCodes,
  resolveSelectedTheme,
  resolveSourceLabel,
  parseSourceValue,
} from '../shared/editorUtils';

type EditProps = {
  attributes: PriceBadgeAttributes;
  setAttributes: (next: Partial<PriceBadgeAttributes>) => void;
};

const currencies = getCurrencies();

export const PriceBadgeEdit = ({ attributes, setAttributes }: EditProps) => {
  const blockProps = useBlockProps();
  const availableCodes = useAvailableCodes(attributes.sourceId, attributes.deal);
  const resolvedSourceLabel = resolveSourceLabel(attributes.sourceId, attributes.deal);
  const selectedTheme = resolveSelectedTheme(attributes.accentTheme);
  /* ── Source options from localized data ── */
  const sourceOptions = (window.crtodaySourceOptions ?? []).map((opt) => ({
    label: opt.label,
    value: opt.id,
  }));

  const currentSourceValue = `${attributes.sourceId}:${attributes.deal}`;

  const handleSourceChange = (compound: string) => {
    const { sourceId, deal } = parseSourceValue(compound);
    setAttributes({ sourceId, deal });
  };

  /* ── Inspector tabs ── */
  const tabs = [
    { name: 'settings', title: __('Settings', 'currencyrate-today-currency-blocks') },
    { name: 'display', title: __('Display', 'currencyrate-today-currency-blocks') },
    { name: 'style', title: __('Style', 'currencyrate-today-currency-blocks') },
  ];

  return (
    <div {...blockProps}>
      <InspectorControls>
        <TabPanel tabs={tabs}>
          {(tab) => {
            if (tab.name === 'settings') {
              return (
                <>
                  <PanelBody title={__('Data source', 'currencyrate-today-currency-blocks')}>
                    {sourceOptions.length > 0 && (
                      <SelectControl __next40pxDefaultSize={true} 
                        label={__('Source', 'currencyrate-today-currency-blocks')}
                        help={__('For daily mid-market rates, use CurrencyRate (default).', 'currencyrate-today-currency-blocks')}
                        value={currentSourceValue}
                        options={sourceOptions}
                        onChange={handleSourceChange}
                      />
                    )}
                  </PanelBody>
                  <PanelBody title={__('Currency', 'currencyrate-today-currency-blocks')}>
                    <SourceCurrencyNotice
                      availableCodes={availableCodes}
                      selectedCodes={[attributes.primaryCurrency, ...attributes.targetCurrencies]}
                    />
                    <CurrencyRichSelect
                      label={__('Primary currency', 'currencyrate-today-currency-blocks')}
                      value={attributes.primaryCurrency}
                      currencies={currencies}
                      onChange={(primaryCurrency) => setAttributes({ primaryCurrency })}
                      availableCodes={availableCodes}
                    />
                    <NumberControl __next40pxDefaultSize={true} 
                      label={__('Price', 'currencyrate-today-currency-blocks')}
                      value={attributes.primaryPrice}
                      onChange={(val) => {
                        if (val !== undefined) {
                          setAttributes({ primaryPrice: normalizeAmountInput(val) });
                        }
                      }}
                      min={0}
                    />
                    <CurrencyMultiRichSelect
                      label={__('Target currencies', 'currencyrate-today-currency-blocks')}
                      values={attributes.targetCurrencies}
                      currencies={currencies}
                      onChange={(targetCurrencies) => setAttributes({ targetCurrencies })}
                      availableCodes={availableCodes}
                    />
                    <NumberControl __next40pxDefaultSize={true} 
                      label={__('Adjustment %', 'currencyrate-today-currency-blocks')}
                      help={__('Mark-up or mark-down rates by percentage', 'currencyrate-today-currency-blocks')}
                      value={String(attributes.adjustmentPercent)}
                      onChange={(val) => {
                        if (val !== undefined) {
                          setAttributes({ adjustmentPercent: Number(val) || 0 });
                        }
                      }}
                      min={-100}
                      max={100}
                      step={0.1}
                    />
                  </PanelBody>
                </>
              );
            }

            if (tab.name === 'display') {
              return (
                <PanelBody>
                  <NumberControl __next40pxDefaultSize={true} 
                    label={__('Decimal places', 'currencyrate-today-currency-blocks')}
                    value={String(attributes.decimals)}
                    onChange={(val) => {
                      if (val !== undefined) {
                        setAttributes({ decimals: Math.max(0, Math.min(8, Number(val) || 0)) });
                      }
                    }}
                    min={0}
                    max={8}
                  />
                  <ToggleControl 
                    label={__('Transparent', 'currencyrate-today-currency-blocks')}
                    help={__('Remove background, border, shadow and theme — use this when placing inside a custom container', 'currencyrate-today-currency-blocks')}
                    checked={attributes.seamless}
                    onChange={(seamless) => setAttributes({ seamless })}
                  />
                  <ToggleControl 
                    label={__('Show flags', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showFlags}
                    onChange={(showFlags) => setAttributes({ showFlags })}
                  />
                  <ToggleControl 
                    label={__('Always expanded', 'currencyrate-today-currency-blocks')}
                    help={__('When off, visitors click to reveal converted prices', 'currencyrate-today-currency-blocks')}
                    checked={attributes.alwaysExpanded}
                    onChange={(alwaysExpanded) => setAttributes({ alwaysExpanded })}
                  />
                  <ToggleControl 
                    label={__('Full width', 'currencyrate-today-currency-blocks')}
                    help={__('Stretch badge and dropdown to fill the container width', 'currencyrate-today-currency-blocks')}
                    checked={attributes.fullWidth}
                    onChange={(fullWidth) => setAttributes({ fullWidth })}
                  />
                  <ToggleControl 
                    label={__('Compact mode', 'currencyrate-today-currency-blocks')}
                    help={__('Smaller badge for inline use; turn off for a larger card-style layout', 'currencyrate-today-currency-blocks')}
                    checked={attributes.compactMode}
                    onChange={(compactMode) => setAttributes({ compactMode })}
                  />
                  <ToggleControl 
                    label={__('Show currency symbols', 'currencyrate-today-currency-blocks')}
                    help={__('Show $, €, ¥ etc. next to currency codes', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showCurrencySymbols}
                    onChange={(showCurrencySymbols) => setAttributes({ showCurrencySymbols })}
                  />
                  <ToggleControl 
                    label={__('Show timestamp', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showTimestamp}
                    onChange={(showTimestamp) => setAttributes({ showTimestamp })}
                  />
                  <TextControl __next40pxDefaultSize={true} 
                    label={__('Source label', 'currencyrate-today-currency-blocks')}
                    help={__('Custom label shown on the widget. Leave empty to use the source name.', 'currencyrate-today-currency-blocks')}
                    value={attributes.sourceLabel}
                    placeholder={resolvedSourceLabel}
                    maxLength={20}
                    onChange={(sourceLabel) => setAttributes({ sourceLabel })}
                  />
                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Theme', 'currencyrate-today-currency-blocks')}
                    value={attributes.theme}
                    disabled={attributes.seamless}
                    options={[
                      { label: __('Light', 'currencyrate-today-currency-blocks'), value: 'light' },
                      { label: __('Dark', 'currencyrate-today-currency-blocks'), value: 'dark' },
                      { label: __('Auto', 'currencyrate-today-currency-blocks'), value: 'auto' },
                    ]}
                    onChange={(theme) => setAttributes({ theme: theme as PriceBadgeAttributes['theme'] })}
                  />
                  <ToggleControl 
                    label={__('Enable shadow', 'currencyrate-today-currency-blocks')}
                    checked={attributes.shadow}
                    disabled={attributes.seamless}
                    onChange={(shadow) => setAttributes({ shadow })}
                  />
                </PanelBody>
              );
            }

            /* style tab */
            return (
              <>
                <PanelBody title={__('Shape', 'currencyrate-today-currency-blocks')}>
                  <RangeControl __next40pxDefaultSize={true} 
                    label={__('Corner radius', 'currencyrate-today-currency-blocks')}
                    value={attributes.radius}
                    min={0}
                    max={32}
                    disabled={attributes.seamless}
                    onChange={(radius) => setAttributes({ radius: Number(radius) })}
                  />
                </PanelBody>
                {!attributes.seamless && (
                <PanelBody title={__('Accent', 'currencyrate-today-currency-blocks')} initialOpen={false}>
                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Accent display', 'currencyrate-today-currency-blocks')}
                    value={attributes.accentMode}
                    options={[
                      { label: __('Top stripe', 'currencyrate-today-currency-blocks'), value: 'stripe' },
                      { label: __('Solid color border', 'currencyrate-today-currency-blocks'), value: 'color-border' },
                      { label: __('None', 'currencyrate-today-currency-blocks'), value: 'none' },
                    ]}
                    onChange={(accentMode) =>
                      setAttributes({ accentMode: accentMode as PriceBadgeAttributes['accentMode'] })
                    }
                  />
                  <BaseControl 
                    label={__('Theme preset', 'currencyrate-today-currency-blocks')}
                    help={selectedTheme.name}
                  >
                    <ColorPalette
                      colors={THEME_SWATCHES}
                      value={selectedTheme.light.primary}
                      onChange={(hex) => {
                        if (hex) {
                          const key = THEME_KEY_BY_COLOR[hex.toLowerCase()] ?? DEFAULT_ACCENT_THEME_KEY;
                          setAttributes({ accentTheme: key });
                        }
                      }}
                      clearable={false}
                      disableCustomColors
                    />
                  </BaseControl>
                </PanelBody>
                )}
              </>
            );
          }}
        </TabPanel>
      </InspectorControls>
      <ServerSideRender
        block="crtoday/price-badge"
        attributes={attributes}
      />
    </div>
  );
};
