"use client";

import { useState, useEffect, useTransition } from "react";
import { useRouter } from "next/navigation";
import { startTimer, startTimerForClient, stopTimer } from "@/app/admin/timer-actions";

function formatDuration(seconds: number): string {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  const s = seconds % 60;
  if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
  return `${m}:${String(s).padStart(2, "0")}`;
}

export function TimerCell({
  clientId,
  projectId,
  activeEntryId,
  activeStartedAt,
  totalTrackedSeconds,
}: {
  clientId: string;
  projectId?: string;
  activeEntryId: string | null;
  activeStartedAt: Date | null;
  totalTrackedSeconds: number;
}) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const isRunning = activeEntryId !== null;

  // Live elapsed counter
  const [elapsed, setElapsed] = useState(() => {
    if (!activeStartedAt) return 0;
    return Math.round((Date.now() - new Date(activeStartedAt).getTime()) / 1000);
  });

  useEffect(() => {
    if (!isRunning) { setElapsed(0); return; }
    const start = activeStartedAt ? new Date(activeStartedAt).getTime() : Date.now();
    const tick = () => setElapsed(Math.round((Date.now() - start) / 1000));
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [isRunning, activeStartedAt]);

  function handleToggle() {
    startTransition(async () => {
      if (isRunning && activeEntryId) {
        await stopTimer(activeEntryId);
      } else if (projectId) {
        await startTimer(projectId);
      } else {
        await startTimerForClient(clientId);
      }
      router.refresh();
    });
  }

  const displayTotal = formatDuration(totalTrackedSeconds + (isRunning ? elapsed : 0));

  return (
    <div
      className={`inline-flex items-center gap-2 rounded-full border pl-2 pr-3 py-1 text-xs font-mono tabular-nums transition-colors ${
        isRunning
          ? "bg-emerald-50/60 border-emerald-100 text-emerald-800 dark:bg-emerald-950/30 dark:border-emerald-900 dark:text-emerald-300 font-semibold"
          : "bg-muted border-border text-muted-foreground"
      }`}
    >
      <button
        onClick={handleToggle}
        title={isRunning ? "Ferma timer" : "Avvia timer"}
        className={`w-5 h-5 rounded-full flex items-center justify-center transition-colors shrink-0 ${
          isRunning
            ? "bg-emerald-500 text-white hover:bg-emerald-600"
            : "bg-foreground/10 text-foreground hover:bg-foreground/20"
        }`}
      >
        {isRunning ? (
          // Pause bars
          <svg className="w-2.5 h-2.5" fill="currentColor" viewBox="0 0 16 16">
            <rect x="4" y="3" width="3" height="10" rx="1" />
            <rect x="9" y="3" width="3" height="10" rx="1" />
          </svg>
        ) : (
          // Play triangle
          <svg className="w-2.5 h-2.5" fill="currentColor" viewBox="0 0 16 16">
            <path d="M4 3.5v9l9-4.5-9-4.5z" />
          </svg>
        )}
      </button>

      {isRunning ? formatDuration(elapsed) : displayTotal}
    </div>
  );
}