"use client";

import { useCallback, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { format } from "date-fns";
import { fr } from "date-fns/locale";
import {
  CheckCircle2,
  ChevronLeft,
  ChevronRight,
  Delete,
  Droplets,
  Loader2,
} from "lucide-react";
import {
  MOMENT_LABELS,
  STATUS_STYLE,
  statusFor,
  type Moment,
} from "@/lib/glycemia";
import { cn } from "@/lib/utils";

type LastReading = { measuredAt: string; moment: string; value: number };

const MOMENTS: Moment[] = ["FASTING", "LUNCH", "DINNER"];
const MOMENT_SHORT: Record<Moment, string> = {
  FASTING: "Matin",
  LUNCH: "Midi",
  DINNER: "Soir",
};
const MOMENT_ICON: Record<Moment, string> = {
  FASTING: "🌅",
  LUNCH: "☀️",
  DINNER: "🌙",
};

function suggestMoment(): Moment {
  const h = new Date().getHours();
  if (h < 11) return "FASTING";
  if (h < 17) return "LUNCH";
  return "DINNER";
}

// Simple numpad keys
const PAD_KEYS = [
  ["1", "2", "3"],
  ["4", "5", "6"],
  ["7", "8", "9"],
  [".", "0", "⌫"],
];

export function MobileEntry({
  firstName,
  last3,
}: {
  firstName: string | null;
  last3: LastReading[];
}) {
  const router = useRouter();
  const [moment, setMoment] = useState<Moment>(suggestMoment());
  const [digits, setDigits] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState<{ value: number; moment: Moment } | null>(null);
  const [error, setError] = useState<string | null>(null);

  const momentIdx = MOMENTS.indexOf(moment);

  function prevMoment() {
    setMoment(MOMENTS[(momentIdx + MOMENTS.length - 1) % MOMENTS.length]);
  }
  function nextMoment() {
    setMoment(MOMENTS[(momentIdx + 1) % MOMENTS.length]);
  }

  function handleKey(key: string) {
    setError(null);
    if (key === "⌫") {
      setDigits((d) => d.slice(0, -1));
      return;
    }
    // Only one dot allowed
    if (key === "." && digits.includes(".")) return;
    // Max 4 chars total (e.g. "1.35")
    if (digits.replace(".", "").length >= 4) return;
    // Don't start with two zeros
    if (digits === "0" && key === "0") return;
    setDigits((d) => d + key);
  }

  const numericValue = useMemo(() => {
    const v = parseFloat(digits.replace(",", "."));
    return Number.isFinite(v) && v > 0 ? v : null;
  }, [digits]);

  const liveStatus = numericValue !== null ? statusFor(numericValue, moment) : null;

  async function handleSubmit() {
    if (!numericValue) {
      setError("Saisissez une valeur.");
      return;
    }
    if (numericValue > 6) {
      setError("Valeur trop élevée (> 6 g/L).");
      return;
    }

    setSubmitting(true);
    setError(null);
    try {
      const res = await fetch("/api/readings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ moment, value: numericValue }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error(d.error ?? "Erreur serveur");
      }
      setSuccess({ value: numericValue, moment });
      setDigits("");
      // Auto-advance to next moment
      setMoment(MOMENTS[(momentIdx + 1) % MOMENTS.length]);
      router.refresh();
      setTimeout(() => setSuccess(null), 3000);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur inconnue");
    } finally {
      setSubmitting(false);
    }
  }

  // Format display value nicely
  const displayValue = digits === "" ? "—" : digits + (digits.endsWith(".") ? "" : "");

  return (
    <div className="flex min-h-[calc(100dvh-0px)] flex-col bg-slate-50">
      {/* Top bar */}
      <div className="flex items-center justify-between bg-teal-600 px-4 py-3 text-white">
        <div className="flex items-center gap-2">
          <Droplets className="h-5 w-5 text-teal-200" />
          <span className="font-semibold">
            {firstName ? `Bonjour ${firstName}` : "Saisie rapide"}
          </span>
        </div>
        <span className="text-sm text-teal-200">
          {format(new Date(), "EEE d MMM", { locale: fr })}
        </span>
      </div>

      <div className="flex flex-1 flex-col gap-4 p-4">
        {/* Last 3 readings */}
        {last3.length > 0 && (
          <div className="flex gap-2 overflow-x-auto pb-1">
            {last3.map((r, i) => {
              const s = statusFor(r.value, r.moment as Moment);
              return (
                <div
                  key={i}
                  className={cn(
                    "flex min-w-[90px] flex-col items-center rounded-xl border px-3 py-2 text-center text-xs",
                    STATUS_STYLE[s].bg,
                    STATUS_STYLE[s].border,
                    STATUS_STYLE[s].color
                  )}
                >
                  <span className="text-base font-bold">
                    {r.value.toFixed(2).replace(".", ",")}
                  </span>
                  <span className="opacity-80">
                    {MOMENT_ICON[r.moment as Moment]} {MOMENT_SHORT[r.moment as Moment]}
                  </span>
                  <span className="opacity-60">
                    {format(new Date(r.measuredAt), "HH:mm")}
                  </span>
                </div>
              );
            })}
          </div>
        )}

        {/* Moment selector */}
        <div className="flex items-center justify-between rounded-2xl bg-white px-4 py-3 shadow-sm">
          <button
            type="button"
            onClick={prevMoment}
            className="rounded-full p-2 text-slate-400 hover:bg-slate-100 active:bg-slate-200"
          >
            <ChevronLeft className="h-5 w-5" />
          </button>
          <div className="text-center">
            <div className="text-2xl">{MOMENT_ICON[moment]}</div>
            <div className="text-sm font-semibold text-slate-800">{MOMENT_SHORT[moment]}</div>
            <div className="text-xs text-slate-500">{MOMENT_LABELS[moment]}</div>
          </div>
          <button
            type="button"
            onClick={nextMoment}
            className="rounded-full p-2 text-slate-400 hover:bg-slate-100 active:bg-slate-200"
          >
            <ChevronRight className="h-5 w-5" />
          </button>
        </div>

        {/* Value display */}
        <div
          className={cn(
            "flex flex-col items-center justify-center rounded-2xl px-4 py-5 shadow-sm transition-colors",
            liveStatus ? STATUS_STYLE[liveStatus].bg : "bg-white",
            liveStatus ? STATUS_STYLE[liveStatus].border : "border-transparent",
            "border-2"
          )}
        >
          <div
            className={cn(
              "text-5xl font-bold tabular-nums tracking-tight",
              liveStatus ? STATUS_STYLE[liveStatus].color : "text-slate-300"
            )}
          >
            {displayValue}
          </div>
          <div className="mt-1 text-sm text-slate-500">g/L</div>
          {liveStatus && (
            <span
              className={cn(
                "mt-2 rounded-full border px-3 py-0.5 text-xs font-medium",
                STATUS_STYLE[liveStatus].bg,
                STATUS_STYLE[liveStatus].border,
                STATUS_STYLE[liveStatus].color
              )}
            >
              {STATUS_STYLE[liveStatus].label}
            </span>
          )}
        </div>

        {/* Numpad */}
        <div className="grid grid-cols-3 gap-3">
          {PAD_KEYS.flat().map((key) => (
            <button
              key={key}
              type="button"
              onPointerDown={(e) => {
                e.preventDefault();
                handleKey(key);
              }}
              className={cn(
                "flex h-16 items-center justify-center rounded-2xl text-xl font-semibold shadow-sm active:scale-95 transition-transform select-none",
                key === "⌫"
                  ? "bg-slate-200 text-slate-600"
                  : key === "."
                    ? "bg-white text-slate-700"
                    : "bg-white text-slate-900"
              )}
            >
              {key === "⌫" ? <Delete className="h-5 w-5" /> : key}
            </button>
          ))}
        </div>

        {/* Error */}
        {error && (
          <div className="rounded-xl border border-rose-300 bg-rose-50 px-4 py-3 text-center text-sm text-rose-800">
            {error}
          </div>
        )}

        {/* Success */}
        {success && (
          <div className="flex items-center justify-center gap-2 rounded-xl border border-emerald-300 bg-emerald-50 px-4 py-3 text-sm font-medium text-emerald-800">
            <CheckCircle2 className="h-5 w-5" />
            {success.value.toFixed(2).replace(".", ",")} g/L enregistré —{" "}
            {MOMENT_SHORT[success.moment]}
          </div>
        )}

        {/* Submit */}
        <button
          type="button"
          onClick={handleSubmit}
          disabled={!numericValue || submitting}
          className={cn(
            "flex h-16 w-full items-center justify-center gap-2 rounded-2xl text-lg font-semibold text-white shadow-md transition active:scale-95",
            numericValue
              ? "bg-teal-600 hover:bg-teal-700"
              : "cursor-not-allowed bg-slate-300"
          )}
        >
          {submitting ? (
            <Loader2 className="h-5 w-5 animate-spin" />
          ) : (
            "Enregistrer"
          )}
        </button>
      </div>
    </div>
  );
}
