"use client";
import React from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { z } from "zod";
import { userSchema } from "@/lib/validation/zod/user";
import { User } from "next-auth";
import { updateUserProfile } from "@/server/actions/user";
import { toast } from "sonner";

function UserForm({ server_user, cb }: { server_user: User; cb?: () => void }) {
  const form = useForm<z.infer<typeof userSchema>>({
    resolver: zodResolver(userSchema),
    defaultValues: {
      name: server_user?.name ?? "",
    },
  });

  // 2. Define a submit handler.
  async function onSubmit(values: z.infer<typeof userSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    const { success } = await updateUserProfile(values);
    if (success) toast.success("Dein Profil wurde aktualisiert!");
    else toast.error("Etwas ist fehlgeschlagen. Bitte versuche es erneut.");
    cb?.();
    form.reset();
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Name</FormLabel>
              <FormControl>
                <div className="flex items-center gap-2">
                  <Input placeholder="Max Mustermann" {...field} />
                </div>
              </FormControl>
              <FormDescription>
                Dein Name ist für alle sichtbar.
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />

        <Button type="submit" disabled={!form.formState.isDirty}>
          Speichern
        </Button>
      </form>
    </Form>
  );
}

export default UserForm;
