"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { DataConsentField } from "@/components/forms/DataConsentField";
import { dataConsent } from "@/content/consent";
import type { InquiryIntent } from "@/lib/inquiry";

type Props = {
  intent: InquiryIntent;
  submitLabel?: string;
};

export function InquiryForm({ intent, submitLabel = "Send message" }: Props) {
  const [status, setStatus] = useState<"idle" | "loading" | "success" | "error">("idle");
  const [error, setError] = useState("");
  const [consent, setConsent] = useState(false);

  async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!consent) {
      setError(dataConsent.errorMessage);
      return;
    }

    setStatus("loading");
    setError("");

    const form = e.currentTarget;
    const data = new FormData(form);

    try {
      const res = await fetch("/api/inquiry", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          intent,
          name: data.get("name"),
          email: data.get("email"),
          company: data.get("company") || undefined,
          phone: data.get("phone") || undefined,
          message: data.get("message"),
          consent: true,
        }),
      });
      const json = await res.json();
      if (!res.ok || !json.ok) {
        throw new Error(json.error || "Something went wrong");
      }
      setStatus("success");
      form.reset();
      setConsent(false);
    } catch (err) {
      setStatus("error");
      setError(err instanceof Error ? err.message : "Failed to send");
    }
  }

  return (
    <form onSubmit={onSubmit} className="space-y-4">
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="space-y-2">
          <Label htmlFor={`${intent}-name`}>Name</Label>
          <Input id={`${intent}-name`} name="name" required placeholder="Your name" />
        </div>
        <div className="space-y-2">
          <Label htmlFor={`${intent}-email`}>Email</Label>
          <Input id={`${intent}-email`} name="email" type="email" required placeholder="you@company.com" />
        </div>
      </div>
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="space-y-2">
          <Label htmlFor={`${intent}-company`}>Company (optional)</Label>
          <Input id={`${intent}-company`} name="company" placeholder="Organization" />
        </div>
        <div className="space-y-2">
          <Label htmlFor={`${intent}-phone`}>Phone (optional)</Label>
          <Input id={`${intent}-phone`} name="phone" placeholder="+251 …" />
        </div>
      </div>
      <div className="space-y-2">
        <Label htmlFor={`${intent}-message`}>Message</Label>
        <Textarea
          id={`${intent}-message`}
          name="message"
          required
          rows={5}
          placeholder="Tell us about your interest…"
        />
      </div>
      <DataConsentField
        id={`${intent}-consent`}
        checked={consent}
        onCheckedChange={setConsent}
      />
      {error && <p className="text-sm text-destructive">{error}</p>}
      {status === "success" && (
        <p className="text-sm text-primary">Thank you! We received your inquiry and will be in touch.</p>
      )}
      <Button type="submit" variant="default" className="bg-accent text-accent-foreground hover:bg-accent/90" disabled={status === "loading"}>
        {status === "loading" ? "Sending…" : submitLabel}
      </Button>
    </form>
  );
}
