"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";

type AcceptInvitationFormProps = {
  token: string;
  email: string;
  defaultName: string;
  departmentLabel: string;
  departmentRole: string;
  platformRoleLabel: string;
};

export default function AcceptInvitationForm({
  token,
  email,
  defaultName,
  departmentLabel,
  departmentRole,
  platformRoleLabel,
}: AcceptInvitationFormProps) {
  const router = useRouter();
  const [name, setName] = useState(defaultName);
  const [password, setPassword] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  return (
    <form
      className="mt-6 space-y-4 rounded-benell border border-benell-stroke bg-benell-surface p-5"
      onSubmit={async (event) => {
        event.preventDefault();
        setErrorMessage(null);
        setIsSubmitting(true);

        const response = await fetch("/api/invitations/accept", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            token,
            email,
            name,
            password,
          }),
        });

        const payload = (await response.json()) as { error?: string };
        setIsSubmitting(false);

        if (!response.ok) {
          setErrorMessage(payload.error ?? "No se pudo aceptar la invitacion.");
          return;
        }

        router.replace("/login");
      }}
    >
      <label className="block space-y-1">
        <span className="text-label font-semibold">Correo</span>
        <input
          type="email"
          value={email}
          readOnly
          className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 text-benell-text-soft"
        />
      </label>

      <div className="grid gap-4 sm:grid-cols-2">
        <label className="block space-y-1">
          <span className="text-label font-semibold">Departamento</span>
          <input
            type="text"
            value={departmentLabel}
            readOnly
            className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 text-benell-text-soft"
          />
        </label>
        <label className="block space-y-1">
          <span className="text-label font-semibold">Acceso en plataforma</span>
          <input
            type="text"
            value={platformRoleLabel}
            readOnly
            className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 text-benell-text-soft"
          />
        </label>
      </div>

      <label className="block space-y-1">
        <span className="text-label font-semibold">Rol dentro del departamento</span>
        <input
          type="text"
          value={departmentRole}
          readOnly
          className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 text-benell-text-soft"
        />
      </label>

      <label className="block space-y-1">
        <span className="text-label font-semibold">Nombre completo</span>
        <input
          type="text"
          value={name}
          onChange={(event) => setName(event.target.value)}
          className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
          required
        />
      </label>

      <label className="block space-y-1">
        <span className="text-label font-semibold">Contraseña</span>
        <input
          type="password"
          value={password}
          onChange={(event) => setPassword(event.target.value)}
          className="text-body w-full rounded-xl border border-benell-stroke bg-white px-3 py-2 outline-none focus-visible:ring-2 focus-visible:ring-benell-brown"
          minLength={8}
          required
        />
      </label>

      {errorMessage ? <p className="text-label text-benell-red">{errorMessage}</p> : null}

      <button
        type="submit"
        disabled={isSubmitting}
        className="text-body w-full rounded-pill bg-benell-brown py-3 font-semibold text-white"
      >
        {isSubmitting ? "Guardando..." : "Activar cuenta"}
      </button>
    </form>
  );
}
