'use client';

import { useId, type CSSProperties, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import { FDI_LOWER_LEFT_TO_RIGHT, FDI_UPPER_LEFT_TO_RIGHT, getToothShapeKind } from '@/components/treatment/fdiToothMeta';
import {
  getToothColumnWidthRem,
  getToothGlyphWidthRem,
} from '@/components/treatment/fdiToothScale';
import { getRealisticToothAsset } from '@/components/treatment/realisticToothAssets';
import { toothEdgeKey } from '@/components/treatment/toothSelectionGroups';
import { ToothGlyph } from '@/components/ui/treatment/ToothGlyph';
import type { FdiToothId } from '@/types/treatment';

const TOOTH_NUMBER_GAP = 'mt-1';
/** Extra crown↔number space for realistic SVGs (outside arch transform so it is not cancelled). */
const REALISTIC_NUMBER_GAP = '2mm';
/** Tight interproximal gap between tooth columns. */
const TOOTH_GAP = 'gap-x-px';
/** Fixed row cell height — must fit tallest scaled canine/root. */
const TOOTH_CELL_H = 'h-[7.25rem]';

function quadrantMirrored(fdi: FdiToothId): boolean {
  const q = fdi[0];
  return q === '2' || q === '3';
}

/** Cartoon glyph height factor vs width (realistic assets use aspect ratio from viewBox). */
function cartoonHeightRem(fdi: FdiToothId, widthRem: number): number {
  const kind = getToothShapeKind(fdi);
  const factor = kind === 'canine' ? 2.85 : kind === 'molar' ? 2.45 : 2.65;
  return Number((widthRem * factor).toFixed(3));
}

function toothSize(fdi: FdiToothId): {
  columnWidthRem: number;
  glyphWidthRem: number;
  glyphHeightRem: number | 'auto';
} {
  const glyphWidthRem = getToothGlyphWidthRem(fdi);
  const columnWidthRem = getToothColumnWidthRem(fdi);
  const realistic = Boolean(getRealisticToothAsset(fdi));
  return {
    columnWidthRem,
    glyphWidthRem,
    glyphHeightRem: realistic ? 'auto' : cartoonHeightRem(fdi, glyphWidthRem),
  };
}

interface FdiToothChartProps {
  selected: ReadonlySet<FdiToothId>;
  /**
   * Legacy / read-only: teeth in a connected bridge.
   * When `linkedEdges` is omitted, filled marks are shown between adjacent
   * selected teeth that both appear in this set.
   */
  connectedTeeth?: ReadonlySet<FdiToothId>;
  /** Filled connection edges (`toothEdgeKey(a,b)`). Preferred over `connectedTeeth` for edit mode. */
  linkedEdges?: ReadonlySet<string>;
  onToggle?: (fdi: FdiToothId, event: { shiftKey: boolean }) => void;
  /** Toggle connect/disconnect for an adjacent selected pair. */
  onToggleLink?: (a: FdiToothId, b: FdiToothId) => void;
  disabled?: boolean;
  /** Non-interactive display (Cases / connection history). */
  readOnly?: boolean;
  /** Visual scale via CSS zoom (0.5 = half size). */
  scale?: number;
  /** Per-tooth accent color for selected glow (prosthesis / treatment-type palettes). */
  toothColors?: Partial<Record<FdiToothId, string>>;
  /** Extra control rendered in the chart header (e.g. whole-plan checkbox). */
  headerControl?: ReactNode;
  /** Compact card for embedded case detail panels. */
  compact?: boolean;
  className?: string;
}

/**
 * Distal tip for arch look — gentler than pre-SVG angles so realistic glyphs stay readable.
 * Positive rotate = clockwise.
 */
const TOOTH_TWEAKS: Partial<Record<FdiToothId, { offset: number; rotate: number }>> = {
  '18': { offset: 5, rotate: -7 },
  '17': { offset: 6, rotate: -5 },
  '16': { offset: 6, rotate: -3.5 },
  '15': { offset: 6, rotate: -2 },
  '14': { offset: 5, rotate: -1 },
  '13': { offset: 5.5, rotate: -0.5 },
  '12': { offset: 4, rotate: -0.25 },
  '11': { offset: 5, rotate: 0 },
  '21': { offset: 5, rotate: 0 },
  '22': { offset: 4, rotate: 0.25 },
  '23': { offset: 5.5, rotate: 0.5 },
  '24': { offset: 5, rotate: 1 },
  '25': { offset: 6, rotate: 2 },
  '26': { offset: 6, rotate: 3.5 },
  '27': { offset: 6, rotate: 5 },
  '28': { offset: 5, rotate: 7 },

  '48': { offset: -5, rotate: -4 },
  '47': { offset: -6, rotate: -3 },
  '46': { offset: -6, rotate: -2 },
  '45': { offset: -6, rotate: -2 },
  '44': { offset: -5, rotate: -1 },
  '43': { offset: -4, rotate: -0.5 },
  '42': { offset: -4, rotate: -0.25 },
  '41': { offset: -3, rotate: 0 },
  '31': { offset: -3, rotate: 0 },
  '32': { offset: -4, rotate: 0.25 },
  '33': { offset: -4, rotate: 0.5 },
  '34': { offset: -5, rotate: 1 },
  '35': { offset: -6, rotate: 2 },
  '36': { offset: -6, rotate: 2 },
  '37': { offset: -6, rotate: 3 },
  '38': { offset: -5, rotate: 4 },
};

export function FdiToothChart({
  selected,
  connectedTeeth,
  linkedEdges,
  onToggle,
  onToggleLink,
  disabled,
  readOnly = false,
  scale = 1,
  toothColors,
  headerControl,
  compact = false,
  className = '',
}: FdiToothChartProps) {
  const t = useTranslations('treatment');
  const uid = useId().replace(/:/g, '');
  const archPeak = 8;
  const interactive = !readOnly && Boolean(onToggle);
  const linkInteractive = interactive && Boolean(onToggleLink);
  const isDisabled = disabled || readOnly;

  const toothSizeClass = (fdi: FdiToothId) => toothSize(fdi);

  const archOffset = (index: number, count: number, upper?: boolean) => {
    const center = (count - 1) / 2;
    const dist = Math.abs(index - center) / center;
    const curve = (1 - Math.pow(dist, 1.45)) * archPeak;
    return upper ? curve : -curve;
  };

  const archRotate = (index: number, count: number) => {
    const center = (count - 1) / 2;
    const normalized = (index - center) / center;
    return normalized * 4;
  };

  const toothAccent = (fdi: FdiToothId) => toothColors?.[fdi];

  const numberColorClass = (fdi: FdiToothId, isSel: boolean) => {
    if (!isSel) return 'text-text-muted';
    const accent = toothAccent(fdi);
    return accent ? '' : 'text-primary';
  };

  const numberStyle = (fdi: FdiToothId, isSel: boolean): CSSProperties | undefined => {
    if (!isSel) return undefined;
    const accent = toothAccent(fdi);
    return accent ? { color: accent } : undefined;
  };

  const edgeIsLinked = (a: FdiToothId, b: FdiToothId): boolean => {
    const key = toothEdgeKey(a, b);
    if (linkedEdges) return linkedEdges.has(key);
    // Read-only fallback: both teeth marked connected.
    return Boolean(connectedTeeth?.has(a) && connectedTeeth?.has(b));
  };

  /** Circles sit between neighbors, on the crown side (toward FDI numbers). */
  const EdgeRail = ({ teeth }: { teeth: FdiToothId[] }) => {
    const anyVisible = teeth.some((fdi, i) => {
      const next = teeth[i + 1];
      if (!next || !selected.has(fdi) || !selected.has(next)) return false;
      const linked = edgeIsLinked(fdi, next);
      return linkInteractive || linked;
    });
    if (!anyVisible) return null;

    return (
      <div
        className={`flex flex-nowrap justify-center ${TOOTH_GAP} min-w-max mx-auto w-fit h-3.5 items-center`}
      >
        {teeth.map((fdi, i) => {
          const size = toothSizeClass(fdi);
          const prev = i > 0 ? teeth[i - 1] : undefined;
          const next = teeth[i + 1];
          const showEdge = Boolean(next && selected.has(fdi) && selected.has(next));
          const linked = showEdge ? edgeIsLinked(fdi, next!) : false;
          const renderEdge = showEdge && (linkInteractive || linked);
          // Narrow link across this column when both neighboring edges are filled.
          const bridgeLine = Boolean(
            prev &&
              next &&
              selected.has(prev) &&
              selected.has(fdi) &&
              selected.has(next) &&
              edgeIsLinked(prev, fdi) &&
              edgeIsLinked(fdi, next),
          );

          return (
            <div
              key={`e-${fdi}`}
              className="relative h-3.5 flex items-center justify-center"
              style={{ width: `${size.columnWidthRem}rem` }}
            >
              {bridgeLine ? (
                <span
                  className="pointer-events-none absolute inset-x-0 top-1/2 z-0 h-[2px] -translate-y-1/2 bg-primary/75"
                  aria-hidden
                />
              ) : null}
              {renderEdge ? (
                linkInteractive ? (
                  <button
                    type="button"
                    disabled={isDisabled}
                    title={linked ? t('toothUnlinkHint') : t('toothLinkHint')}
                    aria-label={
                      linked
                        ? t('toothUnlinkAria', { a: fdi, b: next! })
                        : t('toothLinkAria', { a: fdi, b: next! })
                    }
                    aria-pressed={linked}
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      onToggleLink?.(fdi, next!);
                    }}
                    className={`
                      absolute right-0 z-10 translate-x-1/2 h-3.5 w-3.5 rounded-full border-2 transition-colors
                      focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50
                      ${
                        linked
                          ? 'border-primary bg-primary shadow-sm'
                          : 'border-primary bg-background-secondary hover:bg-primary/15'
                      }
                      ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
                    `}
                  />
                ) : (
                  <span
                    className="absolute right-0 z-10 translate-x-1/2 h-2.5 w-2.5 rounded-full bg-primary shadow-sm"
                    title={t('toothConnectedHint')}
                    aria-hidden
                  />
                )
              ) : null}
            </div>
          );
        })}
      </div>
    );
  };

  const Row = ({ teeth, upper }: { teeth: FdiToothId[]; upper?: boolean }) => (
    <div className="flex flex-col items-center min-w-max mx-auto w-fit gap-y-0.5">
      {/* Lower: crowns face numbers above → rail above teeth */}
      {!upper ? <EdgeRail teeth={teeth} /> : null}
      <div className={`flex flex-nowrap justify-center ${TOOTH_GAP} min-w-max mx-auto w-fit`}>
        {teeth.map((fdi, i) => {
          const kind = getToothShapeKind(fdi);
          const gid = `${uid}-g-${fdi}-${i}`;
          const isSel = selected.has(fdi);
          const size = toothSizeClass(fdi);
          const tweak = TOOTH_TWEAKS[fdi];
          const offsetY = tweak ? tweak.offset : archOffset(i, teeth.length, upper);
          const rotate = tweak ? tweak.rotate : archRotate(i, teeth.length);
          const alignItems = upper ? 'items-end' : 'items-start';
          const accent = toothAccent(fdi);
          const realistic = Boolean(getRealisticToothAsset(fdi));

          const glyph = (
            <ToothGlyph
              fdi={fdi}
              kind={kind}
              gradientId={gid}
              selected={isSel}
              upper={upper}
              mirrored={quadrantMirrored(fdi)}
              upsideDown={upper}
              className="shrink-0 max-h-full"
              style={{
                width: `${size.glyphWidthRem}rem`,
                height: size.glyphHeightRem === 'auto' ? 'auto' : `${size.glyphHeightRem}rem`,
              }}
              accentColor={isSel ? accent : undefined}
            />
          );

          return (
            <div
              key={fdi}
              className="flex flex-col items-center"
              style={{ width: `${size.columnWidthRem}rem` }}
            >
              {!upper && realistic ? (
                <div style={{ height: REALISTIC_NUMBER_GAP }} aria-hidden />
              ) : null}
              <div className={`${TOOTH_CELL_H} flex ${alignItems} justify-center`}>
                {interactive ? (
                  <button
                    type="button"
                    disabled={isDisabled}
                    onMouseDown={(e) => {
                      if (e.shiftKey) e.preventDefault();
                    }}
                    onClick={(e) => {
                      e.preventDefault();
                      onToggle?.(fdi, { shiftKey: e.shiftKey });
                    }}
                    style={{ transform: `translateY(${offsetY}px) rotate(${rotate}deg)` }}
                    className={`
                      rounded-[var(--radius-sm)] p-0.5 transition-transform select-none
                      focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/50
                      ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'hover:scale-105 active:scale-95'}
                    `}
                    aria-pressed={isSel}
                    aria-label={
                      isSel
                        ? `${t('toothAria', { fdi })}${t('toothSelectedSuffix')}`
                        : t('toothAria', { fdi })
                    }
                  >
                    {glyph}
                  </button>
                ) : (
                  <div
                    style={{ transform: `translateY(${offsetY}px) rotate(${rotate}deg)` }}
                    className="rounded-[var(--radius-sm)] p-0.5"
                    aria-hidden={!isSel}
                  >
                    {glyph}
                  </div>
                )}
              </div>
              {upper && realistic ? (
                <div style={{ height: REALISTIC_NUMBER_GAP }} aria-hidden />
              ) : null}
            </div>
          );
        })}
      </div>
      {/* Upper: crowns face numbers below → rail below teeth */}
      {upper ? <EdgeRail teeth={teeth} /> : null}
    </div>
  );

  const cardClass = compact
    ? 'rounded-lg border border-border/60 bg-background-secondary/30 p-2 space-y-2'
    : 'surface-card p-3 space-y-3';

  const chartBody = (
    <>
      <p className="text-[11px] uppercase tracking-wide text-text-muted mb-1 text-center">{t('upperArch')}</p>

      <div className="overflow-x-auto py-1 -mx-1 px-1 select-none">
        <div className="relative isolate min-w-max mx-auto w-fit select-none">
          <div
            className="pointer-events-none absolute left-1/2 top-3 bottom-3 w-px -translate-x-1/2 bg-border/70"
            aria-hidden
          />
          <div className="relative z-10 space-y-0">
            <Row teeth={FDI_UPPER_LEFT_TO_RIGHT} upper />
            <div className={`flex flex-nowrap justify-center ${TOOTH_GAP} ${TOOTH_NUMBER_GAP}`}>
              {FDI_UPPER_LEFT_TO_RIGHT.map((fdi) => {
                const size = toothSizeClass(fdi);
                const isSel = selected.has(fdi);
                return (
                  <span
                    key={`u-${fdi}`}
                    className={`text-[10px] tabular-nums text-center leading-none ${numberColorClass(fdi, isSel)}`}
                    style={{
                      width: `${size.columnWidthRem}rem`,
                      ...(numberStyle(fdi, isSel) ?? {}),
                    }}
                  >
                    {fdi}
                  </span>
                );
              })}
            </div>

            <div className="my-2 h-px w-full bg-border/70" role="separator" aria-hidden />

            <div className="pt-0.5">
              <div className={`flex flex-nowrap justify-center ${TOOTH_GAP}`}>
                {FDI_LOWER_LEFT_TO_RIGHT.map((fdi) => {
                  const size = toothSizeClass(fdi);
                  const isSel = selected.has(fdi);
                  return (
                    <span
                      key={`l-${fdi}`}
                      className={`text-[10px] tabular-nums text-center leading-none ${numberColorClass(fdi, isSel)}`}
                      style={{
                        width: `${size.columnWidthRem}rem`,
                        ...(numberStyle(fdi, isSel) ?? {}),
                      }}
                    >
                      {fdi}
                    </span>
                  );
                })}
              </div>
              <div className={TOOTH_NUMBER_GAP}>
                <Row teeth={FDI_LOWER_LEFT_TO_RIGHT} />
              </div>
            </div>
          </div>
        </div>
      </div>

      <p className="text-[11px] uppercase tracking-wide text-text-muted mt-1 text-center">{t('lowerArch')}</p>
    </>
  );

  return (
    <div className={`${cardClass} ${className}`}>
      <div className="flex flex-col gap-1.5 sm:flex-row sm:items-start sm:justify-between">
        <div className="min-w-0">
          <h3 className="text-sm font-semibold text-text-primary">
            {compact ? t('toothChartTitleCompact') : t('toothChartTitle')}
          </h3>
          {!compact && (
            <p className="text-[11px] text-text-muted mt-0.5">{t('toothChartHint')}</p>
          )}
        </div>
        <div className="flex flex-col items-start gap-1.5 sm:items-end shrink-0">
          {headerControl}
          <p className="text-[11px] text-text-secondary tabular-nums sm:text-end">
            {t('selectedLabel')}{' '}
            {selected.size === 0 ? t('selectedEmpty') : [...selected].sort().join(', ')}
          </p>
        </div>
      </div>

      {scale !== 1 ? (
        <div style={{ zoom: scale }} className="origin-top-left w-fit">
          {chartBody}
        </div>
      ) : (
        chartBody
      )}
    </div>
  );
}
