"use client";

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

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { updateNameAction } from "@/lib/appwrite/profile-actions";
import { initialProfileState } from "@/lib/appwrite/profile-types";

export function NameForm({ currentName }: { currentName: string }) {
  const [state, formAction, isPending] = useActionState(updateNameAction, initialProfileState);

  useEffect(() => {
    if (state.ok) toast.success("İsim güncellendi.");
    else if (state.error) toast.error(state.error);
  }, [state]);

  return (
    <Card>
      <CardHeader>
        <CardTitle>Görünür isim</CardTitle>
        <CardDescription>
          Header'da, davetlerde ve takım listesinde görünecek isim.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form action={formAction} className="grid gap-4 md:grid-cols-[1fr_auto] md:items-end">
          <div className="grid gap-2">
            <Label htmlFor="name">İsim</Label>
            <Input id="name" name="name" defaultValue={currentName} required maxLength={128} />
            {state.fieldErrors?.name && (
              <p className="text-destructive text-xs">{state.fieldErrors.name}</p>
            )}
          </div>
          <Button type="submit" disabled={isPending}>
            {isPending ? (
              <>
                <Loader2 className="size-4 animate-spin" />
                Kaydediliyor...
              </>
            ) : (
              <>
                <Save className="size-4" />
                Kaydet
              </>
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}
