"use client";

import { useActionState, useEffect } 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/configuracion";
import { toast } from "sonner";

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

  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>Cambiar contraseña propia</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" error={state.errors?.currentPassword} />
          <Field label="Nueva contraseña" name="password" type="password" error={state.errors?.password} />
          <Field label="Confirmar contraseña" name="confirmPassword" type="password" error={state.errors?.confirmPassword} />
          <div className="md:col-span-3 flex justify-end">
            <Button type="submit">Actualizar contraseña</Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

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