import type { AsukaModuleComponent } from '../../core/modules';
import type { AsukaCanvas2DTextPatch, AsukaCanvas2DTextSelection } from '../../core/renderEngine';
import { getSelectedRendererText, updateSelectedRendererText } from '../../core/rendererTextSelection';
import { useEffect, useMemo, useState } from 'preact/hooks';
import { useAsukaStore } from '../../store/asukaStore';
import { useT } from '../../hooks/useT';
import { Card, CardContent } from '../core/Card';
import { Field } from '../core/Field';
import { Input } from '../core/Input';
import { Select } from '../core/Select';
import { ToggleButton } from '../core/ToggleButton';
import { ColorInput } from '../forms';

const TextFormatting3DModule: AsukaModuleComponent = ({ context }) => {
  const t = useT();
  const engine = context.getEngine?.() ?? null;
  const fontsCatalog = useAsukaStore((state: any) => state.fontsCatalog ?? []);
  const [activeText, setActiveText] = useState<AsukaCanvas2DTextSelection | null>(() => getSelectedRendererText(engine));

  useEffect(() => {
    const sync = () => setActiveText(getSelectedRendererText(engine));
    sync();
    return engine?.events.subscribe(() => sync()) ?? (() => {});
  }, [engine]);

  const fontOptions = useMemo(() => {
    const current = String(activeText?.fontFamily ?? 'Arial');
    const values = (Array.isArray(fontsCatalog) ? fontsCatalog : [])
      .map((font: any) => String(font?.family ?? '').trim())
      .filter(Boolean);
    if (!values.includes(current)) values.unshift(current);
    return Array.from(new Set(values)).map((value) => ({ value, label: value }));
  }, [activeText?.fontFamily, fontsCatalog]);

  const applyPatch = (patch: AsukaCanvas2DTextPatch) => {
    if (!engine || !activeText) return;
    void updateSelectedRendererText(engine, patch, { source: 'text-formatting-3d' }).catch(() => {});
  };

  if (!activeText) {
    return <Card><CardContent><div class="ask-text-[12px] ask-text-textMuted">{t('ui.select_a_text_object_to_edit_formatting', 'Select a text layer to edit formatting.')}</div></CardContent></Card>;
  }

  const fontWeight = String(activeText.fontWeight ?? 'normal');
  const isBold = fontWeight === 'bold' || Number(fontWeight) >= 600;
  const isItalic = activeText.fontStyle === 'italic';

  return (
    <Card>
      <CardContent className="ask-flex ask-flex-col ask-gap-3">
        <div class="ask-grid ask-grid-cols-2 ask-gap-2">
          <Field label={t('ui.font', 'Font')}>
            <Select value={activeText.fontFamily} options={fontOptions} onChange={(event) => applyPatch({ fontFamily: (event.currentTarget as HTMLSelectElement).value })} />
          </Field>
          <Field label={t('ui.size', 'Size')}>
            <Input type="number" min="8" value={String(activeText.fontSize)} onInput={(event) => applyPatch({ fontSize: Math.max(8, Number((event.currentTarget as HTMLInputElement).value) || 8) })} />
          </Field>
        </div>

        <div class="ask-flex ask-flex-wrap ask-gap-2">
          <ToggleButton pressed={isBold} onClick={() => applyPatch({ fontWeight: isBold ? 'normal' : 'bold' })} title={t('ui.bold', 'Bold')}>B</ToggleButton>
          <ToggleButton pressed={isItalic} onClick={() => applyPatch({ fontStyle: isItalic ? 'normal' : 'italic' })} title={t('ui.italic', 'Italic')}>I</ToggleButton>
          <ToggleButton pressed={activeText.underline} onClick={() => applyPatch({ underline: !activeText.underline })} title={t('ui.underline', 'Underline')}>U</ToggleButton>
          <ToggleButton onClick={() => applyPatch({ text: activeText.text.toUpperCase() })} title={t('ui.uppercase', 'Uppercase')}>UPPER</ToggleButton>
          <ToggleButton onClick={() => applyPatch({ text: activeText.text.toLowerCase() })} title={t('ui.lowercase', 'Lowercase')}>lower</ToggleButton>
        </div>

        <Field label={t('ui.text_color', 'Text color')}>
          <ColorInput value={activeText.fill} colorLabel={t('ui.text_color', 'Text color')} onValueChange={(value) => applyPatch({ fill: value })} />
        </Field>
      </CardContent>
    </Card>
  );
};

export default TextFormatting3DModule;
