"use client";

import { useActionState } from "react";
import { AlertCircle, Lock, Loader2 } from "lucide-react";
import { resetPassword, type ResetPasswordState } from "./actions";
import { Button } from "@/components/Button";

const initial: ResetPasswordState = { ok: false };

export function ResetPasswordForm({ token }: { token: string }) {
  const bound = resetPassword.bind(null, token);
  const [state, action, pending] = useActionState(bound, initial);
  return (
    <form action={action} className="space-y-5">
      {state.message && (
        <div
          role="alert"
          className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800"
        >
          <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
          <span>{state.message}</span>
        </div>
      )}
      <PasswordField
        name="password"
        label="New password"
        errors={state.fieldErrors?.password}
      />
      <PasswordField
        name="confirm"
        label="Confirm password"
        errors={state.fieldErrors?.confirm}
      />
      <Button type="submit" disabled={pending} className="w-full">
        {pending ? (
          <>
            <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
            Updating password…
          </>
        ) : (
          "Update password"
        )}
      </Button>
    </form>
  );
}

function PasswordField({
  name,
  label,
  errors,
}: {
  name: string;
  label: string;
  errors?: string[];
}) {
  return (
    <label className="block">
      <span className="mb-1.5 block text-sm font-semibold text-[var(--color-ink)]">
        {label}
      </span>
      <div className="relative">
        <Lock
          className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-slate)]"
          aria-hidden
        />
        <input
          name={name}
          type="password"
          required
          autoComplete="new-password"
          minLength={10}
          className="w-full rounded-md border border-[var(--color-line)] bg-white py-2.5 pl-9 pr-3 text-[var(--color-ink)] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-blue)]/20"
        />
      </div>
      {errors && errors.length > 0 && (
        <ul className="mt-1 list-disc pl-5 text-[12px] text-red-700">
          {errors.map((e) => (
            <li key={e}>{e}</li>
          ))}
        </ul>
      )}
    </label>
  );
}
