"use client";

import { useActionState, useEffect, useMemo } from "react";
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 { changeOwnPasswordAction } from "@/server/actions/perfil";
import { toast } from "sonner";

export function PerfilPasswordForm() {
  const [state, formAction] = useActionState(changeOwnPasswordAction, initialState);

  const values = useMemo(
    () => ({
      currentPassword: typeof state.formValues?.currentPassword === "string" ? state.formValues.currentPassword : "",
      password: typeof state.formValues?.password === "string" ? state.formValues.password : "",
      confirmPassword: typeof state.formValues?.confirmPassword === "string" ? state.formValues.confirmPassword : "",
    }),
    [state.formValues?.confirmPassword, state.formValues?.currentPassword, state.formValues?.password],
  );

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

  return (
    <Card className="border-border shadow-sm">
      <CardHeader>
        <CardTitle>Seguridad</CardTitle>
      </CardHeader>
      <CardContent>
        <form key={state.formVersion ?? "initial"} action={formAction} className="grid gap-4 md:grid-cols-3">
          <Field label="Contraseña actual" name="currentPassword" type="password" value={values.currentPassword} error={state.errors?.currentPassword} />
          <Field label="Nueva contraseña" name="password" type="password" value={values.password} error={state.errors?.password} />
          <Field label="Confirmar nueva contraseña" name="confirmPassword" type="password" value={values.confirmPassword} error={state.errors?.confirmPassword} />
          <div className="md:col-span-3 flex justify-end">
            <Button type="submit">Cambiar contraseña</Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

function Field({
  label,
  name,
  type,
  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}
        autoComplete={name === "currentPassword" ? "current-password" : "new-password"}
      />
      {error?.[0] ? <p className="text-sm text-destructive">{error[0]}</p> : null}
    </div>
  );
}
