'use client';

import {
  FDI_LOWER_LEFT_TO_RIGHT,
  FDI_UPPER_LEFT_TO_RIGHT,
} from '@/components/treatment/fdiToothMeta';
import {
  prosthesisTypeColor,
  prosthesisTypeColorFromCatalog,
} from '@/components/treatment/prosthesisTypeDisplay';
import type { CaseToothChartProsthesisRow } from '@/components/ui/lab/CaseToothChartPanel';
import type { ProsthesisCatalogEntry } from '@/types/treatment-catalog';
import type { FdiToothId } from '@/types/treatment';

type CaseSheetFdiChartProps = {
  selected: ReadonlySet<FdiToothId>;
  connectedTeeth: ReadonlySet<FdiToothId>;
  prosthesisRows: CaseToothChartProsthesisRow[];
  prosthesisCatalog?: readonly ProsthesisCatalogEntry[];
};

const CELL = 42;
const ARCH_H = 72;
const GAP = 10;

/**
 * PDF-safe FDI preview: only hex/rgb colors (no Tailwind / CSS variables).
 * html2canvas cannot parse modern `lab()` / `oklch()` from app stylesheets.
 */
export function CaseSheetFdiChart({
  selected,
  connectedTeeth,
  prosthesisRows,
  prosthesisCatalog,
}: CaseSheetFdiChartProps) {
  const colors: Partial<Record<FdiToothId, string>> = {};
  prosthesisRows.forEach((row, index) => {
    const color = prosthesisCatalog?.length
      ? prosthesisTypeColorFromCatalog(row.prosthesisTypeCode, prosthesisCatalog)
      : prosthesisTypeColor(row.prosthesisTypeCode, index);
    for (const tooth of row.teeth) {
      colors[tooth as FdiToothId] = color;
    }
  });

  const width = FDI_UPPER_LEFT_TO_RIGHT.length * CELL;
  const height = ARCH_H * 2 + GAP;
  const midX = width / 2;
  const midY = ARCH_H + GAP / 2;

  return (
    <svg
      width="100%"
      viewBox={`0 0 ${width} ${height}`}
      style={{ display: 'block', maxWidth: '100%', height: 'auto' }}
    >
      {/* Vertical midline (left/right quadrants) */}
      <line
        x1={midX}
        y1={4}
        x2={midX}
        y2={height - 4}
        stroke="#cbd5e1"
        strokeWidth={1}
      />
      {/* Horizontal separator (upper/lower arches) */}
      <line
        x1={4}
        y1={midY}
        x2={width - 4}
        y2={midY}
        stroke="#cbd5e1"
        strokeWidth={1}
      />

      <ArchRow
        teeth={FDI_UPPER_LEFT_TO_RIGHT}
        selected={selected}
        connectedTeeth={connectedTeeth}
        colors={colors}
        connectedMarksBelow
        yOffset={0}
      />
      <ArchRow
        teeth={FDI_LOWER_LEFT_TO_RIGHT}
        selected={selected}
        connectedTeeth={connectedTeeth}
        colors={colors}
        connectedMarksBelow={false}
        yOffset={ARCH_H + GAP}
      />
    </svg>
  );
}

function ArchRow({
  teeth,
  selected,
  connectedTeeth,
  colors,
  connectedMarksBelow,
  yOffset,
}: {
  teeth: readonly FdiToothId[];
  selected: ReadonlySet<FdiToothId>;
  connectedTeeth: ReadonlySet<FdiToothId>;
  colors: Partial<Record<FdiToothId, string>>;
  connectedMarksBelow: boolean;
  yOffset: number;
}) {
  return (
    <g transform={`translate(0 ${yOffset})`}>
      {teeth.map((fdi, index) => {
        const x = index * CELL + CELL / 2;
        const isSelected = selected.has(fdi);
        const isConnected = connectedTeeth.has(fdi);
        const next = teeth[index + 1];
        const linkToNext = Boolean(
          isConnected && next && connectedTeeth.has(next) && selected.has(next),
        );
        const fill = isSelected ? (colors[fdi] ?? '#94a3b8') : '#f8fafc';
        const stroke = isSelected ? '#334155' : '#cbd5e1';
        const cy = connectedMarksBelow ? 28 : 44;
        const markY = connectedMarksBelow ? 58 : 14;

        return (
          <g key={fdi}>
            {linkToNext ? (
              <line
                x1={x}
                y1={markY}
                x2={x + CELL}
                y2={markY}
                stroke="#64748b"
                strokeWidth={2}
                strokeLinecap="round"
              />
            ) : null}
            <rect
              x={x - 14}
              y={cy - 16}
              width={28}
              height={32}
              rx={6}
              fill={fill}
              stroke={stroke}
              strokeWidth={1.5}
            />
            <text
              x={x}
              y={cy + 4}
              textAnchor="middle"
              fontSize={11}
              fontFamily="system-ui, sans-serif"
              fill="#0f172a"
              fontWeight={isSelected ? 600 : 400}
            >
              {fdi}
            </text>
            {linkToNext ? (
              <circle cx={x + CELL / 2} cy={markY} r={3.5} fill="#475569" />
            ) : null}
          </g>
        );
      })}
    </g>
  );
}
