import type { FunctionalComponent } from 'preact';
import { registerModule, type AsukaModuleContext } from '../../core/modules';
import { useAsukaStore } from '../../store/asukaStore';
import { DEFAULT_PERMISSIONS } from '../../core/permissions';
import { IconButton } from '../core/IconButton';
import { Card, CardContent, CardHeader, CardTitle } from '../core/Card';
import { AsukaIcon } from '../core/AsukaIcon';
import { Tooltip } from '../core/Tooltip';
import { useT } from '../../hooks/useT';

type BasicKind = 'rect' | 'circle' | 'triangle' | 'line' | 'star';

type ShapeLibraryItem = {
  id: string;
  kind: BasicKind;
  label: string;
  helper: string;
  labelKey: string;
  helperKey: string;
};

const BASIC_SHAPES: ShapeLibraryItem[] = [
  { id: 'rect', kind: 'rect', labelKey: 'shapes.rect', label: 'Rectangle', helperKey: 'shapes.rectHelper', helper: 'Classic block shape' },
  { id: 'circle', kind: 'circle', labelKey: 'shapes.circle', label: 'Circle', helperKey: 'shapes.circleHelper', helper: 'Rounded shape for badges' },
  { id: 'triangle', kind: 'triangle', labelKey: 'shapes.triangle', label: 'Triangle', helperKey: 'shapes.triangleHelper', helper: 'Strong directional shape' },
  { id: 'line', kind: 'line', labelKey: 'shapes.line', label: 'Line', helperKey: 'shapes.lineHelper', helper: 'Divider or underline' },
  { id: 'star', kind: 'star', labelKey: 'shapes.star', label: 'Star', helperKey: 'shapes.starHelper', helper: 'Accent and highlight shape' },
];

const BasicShapePreview: FunctionalComponent<{ kind: BasicKind }> = ({ kind }) => {
  if (kind === 'rect') {
    return (
      <svg viewBox="0 0 120 84" class="ask-shapes-module__preview-svg" aria-hidden="true">
        <rect x="18" y="18" width="84" height="48" rx="12" />
      </svg>
    );
  }

  if (kind === 'circle') {
    return (
      <svg viewBox="0 0 120 84" class="ask-shapes-module__preview-svg" aria-hidden="true">
        <circle cx="60" cy="42" r="24" />
      </svg>
    );
  }

  if (kind === 'triangle') {
    return (
      <svg viewBox="0 0 120 84" class="ask-shapes-module__preview-svg" aria-hidden="true">
        <path d="M60 16 98 68 22 68Z" />
      </svg>
    );
  }

  if (kind === 'line') {
    return (
      <svg viewBox="0 0 120 84" class="ask-shapes-module__preview-svg" aria-hidden="true">
        <line x1="22" y1="42" x2="98" y2="42" />
      </svg>
    );
  }

  return (
    <svg viewBox="0 0 120 84" class="ask-shapes-module__preview-svg" aria-hidden="true">
      <path d="M60 14 68 32 88 34 73 47 77 67 60 57 43 67 47 47 32 34 52 32Z" />
    </svg>
  );
};

export const ShapesModule: FunctionalComponent<{ context: AsukaModuleContext }> = ({ context }) => {
  const t = useT();
  const engine = context.getEngine?.() ?? null;
  const shapeTools = engine?.canvas2d ?? null;
  const permissions = useAsukaStore((s: any) => s.permissions ?? DEFAULT_PERMISSIONS);
  const placing = useAsukaStore((s) => s.shapePlacing);
  const beginPlace = useAsukaStore((s) => s.beginPlaceShape);
  const cancelPlace = useAsukaStore((s) => s.cancelPlaceShape);
  const shapeStyle = useAsukaStore((s) => s.shapeStyle);
  const editDefaults = useAsukaStore((s) => s.shapeEditDefaults);

  const getDefaultStyle = () => {
    const fill = typeof shapeStyle?.fill === 'string' ? shapeStyle.fill : 'transparent';
    const stroke = typeof shapeStyle?.stroke === 'string' ? shapeStyle.stroke : '#111827';
    const strokeWidth = Math.max(0, Number(shapeStyle?.strokeWidth ?? 2) || 2);
    const opacity = Math.min(1, Math.max(0, Number(shapeStyle?.opacity ?? 1) || 1));
    return { fill, stroke, strokeWidth, opacity };
  };

  const addBasic = (kind: BasicKind) => {
    if (!(permissions as any)?.canAddShape) return;
    if (!shapeTools) return;
    const { fill, stroke, strokeWidth, opacity } = getDefaultStyle();
    void shapeTools.addShape({
      kind,
      fill,
      stroke,
      strokeWidth,
      opacity,
      rectRadius: Math.max(0, Number(editDefaults?.rectRadius ?? 0) || 0),
      starSpikes: Math.max(3, Math.min(32, Number(editDefaults?.starSpikes ?? 5) || 5)),
      starInnerRatio: Math.min(0.95, Math.max(0.05, Number(editDefaults?.starInnerRatio ?? 0.45) || 0.45)),
    }).catch(() => {});
  };

  const startDrawBasic = (kind: BasicKind) => {
    if (!(permissions as any)?.canDrawShape) return;
    beginPlace({ type: 'basic', kind } as any);
  };


  return (
    <div class="ask-shapes-module">
      <Card>
        <CardHeader className="ask-flex ask-items-center ask-justify-between ask-gap-2">
          <CardTitle>{t('modules.shapes', 'Shapes')}</CardTitle>
          {placing ? (
            <Tooltip content={t('shapes.cancelDrawing', 'Cancel drawing')} direction="left">
              <IconButton aria-label={t('shapes.cancelDrawing', 'Cancel drawing')} onClick={() => cancelPlace?.()} variant="plain">
                <AsukaIcon name="close" size={14} />
              </IconButton>
            </Tooltip>
          ) : null}
        </CardHeader>
        <CardContent className="ask-flex ask-flex-col ask-gap-4">
          <div class="ask-shapes-module__visual-grid">
            {BASIC_SHAPES.map((item) => (
              <div key={item.id} class="ask-shapes-module__shape-card">
                <div class="ask-shapes-module__shape-preview-wrap">
                  <BasicShapePreview kind={item.kind} />
                </div>

                <div class="ask-shapes-module__shape-meta">
                  <div class="ask-shapes-module__shape-name">{t((item as any).labelKey, item.label)}</div>
                  <div class="ask-shapes-module__shape-helper">{t((item as any).helperKey, item.helper)}</div>
                </div>

                <div class="ask-shapes-module__shape-actions ask-shapes-module__shape-actions--icons">
                  <Tooltip content={t('shapes.addShape', 'Add {shape}', { shape: t((item as any).labelKey, item.label) })} direction="top">
                    <IconButton
                      aria-label={t('shapes.addShape', 'Add {shape}', { shape: t((item as any).labelKey, item.label) })}
                      onClick={() => addBasic(item.kind)} disabled={!((permissions as any)?.canAddShape ?? true)}
                      className="ask-shapes-module__icon-action ask-shapes-module__icon-action--add"
                    >
                      <AsukaIcon name="plus" size={14} />
                    </IconButton>
                  </Tooltip>
                  <Tooltip content={t('shapes.drawShape', 'Draw {shape}', { shape: t((item as any).labelKey, item.label) })} direction="top">
                    <IconButton
                      aria-label={t('shapes.drawShape', 'Draw {shape}', { shape: t((item as any).labelKey, item.label) })}
                      onClick={() => startDrawBasic(item.kind)} disabled={!((permissions as any)?.canDrawShape ?? true)}
                      className="ask-shapes-module__icon-action ask-shapes-module__icon-action--draw"
                    >
                      <AsukaIcon name="brush" size={14} />
                    </IconButton>
                  </Tooltip>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

registerModule({
  id: 'shapes' as any,
  label: 'Shapes',
  icon: 'customize',
  displayMode: 'floating',
  supportedEngines: ['fabric'],
  requiredCapabilities: ['canvas2d'],
  render: ({ context }) => <ShapesModule context={context} />,
});
