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 Big from 'big.js';

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

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

const currencies = getCurrencies();

export const Edit = ({ attributes, setAttributes }: EditProps) => {
  const blockProps = useBlockProps();
  const editorUi = window.crtodayEditorCurrenciesUi ?? {};
  const editorLabels = editorUi.labels ?? {};
  const selectedTheme = resolveSelectedTheme(attributes.accentTheme);
  const availableCodes = useAvailableCodes(attributes.sourceId, attributes.deal);
  const resolvedSourceLabel = resolveSourceLabel(attributes.sourceId, attributes.deal);

  return (
    <div {...blockProps}>
      <InspectorControls>
        <TabPanel
          tabs={[
            { name: 'settings', title: __('Settings', 'currencyrate-today-currency-blocks') },
            { name: 'display', title: __('Display', 'currencyrate-today-currency-blocks') },
            { name: 'button', title: __('Button', 'currencyrate-today-currency-blocks') }
          ]}
        >
          {(tab) =>
            tab.name === 'settings' ? (
              <>
                <PanelBody title={__('Data settings', 'currencyrate-today-currency-blocks')} initialOpen>
                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Data source', 'currencyrate-today-currency-blocks')}
                    help={__('For daily mid-market rates, use CurrencyRate (default).', 'currencyrate-today-currency-blocks')}
                    value={`${attributes.sourceId}:${attributes.deal}`}
                    options={buildSourceOptions(editorLabels)}
                    onChange={(value) => {
                      if (!value) return;
                      const { sourceId, deal } = parseSourceValue(value);
                      setAttributes({ sourceId, deal });
                    }}
                  />

                  <SourceCurrencyNotice
                    availableCodes={availableCodes}
                    selectedCodes={[attributes.base, ...attributes.symbols]}
                  />

                  <CurrencyRichSelect
                    label={__('Base currency', 'currencyrate-today-currency-blocks')}
                    value={attributes.base}
                    currencies={currencies}
                    onChange={(base) => setAttributes({ base })}
                    availableCodes={availableCodes}
                  />

                  <CurrencyMultiRichSelect
                    label={__('Target currencies', 'currencyrate-today-currency-blocks')}
                    values={attributes.symbols}
                    currencies={currencies}
                    onChange={(symbols) => setAttributes({ symbols })}
                    availableCodes={availableCodes}
                  />

                  <ToggleControl 
                    label={__('Invert rates', 'currencyrate-today-currency-blocks')}
                    help={
                      attributes.invertRates
                        ? __('Showing target → base direction', 'currencyrate-today-currency-blocks')
                        : __('Showing base → target direction', 'currencyrate-today-currency-blocks')
                    }
                    checked={attributes.invertRates}
                    onChange={(invertRates) => setAttributes({ invertRates })}
                  />

                  <NumberControl __next40pxDefaultSize={true} 
                    label={__('Amount', 'currencyrate-today-currency-blocks')}
                    help={__('Multiply rates by this amount', 'currencyrate-today-currency-blocks')}
                    value={attributes.amount}
                    min={0.01}
                    max={999999999}
                    step={0.01}
                    onChange={(value) => {
                      const normalized = normalizeAmountInput(String(value ?? ''));

                      if (normalized === '') {
                        return;
                      }

                      try {
                        const parsed = new Big(normalized);
                        if (parsed.gt(0)) {
                          setAttributes({ amount: parsed.toString() });
                        }
                      } catch {
                        return;
                      }
                    }}
                  />

                  <NumberControl __next40pxDefaultSize={true} 
                    label={__('Adjustment (%)', 'currencyrate-today-currency-blocks')}
                    help={__('Applies percentage to the final displayed values. Supports minus and plus.', 'currencyrate-today-currency-blocks')}
                    value={String(attributes.adjustmentPercent ?? 0)}
                    min={-100}
                    max={100}
                    step={0.05}
                    onChange={(value) => {
                      const parsed = Number(value ?? 0);
                      if (Number.isFinite(parsed)) {
                        setAttributes({ adjustmentPercent: parsed });
                      }
                    }}
                  />
                </PanelBody>
              </>
            ) : tab.name === 'button' ? (
              <>
                <PanelBody title={__('Row button', 'currencyrate-today-currency-blocks')} initialOpen>
                  <ToggleControl 
                    label={__('Add button to each row', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showCtaButton}
                    onChange={(showCtaButton) => setAttributes({ showCtaButton })}
                  />

                  <TextControl __next40pxDefaultSize={true} 
                    label={__('Button text', 'currencyrate-today-currency-blocks')}
                    value={attributes.ctaButtonText}
                    maxLength={40}
                    disabled={!attributes.showCtaButton}
                    onChange={(ctaButtonText) => setAttributes({ ctaButtonText })}
                  />

                  <TextControl __next40pxDefaultSize={true} 
                    label={__('URL template', 'currencyrate-today-currency-blocks')}
                    value={attributes.ctaUrlTemplate}
                    disabled={!attributes.showCtaButton}
                    placeholder={editorLabels.exchangeUrlPlaceholder ?? ''}
                    help={__(
                      'Use placeholders: {amount}, {from}, {to}, {result}, {bid}, {ask}.',
                      'currencyrate-today-currency-blocks'
                    )}
                    onChange={(ctaUrlTemplate) => setAttributes({ ctaUrlTemplate })}
                  />
                </PanelBody>
              </>
            ) : (
              <>
                <PanelBody title={__('Presentation', 'currencyrate-today-currency-blocks')} initialOpen>
                  <RangeControl __next40pxDefaultSize={true} 
                    label={__('Decimals', 'currencyrate-today-currency-blocks')}
                    value={attributes.decimals}
                    min={0}
                    max={8}
                    onChange={(decimals) => setAttributes({ decimals: Number(decimals) })}
                  />

                  <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 })}
                  />

                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Theme', 'currencyrate-today-currency-blocks')}
                    value={attributes.theme}
                    disabled={attributes.seamless}
                    options={[
                      { label: __('Auto', 'currencyrate-today-currency-blocks'), value: 'auto' },
                      { label: __('Light', 'currencyrate-today-currency-blocks'), value: 'light' },
                      { label: __('Dark', 'currencyrate-today-currency-blocks'), value: 'dark' }
                    ]}
                    onChange={(theme) => setAttributes({ theme: theme as FxAttributes['theme'] })}
                  />

                  <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) })}
                  />

                  <ToggleControl
                    label={__('Enable shadow', 'currencyrate-today-currency-blocks')}
                    checked={attributes.shadow}
                    disabled={attributes.seamless}
                    onChange={(shadow) => setAttributes({ shadow })}
                  />

                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Currency labels', 'currencyrate-today-currency-blocks')}
                    value={attributes.currencyLabelMode}
                    options={[
                      { label: __('Code', 'currencyrate-today-currency-blocks'), value: 'code' },
                      { label: __('Name', 'currencyrate-today-currency-blocks'), value: 'name' }
                    ]}
                    onChange={(currencyLabelMode) =>
                      setAttributes({ currencyLabelMode: currencyLabelMode as FxAttributes['currencyLabelMode'] })
                    }
                  />

                  <ToggleControl 
                    label={__('Show currency symbols', 'currencyrate-today-currency-blocks')}
                    help={__('Show currency symbols like $, €, £ next to values', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showCurrencySymbols}
                    onChange={(showCurrencySymbols) => setAttributes({ showCurrencySymbols })}
                  />

                  <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 })}
                  />

                  <ToggleControl 
                    label={__('Show timestamp', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showTimestamp}
                    onChange={(showTimestamp) => setAttributes({ showTimestamp })}
                  />

                  <ToggleControl 
                    label={__('Show 24h change', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showChange}
                    onChange={(showChange) => setAttributes({ showChange })}
                  />

                  <ToggleControl 
                    label={__('Compact mode', 'currencyrate-today-currency-blocks')}
                    help={__('Smaller rows and tighter spacing', 'currencyrate-today-currency-blocks')}
                    checked={attributes.compactMode}
                    onChange={(compactMode) => setAttributes({ compactMode })}
                  />

                  <ToggleControl 
                    label={__('Show flags', 'currencyrate-today-currency-blocks')}
                    help={__('Show flags next to currencies', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showFlags}
                    onChange={(showFlags) => setAttributes({ showFlags })}
                  />

                  <ToggleControl 
                    label={__('Attribution', 'currencyrate-today-currency-blocks')}
                    help={__('Show optional credit link in the footer', 'currencyrate-today-currency-blocks')}
                    checked={attributes.attribution}
                    onChange={(attribution) => setAttributes({ attribution })}
                  />

                  <ToggleControl 
                    label={__('Full width', 'currencyrate-today-currency-blocks')}
                    help={
                      attributes.fullWidth
                        ? __('Stretches to fill width', 'currencyrate-today-currency-blocks')
                        : __('Shrinks to fit content', 'currencyrate-today-currency-blocks')
                    }
                    checked={attributes.fullWidth}
                    onChange={(fullWidth) => setAttributes({ fullWidth })}
                  />

                  <ToggleControl 
                    label={__('Search engine data', 'currencyrate-today-currency-blocks')}
                    help={__('Helps Google and other search engines understand and display your exchange rates.', 'currencyrate-today-currency-blocks')}
                    checked={attributes.enableStructuredData}
                    onChange={(enableStructuredData) => setAttributes({ enableStructuredData })}
                  />
                </PanelBody>
                {!attributes.seamless && (
                <PanelBody title={__('Style', '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 FxAttributes['accentMode'] })
                    }
                  />

                  <BaseControl 
                    label={__('Theme preset', 'currencyrate-today-currency-blocks')}
                    help={selectedTheme.name}
                  >
                    <ColorPalette
                      colors={THEME_SWATCHES}
                      value={selectedTheme.light.primary}
                      disableCustomColors
                      onChange={(color?: string) => {
                        if (!color) {
                          return;
                        }

                        const accentTheme = THEME_KEY_BY_COLOR[color.toLowerCase()];
                        if (accentTheme) {
                          setAttributes({ accentTheme });
                        }
                      }}
                    />
                  </BaseControl>

                  {attributes.accentMode === 'stripe' && (
                    <RangeControl __next40pxDefaultSize={true} 
                      label={__('Gradient angle', 'currencyrate-today-currency-blocks')}
                      value={attributes.accentAngle}
                      min={0}
                      max={360}
                      onChange={(accentAngle) =>
                        setAttributes({ accentAngle: Number(accentAngle ?? 135) })
                      }
                    />
                  )}
                </PanelBody>
                )}
              </>
            )
          }
        </TabPanel>
      </InspectorControls>

      <ServerSideRender block="crtoday/exchange-rates" attributes={attributes} />
    </div>
  );
};
