"use client";

import { BASE_PATH } from "@/lib/config";
import { useEffect, useState } from "react";
import { format } from "date-fns";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function QuickEntryForm({ onClose }: { onClose: () => void }) {
  const [clients, setClients] = useState<any[]>([]);
  const [clientId, setClientId] = useState("");
  const [description, setDescription] = useState("");
  const [date, setDate] = useState(format(new Date(), "yyyy-MM-dd"));
  const [startTime, setStartTime] = useState("09:00");
  const [endTime, setEndTime] = useState("10:00");
  const [hourlyRate, setHourlyRate] = useState("");
  const [loading, setLoading] = useState(false);

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

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!clientId) return;
    setLoading(true);
    const start = new Date(`${date}T${startTime}`).toISOString();
    const end = new Date(`${date}T${endTime}`).toISOString();
    const client = clients.find((c) => c.id === clientId);
    const rate = Number(hourlyRate) || client?.defaultHourlyRate || 50;
    const res = await fetch(`${BASE_PATH}/api/entries`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ clientId, description, startTime: start, endTime: end, hourlyRate: rate }),
    });
    setLoading(false);
    if (res.ok) {
      onClose();
      window.location.reload();
    } else {
      alert("Failed to add entry");
    }
  }

  return (
    <form onSubmit={submit} 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)}>
          <option value="">Select client</option>
          {clients.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      </div>
      <div>
        <Label>Description</Label>
        <Input value={description} onChange={(e) => setDescription(e.target.value)} placeholder="What did you work on?" className="mt-1 h-12 rounded-xl" />
      </div>
      <div className="grid grid-cols-3 gap-3">
        <div>
          <Label>Date</Label>
          <Input type="date" value={date} onChange={(e) => setDate(e.target.value)} className="mt-1 h-12 rounded-xl" />
        </div>
        <div>
          <Label>Start</Label>
          <Input type="time" value={startTime} onChange={(e) => setStartTime(e.target.value)} className="mt-1 h-12 rounded-xl" />
        </div>
        <div>
          <Label>End</Label>
          <Input type="time" value={endTime} onChange={(e) => setEndTime(e.target.value)} className="mt-1 h-12 rounded-xl" />
        </div>
      </div>
      <div>
        <Label>Hourly rate</Label>
        <Input type="number" value={hourlyRate} onChange={(e) => setHourlyRate(e.target.value)} placeholder={clients.find((c) => c.id === clientId)?.defaultHourlyRate || "75"} className="mt-1 h-12 rounded-xl" />
      </div>
      <Button type="submit" disabled={loading || !clientId} className="w-full rounded-full bg-primary py-6 hover:bg-primary/90">
        {loading ? "Saving..." : "Add Entry"}
      </Button>
    </form>
  );
}
