"use client";

import { useTransition } from "react";
import { Loader2, Save } from "lucide-react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { updateMyContact } from "../actions";

type ContactFormProps = {
  contact: {
    phone: string | null;
    street: string | null;
    postalCode: string | null;
    city: string | null;
  };
};

export function ContactForm({ contact }: ContactFormProps) {
  const [isPending, startTransition] = useTransition();

  function handleSubmit(formData: FormData) {
    startTransition(async () => {
      const result = await updateMyContact({
        phone: String(formData.get("phone") ?? ""),
        street: String(formData.get("street") ?? ""),
        postalCode: String(formData.get("postalCode") ?? ""),
        city: String(formData.get("city") ?? ""),
      });

      if (result.error) {
        toast.error(result.error);
        return;
      }

      toast.success("Kontaktdaten gespeichert.");
    });
  }

  return (
    <form action={handleSubmit} className="grid gap-4">
      <div className="grid gap-2">
        <Label htmlFor="phone">Telefonnummer</Label>
        <Input
          id="phone"
          name="phone"
          type="tel"
          defaultValue={contact.phone ?? ""}
          placeholder="+49 30 123456"
        />
      </div>

      <div className="grid gap-2">
        <Label htmlFor="street">Straße und Hausnummer</Label>
        <Input
          id="street"
          name="street"
          defaultValue={contact.street ?? ""}
          placeholder="Beispielweg 12"
        />
      </div>

      <div className="grid gap-3 sm:grid-cols-[120px_1fr]">
        <div className="grid gap-2">
          <Label htmlFor="postalCode">PLZ</Label>
          <Input
            id="postalCode"
            name="postalCode"
            defaultValue={contact.postalCode ?? ""}
            placeholder="10115"
          />
        </div>
        <div className="grid gap-2">
          <Label htmlFor="city">Ort</Label>
          <Input
            id="city"
            name="city"
            defaultValue={contact.city ?? ""}
            placeholder="Berlin"
          />
        </div>
      </div>

      <div className="flex justify-end">
        <Button type="submit" disabled={isPending}>
          {isPending ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Save className="h-4 w-4" />
          )}
          Speichern
        </Button>
      </div>
    </form>
  );
}
