"use client";

import { useActionState, useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { initialState } from "@/server/actions/action-state";
import { updateOwnProfileAction } from "@/server/actions/perfil";
import type { getMyProfile } from "@/server/queries/perfil";
import { toast } from "sonner";

type ProfileData = Awaited<ReturnType<typeof getMyProfile>>;

export function PerfilAccountForm({ profile }: { profile: NonNullable<ProfileData> }) {
  const router = useRouter();
  const [state, formAction] = useActionState(updateOwnProfileAction, initialState);

  const values = useMemo(
    () => ({
      name: typeof state.formValues?.name === "string" ? state.formValues.name : profile.name,
      email: typeof state.formValues?.email === "string" ? state.formValues.email : profile.email,
    }),
    [profile.email, profile.name, state.formValues?.email, state.formValues?.name],
  );

  useEffect(() => {
    if (!state.message) return;
    if (state.success) {
      toast.success(state.message);
      router.refresh();
    } else {
      toast.error(state.message);
    }
  }, [router, state.message, state.success]);

  return (
    <Card className="border-border shadow-sm">
      <CardHeader>
        <CardTitle>Editar perfil</CardTitle>
      </CardHeader>
      <CardContent>
        <form key={state.formVersion ?? "initial"} action={formAction} className="grid gap-4 md:grid-cols-2">
          <Field label="Nombre" name="name" value={values.name} error={state.errors?.name} />
          <Field label="Correo" name="email" type="email" value={values.email} error={state.errors?.email} />
          <div className="md:col-span-2 flex justify-end">
            <Button type="submit">Guardar cambios</Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

function Field({
  label,
  name,
  type = "text",
  value,
  error,
}: {
  label: string;
  name: string;
  type?: string;
  value: string;
  error?: string[];
}) {
  return (
    <div className="space-y-2">
      <Label htmlFor={name}>{label}</Label>
      <Input id={name} name={name} type={type} defaultValue={value} />
      {error?.[0] ? <p className="text-sm text-destructive">{error[0]}</p> : null}
    </div>
  );
}
