"use client";

import { BASE_PATH } from "@/lib/config";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

export function NewClientForm({ onClose }: { onClose: () => void }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [address, setAddress] = useState("");
  const [defaultHourlyRate, setDefaultHourlyRate] = useState("");
  const [loading, setLoading] = useState(false);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!name) return;
    setLoading(true);
    const res = await fetch(`${BASE_PATH}/api/clients`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name, email, address, defaultHourlyRate: Number(defaultHourlyRate) || undefined }),
    });
    setLoading(false);
    if (res.ok) {
      onClose();
      window.location.reload();
    } else {
      alert("Failed to add client");
    }
  }

  return (
    <form onSubmit={submit} className="space-y-4">
      <div>
        <Label>Client name</Label>
        <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Acme Corp" required className="mt-1 h-12 rounded-xl" />
      </div>
      <div>
        <Label>Email</Label>
        <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="billing@acme.com" className="mt-1 h-12 rounded-xl" />
      </div>
      <div>
        <Label>Address</Label>
        <Input value={address} onChange={(e) => setAddress(e.target.value)} placeholder="123 Business Rd" className="mt-1 h-12 rounded-xl" />
      </div>
      <div>
        <Label>Default hourly rate</Label>
        <Input type="number" value={defaultHourlyRate} onChange={(e) => setDefaultHourlyRate(e.target.value)} placeholder="75" className="mt-1 h-12 rounded-xl" />
      </div>
      <Button type="submit" disabled={loading || !name} className="w-full rounded-full bg-primary py-6 hover:bg-primary/90">
        {loading ? "Saving..." : "Add Client"}
      </Button>
    </form>
  );
}
