"use client";

import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { CheckCircle2, Loader2 } from "lucide-react";
import { MOMENTS, statusFor, STATUS_STYLE, type Moment } from "@/lib/glycemia";

function suggestMomentForNow(): Moment {
  const h = new Date().getHours();
  if (h < 10) return "FASTING";
  if (h < 12) return "BEFORE_LUNCH";
  if (h < 15) return "AFTER_LUNCH";
  if (h < 19) return "BEFORE_DINNER";
  if (h < 21) return "AFTER_DINNER";
  if (h < 23) return "BEDTIME";
  return "OTHER";
}

function nowLocalDateTime(): string {
  const d = new Date();
  d.setMinutes(d.getMinutes() - d.getTimezoneOffset());
  return d.toISOString().slice(0, 16);
}

export function ReadingForm() {
  const router = useRouter();
  const [moment, setMoment] = useState<Moment>(suggestMomentForNow());
  const [valueStr, setValueStr] = useState("");
  const [measuredAt, setMeasuredAt] = useState(nowLocalDateTime());
  const [notes, setNotes] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

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

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setSuccess(false);

    if (numericValue === null || numericValue <= 0) {
      setError("Saisissez une valeur valide (ex : 1,12).");
      return;
    }
    if (numericValue > 6) {
      setError("Valeur trop élevée (>6 g/L). Vérifiez la saisie.");
      return;
    }

    setSubmitting(true);
    try {
      const res = await fetch("/api/readings", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          measuredAt: new Date(measuredAt).toISOString(),
          moment,
          value: numericValue,
          notes,
        }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error ?? "Erreur lors de l'enregistrement.");
      }
      setSuccess(true);
      setValueStr("");
      setNotes("");
      setMeasuredAt(nowLocalDateTime());
      setMoment(suggestMomentForNow());
      router.refresh();
      setTimeout(() => setSuccess(false), 2500);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Erreur inconnue");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5 rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
      {/* Moment */}
      <div>
        <label className="mb-2 block text-sm font-medium text-slate-700">Moment</label>
        <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">
          {MOMENTS.map((m) => (
            <button
              key={m.value}
              type="button"
              onClick={() => setMoment(m.value)}
              className={`rounded-lg border px-2 py-2.5 text-xs font-medium transition sm:text-sm ${
                moment === m.value
                  ? "border-teal-600 bg-teal-50 text-teal-800"
                  : "border-slate-200 bg-white text-slate-600 hover:border-slate-300"
              }`}
            >
              {m.short}
            </button>
          ))}
        </div>
      </div>

      {/* Value */}
      <div>
        <label htmlFor="value" className="mb-2 block text-sm font-medium text-slate-700">
          Glycémie (g/L)
        </label>
        <div className="flex items-center gap-3">
          <input
            id="value"
            type="text"
            inputMode="decimal"
            autoComplete="off"
            placeholder="1,12"
            value={valueStr}
            onChange={(e) => setValueStr(e.target.value)}
            className="w-full rounded-lg border border-slate-300 bg-white px-4 py-3 text-2xl font-semibold tracking-tight outline-none focus:border-teal-500 focus:ring-2 focus:ring-teal-200"
          />
          <span className="text-sm text-slate-500">g/L</span>
        </div>
        {liveStatus && (
          <div className="mt-2">
            <span
              className={`inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-medium ${STATUS_STYLE[liveStatus].bg} ${STATUS_STYLE[liveStatus].color} ${STATUS_STYLE[liveStatus].border}`}
            >
              {STATUS_STYLE[liveStatus].label}
            </span>
          </div>
        )}
      </div>

      {/* DateTime */}
      <div>
        <label htmlFor="measuredAt" className="mb-2 block text-sm font-medium text-slate-700">
          Date et heure
        </label>
        <input
          id="measuredAt"
          type="datetime-local"
          value={measuredAt}
          onChange={(e) => setMeasuredAt(e.target.value)}
          className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 outline-none focus:border-teal-500 focus:ring-2 focus:ring-teal-200"
        />
      </div>

      {/* Notes */}
      <div>
        <label htmlFor="notes" className="mb-2 block text-sm font-medium text-slate-700">
          Notes <span className="font-normal text-slate-400">(optionnel)</span>
        </label>
        <textarea
          id="notes"
          rows={3}
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          placeholder="Repas, activité, ressenti…"
          className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 outline-none focus:border-teal-500 focus:ring-2 focus:ring-teal-200"
        />
      </div>

      {error && (
        <div className="rounded-md border border-rose-300 bg-rose-50 px-3 py-2 text-sm text-rose-800">
          {error}
        </div>
      )}
      {success && (
        <div className="flex items-center gap-2 rounded-md border border-emerald-300 bg-emerald-50 px-3 py-2 text-sm text-emerald-800">
          <CheckCircle2 className="h-4 w-4" />
          Relevé enregistré.
        </div>
      )}

      <button
        type="submit"
        disabled={submitting}
        className="inline-flex w-full items-center justify-center gap-2 rounded-lg bg-teal-600 px-4 py-3 text-sm font-medium text-white shadow-sm hover:bg-teal-700 disabled:cursor-not-allowed disabled:opacity-60"
      >
        {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
        Enregistrer
      </button>
    </form>
  );
}
