"use client";

import { BASE_PATH } from "@/lib/config";
import { useEffect, useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Play, Square, Pause } from "lucide-react";

export function TimerForm({ onClose }: { onClose: () => void }) {
  const [clients, setClients] = useState<any[]>([]);
  const [clientId, setClientId] = useState("");
  const [description, setDescription] = useState("");
  const [running, setRunning] = useState(false);
  const [elapsed, setElapsed] = useState(0);
  const [saving, setSaving] = useState(false);
  const startRef = useRef<string | null>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    fetch(`${BASE_PATH}/api/clients`)
      .then((r) => r.json())
      .then((d) => setClients(d.clients || []));
  }, []);

  useEffect(() => {
    if (running) {
      intervalRef.current = setInterval(() => {
        setElapsed((prev) => prev + 1);
      }, 1000);
    } else {
      if (intervalRef.current) clearInterval(intervalRef.current);
    }
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [running]);

  function start() {
    if (!clientId) return;
    startRef.current = new Date().toISOString();
    setRunning(true);
    setElapsed(0);
  }

  async function stop() {
    if (!startRef.current) return;
    setSaving(true);
    const endTime = new Date().toISOString();
    const res = await fetch(`${BASE_PATH}/api/entries`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        clientId,
        description,
        startTime: startRef.current,
        endTime,
      }),
    });
    setSaving(false);
    if (res.ok) {
      onClose();
      window.location.reload();
    } else {
      alert("Failed to save entry");
    }
  }

  function formatTime(totalSeconds: number) {
    const h = Math.floor(totalSeconds / 3600);
    const m = Math.floor((totalSeconds % 3600) / 60);
    const s = totalSeconds % 60;
    return `${h.toString().padStart(2, "0")}:${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
  }

  return (
    <div className="space-y-4">
      <div>
        <Label>Client</Label>
        <select
          className="mt-1 w-full rounded-xl border bg-background p-3"
          value={clientId}
          onChange={(e) => setClientId(e.target.value)}
          disabled={running}
        >
          <option value="">Select client</option>
          {clients.map((c: any) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </div>
      <div>
        <Label>What are you working on?</Label>
        <Input
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Design review, consulting, etc."
          disabled={running}
          className="mt-1 h-12 rounded-xl"
        />
      </div>
      <div className="flex flex-col items-center justify-center rounded-3xl bg-accent/30 py-8">
        <div className="font-mono text-5xl font-light text-primary">{formatTime(elapsed)}</div>
        <div className="mt-2 text-sm text-muted-foreground">{running ? "Timer running" : "Ready to start"}</div>
      </div>
      {!running ? (
        <Button onClick={start} disabled={!clientId} className="w-full rounded-full bg-primary py-6 text-lg hover:bg-primary/90">
          <Play className="mr-2 h-5 w-5" /> Start Timer
        </Button>
      ) : (
        <Button onClick={stop} disabled={saving} className="w-full rounded-full bg-accent py-6 text-lg text-accent-foreground hover:bg-accent/90">
          <Square className="mr-2 h-5 w-5" /> {saving ? "Saving..." : "Stop & Save"}
        </Button>
      )}
    </div>
  );
}
