"use client";

import { useTranslations } from "next-intl";
import { useState, useTransition } from "react";
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { updateProfile } from "@/lib/actions/profile";

export function ProfileForm({ defaultName, email }: { defaultName: string; email: string }) {
  const t = useTranslations("Settings.profile");
  const [name, setName] = useState(defaultName);
  const [isPending, startTransition] = useTransition();

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const trimmed = name.trim();
    if (!trimmed || trimmed === defaultName) return;
    startTransition(async () => {
      try {
        await updateProfile({ name: trimmed });
        toast.success(t("saveSuccess"));
      } catch {
        toast.error(t("saveFailed"));
      }
    });
  }

  return (
    <form onSubmit={onSubmit} className="flex max-w-md flex-col gap-4">
      <div className="flex flex-col gap-2">
        <Label htmlFor="profile-name">{t("nameLabel")}</Label>
        <Input
          id="profile-name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder={t("namePlaceholder")}
          required
        />
      </div>
      <div className="flex flex-col gap-2">
        <Label htmlFor="profile-email">{t("emailLabel")}</Label>
        <Input id="profile-email" value={email} disabled />
        <p className="text-xs text-muted-foreground">{t("emailHelper")}</p>
      </div>
      <div>
        <Button type="submit" disabled={isPending || !name.trim() || name.trim() === defaultName}>
          {isPending ? t("submitting") : t("submit")}
        </Button>
      </div>
    </form>
  );
}
