"use client";

import * as React from "react";

import { cn } from "@/lib/utils";

// FDI Two-Digit Notation, permanent dentition (32 teeth).
// Quadrants:
//   Upper Right (1):  18 17 16 15 14 13 12 11
//   Upper Left  (2):  21 22 23 24 25 26 27 28
//   Lower Left  (3):  31 32 33 34 35 36 37 38
//   Lower Right (4):  48 47 46 45 44 43 42 41
const UPPER_RIGHT = ["18", "17", "16", "15", "14", "13", "12", "11"];
const UPPER_LEFT = ["21", "22", "23", "24", "25", "26", "27", "28"];
const LOWER_LEFT = ["31", "32", "33", "34", "35", "36", "37", "38"];
const LOWER_RIGHT = ["48", "47", "46", "45", "44", "43", "42", "41"];

export function TeethChart({
  value,
  onChange,
  name = "teeth",
  disabled = false,
}: {
  value: string[];
  onChange: (next: string[]) => void;
  name?: string;
  disabled?: boolean;
}) {
  const selected = React.useMemo(() => new Set(value), [value]);

  const toggle = (tooth: string) => {
    if (disabled) return;
    const next = new Set(selected);
    if (next.has(tooth)) next.delete(tooth);
    else next.add(tooth);
    // Preserve canonical order for serialisation.
    onChange(
      [...UPPER_RIGHT, ...UPPER_LEFT, ...LOWER_RIGHT, ...LOWER_LEFT].filter((t) => next.has(t)),
    );
  };

  return (
    <div className="bg-muted/30 rounded-md border p-4">
      {/* Hidden form fields — submitted as repeated name="teeth" entries */}
      {value.map((t) => (
        <input key={t} type="hidden" name={name} value={t} />
      ))}

      <p className="text-muted-foreground mb-3 flex items-center justify-between text-xs">
        <span>Sağ ←</span>
        <span className="font-medium uppercase tracking-wide">Üst Çene</span>
        <span>→ Sol</span>
      </p>
      <div className="grid grid-cols-[repeat(16,minmax(0,1fr))] gap-1.5">
        {UPPER_RIGHT.map((t) => (
          <ToothButton
            key={t}
            tooth={t}
            selected={selected.has(t)}
            onClick={() => toggle(t)}
            disabled={disabled}
          />
        ))}
        {UPPER_LEFT.map((t) => (
          <ToothButton
            key={t}
            tooth={t}
            selected={selected.has(t)}
            onClick={() => toggle(t)}
            disabled={disabled}
          />
        ))}
      </div>

      <div className="bg-border my-3 h-px" aria-hidden />

      <div className="grid grid-cols-[repeat(16,minmax(0,1fr))] gap-1.5">
        {LOWER_RIGHT.map((t) => (
          <ToothButton
            key={t}
            tooth={t}
            selected={selected.has(t)}
            onClick={() => toggle(t)}
            disabled={disabled}
          />
        ))}
        {LOWER_LEFT.map((t) => (
          <ToothButton
            key={t}
            tooth={t}
            selected={selected.has(t)}
            onClick={() => toggle(t)}
            disabled={disabled}
          />
        ))}
      </div>
      <p className="text-muted-foreground mt-3 flex items-center justify-between text-xs">
        <span>Sağ ←</span>
        <span className="font-medium uppercase tracking-wide">Alt Çene</span>
        <span>→ Sol</span>
      </p>

      <div className="text-muted-foreground mt-4 flex flex-wrap items-baseline justify-between gap-2 text-xs">
        <span>FDI iki haneli numaralama · {value.length} diş seçili</span>
        {value.length > 0 && !disabled && (
          <button
            type="button"
            onClick={() => onChange([])}
            className="hover:text-foreground underline-offset-4 hover:underline"
          >
            Temizle
          </button>
        )}
      </div>
    </div>
  );
}

function ToothButton({
  tooth,
  selected,
  onClick,
  disabled,
}: {
  tooth: string;
  selected: boolean;
  onClick: () => void;
  disabled: boolean;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      aria-pressed={selected}
      aria-label={`Diş ${tooth}`}
      className={cn(
        "flex aspect-square items-center justify-center rounded-md border text-[10px] font-medium tabular-nums transition-colors",
        selected
          ? "border-primary bg-primary text-primary-foreground"
          : "border-input bg-background hover:bg-accent hover:text-accent-foreground",
        disabled && "cursor-not-allowed opacity-60",
      )}
    >
      {tooth}
    </button>
  );
}
