import React from "react";
import { cn } from "~/lib/utils";
import { DEFAULT_SCORING_RULES, type ScoringRules } from "~/lib/scoring-types";

export const OMNIFANTASY_SCORING: ScoringRules = {
  pointsFor1st: 80,
  pointsFor2nd: 50,
  pointsFor3rd: 30,
  pointsFor4th: 30,
  pointsFor5th: 20,
  pointsFor6th: 20,
  pointsFor7th: 20,
  pointsFor8th: 20,
};

export const PLACEMENT_LABELS = [
  { key: "pointsFor1st" as const, label: "1st", color: "text-yellow-500" },
  { key: "pointsFor2nd" as const, label: "2nd", color: "text-slate-400" },
  { key: "pointsFor3rd" as const, label: "3rd", color: "text-orange-400" },
  { key: "pointsFor4th" as const, label: "4th", color: "text-sky-400" },
  { key: "pointsFor5th" as const, label: "5th", color: "text-green-500" },
  { key: "pointsFor6th" as const, label: "6th", color: "text-green-500" },
  { key: "pointsFor7th" as const, label: "7th", color: "text-emerald-400" },
  { key: "pointsFor8th" as const, label: "8th", color: "text-emerald-400" },
];

export interface ScoringPresetPickerProps {
  preset: "brackt" | "omnifantasy" | "custom";
  onPresetChange: (v: "brackt" | "omnifantasy" | "custom") => void;
  rules: ScoringRules;
  onRulesChange: (r: ScoringRules) => void;
  disabled?: boolean;
}

export function ScoringPresetPicker({
  preset,
  onPresetChange,
  rules,
  onRulesChange,
  disabled,
}: ScoringPresetPickerProps) {
  const maxPoints = Math.max(...Object.values(rules));
  const PRESET_VALUES = ["brackt", "omnifantasy", "custom"] as const;

  function handleGroupKeyDown(e: React.KeyboardEvent<HTMLDivElement>) {
    if (disabled) return;
    if (!["ArrowDown", "ArrowRight", "ArrowUp", "ArrowLeft"].includes(e.key)) return;
    e.preventDefault();
    const idx = PRESET_VALUES.indexOf(preset);
    const next = e.key === "ArrowDown" || e.key === "ArrowRight"
      ? (idx + 1) % PRESET_VALUES.length
      : (idx - 1 + PRESET_VALUES.length) % PRESET_VALUES.length;
    const nextValue = PRESET_VALUES[next];
    if (nextValue !== "custom") applyPreset(nextValue);
    else onPresetChange("custom");
    e.currentTarget.querySelector<HTMLElement>(`[data-radio-value="${nextValue}"]`)?.focus();
  }

  function applyPreset(p: "brackt" | "omnifantasy") {
    onPresetChange(p);
    onRulesChange(p === "brackt" ? { ...DEFAULT_SCORING_RULES } : { ...OMNIFANTASY_SCORING });
  }

  function handleFieldChange(key: keyof ScoringRules, raw: string) {
    const val = parseInt(raw, 10);
    if (!isNaN(val) && val >= 0 && val <= 1000) {
      onPresetChange("custom");
      onRulesChange({ ...rules, [key]: val });
    }
  }

  return (
    <div className="space-y-4">
      {/* Preset tabs */}
      <div role="radiogroup" aria-label="Scoring preset" onKeyDown={handleGroupKeyDown} className="flex rounded-lg border border-border overflow-hidden">
        {(["brackt", "omnifantasy", "custom"] as const).map((p) => (
          <button
            key={p}
            type="button"
            role="radio"
            aria-checked={preset === p}
            tabIndex={preset === p ? 0 : -1}
            data-radio-value={p}
            disabled={disabled}
            onClick={() => p !== "custom" ? applyPreset(p) : onPresetChange("custom")}
            className={cn(
              "flex-1 py-2 text-sm font-medium transition-colors",
              preset === p
                ? "bg-primary text-primary-foreground"
                : "text-muted-foreground hover:bg-accent",
              disabled && "opacity-50 cursor-not-allowed"
            )}
          >
            {p === "brackt" ? "Brackt Default" : p === "omnifantasy" ? "Omnifantasy Default" : "Custom"}
          </button>
        ))}
      </div>

      {/* Placement fields */}
      <div className="space-y-3">
        {PLACEMENT_LABELS.map(({ key, label, color }) => {
          const val = rules[key];
          const barWidth = maxPoints > 0 ? (val / maxPoints) * 100 : 0;
          return (
            <div key={key} className="flex items-center gap-3">
              <span className={cn("text-sm font-medium w-8 shrink-0", color)}>{label}</span>
              <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
                <div
                  className="h-full bg-primary rounded-full transition-all duration-200"
                  style={{ width: `${barWidth}%` }}
                />
              </div>
              <label htmlFor={`scoring-${key}`} className="sr-only">Points for {label} place</label>
              <input
                id={`scoring-${key}`}
                type="number"
                value={val}
                disabled={disabled}
                onChange={(e) => handleFieldChange(key, e.target.value)}
                min={0}
                max={1000}
                className="w-14 h-8 text-center text-sm font-semibold border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none disabled:opacity-50"
              />
            </div>
          );
        })}
      </div>
    </div>
  );
}
