"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { addManualTimeEntry, deleteTimeEntry } from "@/app/admin/timer-actions";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type TimeEntry = {
  id: string;
  started_at: Date;
  ended_at: Date | null;
  duration_seconds: number | null;
};

function formatDuration(seconds: number | null): string {
  if (!seconds) return "0 min";
  const h = Math.floor(seconds / 3600);
  const m = Math.floor((seconds % 3600) / 60);
  if (h > 0) return `${h}h ${m}min`;
  return `${m} min`;
}

function formatDate(date: Date): string {
  return new Date(date).toLocaleDateString("it-IT", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

type Props = {
  projectId: string;
  recentEntries: TimeEntry[];
};

export function ManualTimeEntry({ projectId, recentEntries }: Props) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [minutes, setMinutes] = useState("");
  const [date, setDate] = useState(() => new Date().toISOString().split("T")[0]);
  const [loading, setLoading] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);

  async function handleQuickAdd(mins: number) {
    setLoading(true);
    try {
      const startedAt = new Date(`${date}T09:00:00`).toISOString();
      await addManualTimeEntry(projectId, mins, startedAt);
      startTransition(() => router.refresh());
    } finally {
      setLoading(false);
    }
  }

  async function handleCustomAdd(e: React.FormEvent) {
    e.preventDefault();
    const mins = parseFloat(minutes);
    if (!mins || mins <= 0) return;
    setLoading(true);
    try {
      const startedAt = new Date(`${date}T09:00:00`).toISOString();
      await addManualTimeEntry(projectId, mins, startedAt);
      setMinutes("");
      startTransition(() => router.refresh());
    } finally {
      setLoading(false);
    }
  }

  async function handleDelete(entryId: string) {
    setDeletingId(entryId);
    try {
      await deleteTimeEntry(entryId, projectId);
      startTransition(() => router.refresh());
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <div className="bg-white rounded-lg border border-[#e5e7eb] p-4 space-y-4">
      <h3 className="font-medium text-[#1a1a1a]">Aggiungi tempo manuale</h3>

      {/* Data */}
      <div className="space-y-1">
        <Label htmlFor="entry-date">Data</Label>
        <Input
          id="entry-date"
          type="date"
          value={date}
          onChange={(e) => setDate(e.target.value)}
          className="max-w-[180px]"
        />
      </div>

      {/* Quick buttons */}
      <div>
        <p className="text-xs text-[#71717a] mb-2">Aggiunte rapide</p>
        <div className="flex gap-2">
          <Button
            type="button"
            size="sm"
            variant="outline"
            disabled={loading}
            onClick={() => handleQuickAdd(30)}
          >
            +30 min
          </Button>
          <Button
            type="button"
            size="sm"
            variant="outline"
            disabled={loading}
            onClick={() => handleQuickAdd(60)}
          >
            +60 min
          </Button>
        </div>
      </div>

      {/* Custom minutes */}
      <form onSubmit={handleCustomAdd} className="flex items-end gap-2">
        <div className="space-y-1 flex-1">
          <Label htmlFor="manual-minutes">Minuti personalizzati</Label>
          <Input
            id="manual-minutes"
            type="number"
            min="1"
            step="1"
            placeholder="es. 45"
            value={minutes}
            onChange={(e) => setMinutes(e.target.value)}
            className="max-w-[120px]"
          />
        </div>
        <Button type="submit" size="sm" disabled={loading || !minutes}>
          Aggiungi
        </Button>
      </form>

      {/* Recent entries */}
      {recentEntries.length > 0 && (
        <div>
          <p className="text-xs text-[#71717a] mb-2 font-medium">Ultime registrazioni</p>
          <ul className="space-y-1.5">
            {recentEntries.map((entry) => (
              <li
                key={entry.id}
                className="flex items-center justify-between gap-2 bg-[#f9f9f9] rounded px-3 py-2"
              >
                <div className="min-w-0">
                  <p className="text-xs font-medium text-[#1a1a1a]">
                    {formatDuration(entry.duration_seconds)}
                  </p>
                  <p className="text-xs text-[#71717a]">{formatDate(entry.started_at)}</p>
                </div>
                <button
                  type="button"
                  disabled={deletingId === entry.id}
                  onClick={() => handleDelete(entry.id)}
                  className="text-[#999999] hover:text-red-500 transition-colors shrink-0 text-xs"
                  aria-label="Elimina registrazione"
                >
                  {deletingId === entry.id ? "..." : "✕"}
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
