"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

type BillingDetails = {
  fullName?: string | null;
  addressLine1?: string | null;
  addressLine2?: string | null;
  city?: string | null;
  postalCode?: string | null;
  country?: string | null;
  phone?: string | null;
};

export function BillingDetailsForm({ initialDetails }: { initialDetails: BillingDetails | null }) {
  const t = useTranslations("settingsForm");
  const [details, setDetails] = useState<BillingDetails>(initialDetails ?? {});
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(false);

  function setField(field: keyof BillingDetails, value: string) {
    setDetails((prev) => ({ ...prev, [field]: value }));
  }

  async function handleSave() {
    if (!details.fullName?.trim()) {
      setError(true);
      return;
    }
    setError(false);
    setSaving(true);
    try {
      const res = await fetch("/api/v1/users/me/billing-details", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(details),
      });
      if (!res.ok) throw new Error("Save failed");
      toast.success(t("billingDetailsSaved"));
    } catch {
      toast.error(t("billingDetailsSaveFailed"));
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="space-y-4">
      <div className="space-y-1.5">
        <Label htmlFor="billing-full-name">
          {t("billingFullName")} <span className="text-destructive">*</span>
        </Label>
        <Input
          id="billing-full-name"
          value={details.fullName ?? ""}
          onChange={(e) => setField("fullName", e.target.value)}
          aria-invalid={error || undefined}
        />
        {error && <p className="text-xs text-destructive">{t("billingFullNameRequired")}</p>}
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="col-span-2 space-y-1.5">
          <Label htmlFor="billing-address-1">{t("billingAddressLine1")}</Label>
          <Input id="billing-address-1" value={details.addressLine1 ?? ""} onChange={(e) => setField("addressLine1", e.target.value)} />
        </div>
        <div className="col-span-2 space-y-1.5">
          <Label htmlFor="billing-address-2">{t("billingAddressLine2")}</Label>
          <Input id="billing-address-2" value={details.addressLine2 ?? ""} onChange={(e) => setField("addressLine2", e.target.value)} />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="billing-city">{t("billingCity")}</Label>
          <Input id="billing-city" value={details.city ?? ""} onChange={(e) => setField("city", e.target.value)} />
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="billing-postal-code">{t("billingPostalCode")}</Label>
          <Input id="billing-postal-code" value={details.postalCode ?? ""} onChange={(e) => setField("postalCode", e.target.value)} />
        </div>
        <div className="col-span-2 space-y-1.5">
          <Label htmlFor="billing-country">{t("billingCountry")}</Label>
          <Input id="billing-country" value={details.country ?? ""} onChange={(e) => setField("country", e.target.value)} />
        </div>
        <div className="col-span-2 space-y-1.5">
          <Label htmlFor="billing-phone">{t("billingPhone")}</Label>
          <Input id="billing-phone" type="tel" value={details.phone ?? ""} onChange={(e) => setField("phone", e.target.value)} />
        </div>
      </div>

      <Button onClick={() => { void handleSave(); }} disabled={saving} size="sm">
        {saving ? t("billingDetailsSaving") : t("saveBillingDetails")}
      </Button>
    </div>
  );
}
