import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
import {
  Button,
  PanelBody,
  RangeControl,
  SelectControl,
  TabPanel,
  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 { TickerAttributes, TickerPair } from './types';
import { getCurrencies } from '../../currencies';
import { CurrencyRichSelect } from '../shared/CurrencyRichSelect';
import { SourceCurrencyNotice } from '../shared/SourceCurrencyNotice';
import '../shared/editorGlobals';
import {
  normalizeAmountInput,
  useAvailableCodes,
  buildSourceOptions,
  parseSourceValue,
} from '../shared/editorUtils';

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

const currencies = getCurrencies();

export const TickerEdit = ({ attributes, setAttributes }: EditProps) => {
  const blockProps = useBlockProps();
  const editorUi = window.crtodayEditorCurrenciesUi ?? {};
  const editorLabels = editorUi.labels ?? {};
  const availableCodes = useAvailableCodes(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: 'ticker', title: __('Ticker', '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 });
                    }}
                  />

                  <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.', '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>

                <PanelBody title={__('Currency pairs', 'currencyrate-today-currency-blocks')} initialOpen>
                  <SourceCurrencyNotice
                    availableCodes={availableCodes}
                    selectedCodes={attributes.pairs.flatMap((p: TickerPair) => [p.from, p.to])}
                  />
                  {attributes.pairs.map((pair: TickerPair, idx: number) => (
                    <div
                      key={idx}
                      style={{
                        position: 'relative',
                        border: '1px solid #e0e0e0',
                        borderRadius: '4px',
                        padding: '8px',
                        marginBottom: '8px',
                      }}
                    >
                      <Button
                        icon="no-alt"
                        isDestructive
                        size="small"
                        label={__('Remove pair', 'currencyrate-today-currency-blocks')}
                        style={{ position: 'absolute', top: '4px', right: '4px', zIndex: 1 }}
                        onClick={() => {
                          const next = attributes.pairs.filter((_: TickerPair, i: number) => i !== idx);
                          setAttributes({ pairs: next.length > 0 ? next : [{ from: 'EUR', to: 'USD' }] });
                        }}
                      />
                      <div style={{ display: 'flex', alignItems: 'flex-end', gap: '4px' }}>
                        <div style={{ flex: 1 }}>
                          <CurrencyRichSelect
                            label={__('From', 'currencyrate-today-currency-blocks')}
                            value={pair.from}
                            currencies={currencies}
                            compact
                            onChange={(from) => {
                              const next = [...attributes.pairs];
                              next[idx] = { ...next[idx], from };
                              setAttributes({ pairs: next });
                            }}
                            availableCodes={availableCodes}
                          />
                        </div>
                        <span style={{ padding: '6px 2px', fontWeight: 600 }}>/</span>
                        <div style={{ flex: 1 }}>
                          <CurrencyRichSelect
                            label={__('To', 'currencyrate-today-currency-blocks')}
                            value={pair.to}
                            currencies={currencies}
                            compact
                            onChange={(to) => {
                              const next = [...attributes.pairs];
                              next[idx] = { ...next[idx], to };
                              setAttributes({ pairs: next });
                            }}
                            availableCodes={availableCodes}
                          />
                        </div>
                      </div>
                    </div>
                  ))}
                  <Button
                    variant="secondary"
                    icon="plus-alt2"
                    onClick={() => {
                      setAttributes({ pairs: [...attributes.pairs, { from: 'USD', to: 'EUR' }] });
                    }}
                  >
                    {__('Add pair', 'currencyrate-today-currency-blocks')}
                  </Button>
                </PanelBody>
              </>
            ) : tab.name === 'ticker' ? (
              <>
                <PanelBody title={__('Scroll settings', 'currencyrate-today-currency-blocks')} initialOpen>
                  <RangeControl __next40pxDefaultSize={true} 
                    label={__('Speed (px/sec)', 'currencyrate-today-currency-blocks')}
                    help={__('Scrolling speed in pixels per second', 'currencyrate-today-currency-blocks')}
                    value={attributes.speed}
                    min={10}
                    max={200}
                    step={5}
                    onChange={(speed) => setAttributes({ speed: Number(speed) })}
                  />

                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Direction', 'currencyrate-today-currency-blocks')}
                    value={attributes.direction}
                    options={[
                      { label: __('Left', 'currencyrate-today-currency-blocks'), value: 'left' },
                      { label: __('Right', 'currencyrate-today-currency-blocks'), value: 'right' }
                    ]}
                    onChange={(direction) => setAttributes({ direction: direction as TickerAttributes['direction'] })}
                  />

                  <ToggleControl 
                    label={__('Pause on hover', 'currencyrate-today-currency-blocks')}
                    help={__('Pause scrolling when mouse hovers over the ticker', 'currencyrate-today-currency-blocks')}
                    checked={attributes.pauseOnHover}
                    onChange={(pauseOnHover) => setAttributes({ pauseOnHover })}
                  />
                </PanelBody>
              </>
            ) : (
              <>
                <PanelBody title={__('Presentation', 'currencyrate-today-currency-blocks')} initialOpen>
                  <RangeControl
                    label={__('Decimals', 'currencyrate-today-currency-blocks')}
                    value={attributes.decimals}
                    min={0}
                    max={8}
                    onChange={(decimals) => setAttributes({ decimals: Number(decimals) })}
                  />

                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Theme', 'currencyrate-today-currency-blocks')}
                    value={attributes.theme}
                    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 TickerAttributes['theme'] })}
                  />

                  <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 TickerAttributes['currencyLabelMode'] })
                    }
                  />

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

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

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

                  <ToggleControl 
                    label={__('Show timestamp', 'currencyrate-today-currency-blocks')}
                    help={__('Display the date of the exchange rates below the ticker.', 'currencyrate-today-currency-blocks')}
                    checked={attributes.showTimestamp}
                    onChange={(showTimestamp) => setAttributes({ showTimestamp })}
                  />

                  <ToggleControl 
                    label={__('Border top & bottom', 'currencyrate-today-currency-blocks')}
                    checked={attributes.borderY}
                    onChange={(borderY) => setAttributes({ borderY })}
                  />

                  <ToggleControl
                    label={__('Border left & right', 'currencyrate-today-currency-blocks')}
                    checked={attributes.borderX}
                    onChange={(borderX) => setAttributes({ borderX })}
                  />

                  <SelectControl __next40pxDefaultSize={true} 
                    label={__('Separator', 'currencyrate-today-currency-blocks')}
                    value={attributes.separator}
                    options={[
                      { label: __('Dot ·', 'currencyrate-today-currency-blocks'), value: 'dot' },
                      { label: __('Pipe |', 'currencyrate-today-currency-blocks'), value: 'pipe' },
                      { label: __('Slash /', 'currencyrate-today-currency-blocks'), value: 'slash' },
                      { label: __('None', 'currencyrate-today-currency-blocks'), value: 'none' }
                    ]}
                    onChange={(separator) => setAttributes({ separator: separator as TickerAttributes['separator'] })}
                  />
                </PanelBody>
              </>
            )
          }
        </TabPanel>
      </InspectorControls>

      <ServerSideRender block="crtoday/ticker" attributes={attributes} />
    </div>
  );
};
