"use client";

import { useEffect, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { clockInAction, clockOutAction } from "@/lib/actions/timeEntries";

// clockInSince kommt als ISO-String (Server Component kann kein Date direkt
// an eine Client Component durchreichen) - null, wenn gerade nicht
// eingestempelt.
export function ClockInOutPanel({ clockInSince }: { clockInSince: string | null }) {
  const router = useRouter();
  const [pending, startTransition] = useTransition();
  const [error, setError] = useState<string | null>(null);
  // Nur für die Live-Anzeige "seit X:XX (Y Std. Z Min.)" - läuft rein lokal,
  // löst keinen Server-Roundtrip aus.
  const [now, setNow] = useState(() => Date.now());

  useEffect(() => {
    if (!clockInSince) return;
    const id = setInterval(() => setNow(Date.now()), 30_000);
    return () => clearInterval(id);
  }, [clockInSince]);

  const since = clockInSince ? new Date(clockInSince) : null;
  const elapsedMinutes = since ? Math.max(0, Math.floor((now - since.getTime()) / 60_000)) : 0;

  function handleToggle() {
    setError(null);
    startTransition(async () => {
      const result = since ? await clockOutAction() : await clockInAction();
      if (result.error) setError(result.error);
      else router.refresh();
    });
  }

  return (
    <div className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 flex flex-col gap-3">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] mb-1">Meine Zeiterfassung</p>
          {since ? (
            <p className="text-sm text-[var(--rk-ink)]">
              Eingestempelt seit{" "}
              {since.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" })} ·{" "}
              {Math.floor(elapsedMinutes / 60)} Std. {elapsedMinutes % 60} Min.
            </p>
          ) : (
            <p className="text-sm text-[var(--rk-ink-muted)]">Nicht eingestempelt.</p>
          )}
        </div>
        <button
          type="button"
          disabled={pending}
          onClick={handleToggle}
          className={`rounded-lg px-5 py-2.5 text-xs font-semibold uppercase tracking-[0.15em] transition-opacity disabled:opacity-50 ${
            since ? "border border-red-400/40 text-red-400 hover:border-red-400" : "bg-[var(--rk-accent)] text-[#141413] hover:opacity-90"
          }`}
        >
          {since ? "Ausstempeln" : "Einstempeln"}
        </button>
      </div>
      {error && <p className="text-xs text-red-400">{error}</p>}
    </div>
  );
}
