import { useState } from "react";
import type { AcBreakdown } from "../utils/derived-ac";
import styles from "./AcDisplay.module.css";

interface AcDisplayProps {
  breakdown: AcBreakdown;
  onOverride: (value: number | null) => void;
  mode?: "view" | "edit";
}

export default function AcDisplay({
  breakdown,
  onOverride,
  mode = "view",
}: AcDisplayProps) {
  const [editing, setEditing] = useState(false);
  const [editValue, setEditValue] = useState("");

  const isOverridden = breakdown.override !== null;

  function startEdit() {
    setEditValue(String(breakdown.effective));
    setEditing(true);
  }

  function commitEdit() {
    setEditing(false);
    const num = parseInt(editValue, 10);
    if (!isNaN(num) && num !== breakdown.calculated) {
      onOverride(num);
    } else if (num === breakdown.calculated) {
      onOverride(null);
    }
  }

  function handleKeyDown(e: React.KeyboardEvent) {
    if (e.key === "Enter") commitEdit();
    if (e.key === "Escape") setEditing(false);
  }

  return (
    <div className={styles.container}>
      <span className={styles.label}>AC</span>
      {mode === "edit" ? (
        editing ? (
          <input
            className={styles.editInput}
            type="number"
            value={editValue}
            onChange={(e) => setEditValue(e.target.value)}
            onBlur={commitEdit}
            onKeyDown={handleKeyDown}
            autoFocus
          />
        ) : (
          <span
            className={`${styles.value} ${isOverridden ? styles.overridden : ""}`}
            onClick={startEdit}
            title="Click to override"
          >
            {breakdown.effective}
          </span>
        )
      ) : (
        <span
          className={`${styles.value} ${isOverridden ? styles.overridden : ""}`}
        >
          {breakdown.effective}
        </span>
      )}
      {mode === "edit" && (
        <div>
          <div className={styles.source}>{breakdown.source}</div>
          {isOverridden && (
            <div className={styles.override}>
              <span className={styles.calculatedHint}>
                auto: {breakdown.calculated}
              </span>
              <button
                className={styles.overrideIndicator}
                onClick={() => onOverride(null)}
                title="Revert to auto-calculated"
              >
                revert
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
