'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 { ToothGlyph } from '@/components/ui/treatment/ToothGlyph';
import type { FdiToothId } from '@/types/treatment';

const TOOTH_NUMBER_GAP = 'mt-1';

/** Six teeth each side of the midline (anteriors): slightly larger glyph + wrapper. */
const MIDLINE_SIX = new Set<FdiToothId>([
  '13', '12', '11', '21', '22', '23',
  '43', '42', '41', '31', '32', '33',
]);

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

interface FdiToothChartProps {
  selected: ReadonlySet<FdiToothId>;
  /** Teeth that belong to a connected selection span (dots above/below). */
  connectedTeeth?: ReadonlySet<FdiToothId>;
  onToggle?: (fdi: FdiToothId, event: { shiftKey: boolean; ctrlKey: boolean }) => 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;
}

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

  const TOOTH_TWEAKS: Record<FdiToothId, { glyph: string; offset: number; rotate: number }> = {
    '18': { glyph: 'w-[1.98rem] h-[4.65rem]', offset: 7, rotate: -11 },
    '17': { glyph: 'w-[2rem] h-[4.75rem]', offset: 8, rotate: -8 },
    '16': { glyph: 'w-[2.1rem] h-[4.95rem]', offset: 9, rotate: -6 },
    '15': { glyph: 'w-[1.8rem] h-[4.8rem]', offset: 9, rotate: -4 },
    '14': { glyph: 'w-[1.8rem] h-[4.85rem]', offset: 9, rotate: -2 },
    '13': { glyph: 'w-[1.9rem] h-[5.28rem]', offset: 8, rotate: -1 },
    '12': { glyph: 'w-[1.8rem] h-[5.02rem]', offset: 7, rotate: -1 },
    '11': { glyph: 'w-[1.8rem] h-[5.08rem]', offset: 7, rotate: -0.5 },
    '21': { glyph: 'w-[1.8rem] h-[5.08rem]', offset: 7, rotate: 0.5 },
    '22': { glyph: 'w-[1.8rem] h-[5.02rem]', offset: 7, rotate: 1 },
    '23': { glyph: 'w-[1.9rem] h-[5.28rem]', offset: 8, rotate: 1 },
    '24': { glyph: 'w-[1.8rem] h-[4.85rem]', offset: 9, rotate: 2 },
    '25': { glyph: 'w-[1.8rem] h-[4.8rem]', offset: 9, rotate: 4 },
    '26': { glyph: 'w-[2.1rem] h-[4.95rem]', offset: 9, rotate: 6 },
    '27': { glyph: 'w-[2rem] h-[4.75rem]', offset: 8, rotate: 8 },
    '28': { glyph: 'w-[1.98rem] h-[4.65rem]', offset: 7, rotate: 11 },

    '48': { glyph: 'w-[1.98rem] h-[4.7rem]', offset: -7, rotate: -11 },
    '47': { glyph: 'w-[2rem] h-[4.8rem]', offset: -8, rotate: -8 },
    '46': { glyph: 'w-[2.15rem] h-[5rem]', offset: -9, rotate: -6 },
    '45': { glyph: 'w-[1.82rem] h-[4.85rem]', offset: -9, rotate: -4 },
    '44': { glyph: 'w-[1.82rem] h-[4.9rem]', offset: -9, rotate: -2 },
    '43': { glyph: 'w-[1.88rem] h-[5.34rem]', offset: -8, rotate: -1 },
    '42': { glyph: 'w-[1.76rem] h-[5.04rem]', offset: -7, rotate: -1 },
    '41': { glyph: 'w-[1.74rem] h-[4.98rem]', offset: -7, rotate: -0.5 },
    '31': { glyph: 'w-[1.74rem] h-[4.98rem]', offset: -7, rotate: 0.5 },
    '32': { glyph: 'w-[1.76rem] h-[5.04rem]', offset: -7, rotate: 1 },
    '33': { glyph: 'w-[1.88rem] h-[5.34rem]', offset: -8, rotate: 1 },
    '34': { glyph: 'w-[1.82rem] h-[4.9rem]', offset: -9, rotate: 2 },
    '35': { glyph: 'w-[1.82rem] h-[4.85rem]', offset: -9, rotate: 4 },
    '36': { glyph: 'w-[2.15rem] h-[5rem]', offset: -9, rotate: 6 },
    '37': { glyph: 'w-[2rem] h-[4.8rem]', offset: -8, rotate: 8 },
    '38': { glyph: 'w-[1.98rem] h-[4.7rem]', offset: -7, rotate: 11 },
  };

  const toothSizeClass = (fdi: FdiToothId) => {
    const kind = getToothShapeKind(fdi);
    const mid = MIDLINE_SIX.has(fdi);
    switch (kind) {
      case 'incisor':
        return mid
          ? { wrapper: 'w-[2.1rem]', glyph: 'w-[1.68rem] h-[4.78rem]' }
          : { wrapper: 'w-[2rem]', glyph: 'w-[1.6rem] h-[4.6rem]' };
      case 'canine':
        return mid
          ? { wrapper: 'w-[2.2rem]', glyph: 'w-[1.78rem] h-[5.05rem]' }
          : { wrapper: 'w-[2.1rem]', glyph: 'w-[1.7rem] h-[4.9rem]' };
      case 'premolar':
        return mid
          ? { wrapper: 'w-[2.34rem]', glyph: 'w-[1.93rem] h-[5.02rem]' }
          : { wrapper: 'w-[2.25rem]', glyph: 'w-[1.85rem] h-[4.85rem]' };
      case 'molar':
        return mid
          ? { wrapper: 'w-[2.52rem]', glyph: 'w-[2.12rem] h-[5.1rem]' }
          : { wrapper: 'w-[2.45rem]', glyph: 'w-[2.05rem] h-[4.95rem]' };
      default:
        return { wrapper: 'w-[2.25rem]', glyph: 'w-[1.85rem] h-[4.85rem]' };
    }
  };

  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 * 6;
  };

  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;
  };

  /** Dots + thin links — only for Shift-connected spans (not plain / Ctrl singles). */
  const ConnectedRail = ({ teeth, upper }: { teeth: FdiToothId[]; upper?: boolean }) => {
    const hasConnected = teeth.some((fdi) => connectedTeeth?.has(fdi));
    if (!hasConnected) return null;

    return (
      <div
        className={`flex flex-nowrap justify-center gap-x-1 min-w-max mx-auto w-fit ${upper ? 'mb-1' : 'mt-1'}`}
        aria-hidden
      >
        {teeth.map((fdi, i) => {
          const size = toothSizeClass(fdi);
          const isConnected = Boolean(connectedTeeth?.has(fdi));
          const next = teeth[i + 1];
          const linkToNext = Boolean(isConnected && next && connectedTeeth?.has(next));
          return (
            <div
              key={`c-${fdi}`}
              className={`relative flex h-2.5 items-center justify-center ${size.wrapper}`}
              title={isConnected ? t('toothConnectedHint') : undefined}
            >
              {linkToNext ? (
                <span
                  className="pointer-events-none absolute top-1/2 left-1/2 z-0 h-[2px] -translate-y-1/2 bg-primary/75"
                  style={{ width: 'calc(100% + 0.25rem)' }}
                />
              ) : null}
              {isConnected ? (
                <span className="relative z-10 block h-2 w-2 rounded-full bg-primary shadow-sm" />
              ) : (
                <span className="block h-2 w-2" />
              )}
            </div>
          );
        })}
      </div>
    );
  };

  const Row = ({ teeth, upper }: { teeth: FdiToothId[]; upper?: boolean }) => (
    <div className="flex flex-col items-center min-w-max mx-auto w-fit">
      {upper ? <ConnectedRail teeth={teeth} upper /> : null}
      <div className="flex flex-nowrap justify-center gap-x-1 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 isConnected = Boolean(connectedTeeth?.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 glyph = (
            <ToothGlyph
              fdi={fdi}
              kind={kind}
              gradientId={gid}
              selected={isSel}
              upper={upper}
              mirrored={quadrantMirrored(fdi)}
              upsideDown={upper}
              className={tweak?.glyph ?? size.glyph}
              accentColor={isSel ? accent : undefined}
            />
          );

          return (
            <div key={fdi} className={`flex flex-col items-center ${size.wrapper}`}>
              <div className={`h-[5.9rem] flex ${alignItems} justify-center`}>
                {interactive ? (
                  <button
                    type="button"
                    disabled={isDisabled}
                    onMouseDown={(e) => {
                      // Modifier+click otherwise triggers browser text-selection / sticky focus boxes.
                      if (e.shiftKey || e.ctrlKey || e.metaKey) e.preventDefault();
                    }}
                    onClick={(e) => {
                      e.preventDefault();
                      onToggle?.(fdi, {
                        shiftKey: e.shiftKey,
                        ctrlKey: e.ctrlKey || e.metaKey,
                      });
                    }}
                    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')}${
                            isConnected ? t('toothConnectedSuffix') : ''
                          }`
                        : 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>
            </div>
          );
        })}
      </div>
      {!upper ? <ConnectedRail 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 gap-x-1 ${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 ${size.wrapper} ${numberColorClass(fdi, isSel)}`}
                    style={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 gap-x-1">
                {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 ${size.wrapper} ${numberColorClass(fdi, isSel)}`}
                      style={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-right">
            {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>
  );
}
