"use client";

import { useState } from "react";
import { useSession } from "next-auth/react";
import type { DepartmentKey, UserRole } from "@/lib/types";
import { DEPARTMENT_OPTIONS, getDepartmentLabel } from "@/lib/departments";
import { canInviteUsers, getAssignableRoles } from "@/lib/roles";
import { ROLE_LABELS } from "@/lib/utils";

const roleOptions: UserRole[] = ["owner", "leader", "employee"];

export default function InviteUserPanel() {
  const { data: session } = useSession();
  const [inviteeName, setInviteeName] = useState("");
  const [email, setEmail] = useState("");
  const [department, setDepartment] = useState<(typeof DEPARTMENT_OPTIONS)[number]["value"]>("marketing");
  const [departmentRole, setDepartmentRole] = useState("");
  const [roleKey, setRoleKey] = useState<UserRole>("employee");
  const [message, setMessage] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const sessionRole = session?.user?.role as UserRole | undefined;
  const sessionDepartment = (session?.user?.department as DepartmentKey | null | undefined) ?? null;
  const allowedRoles = getAssignableRoles(sessionRole);
  const canInvite = canInviteUsers(sessionRole);
  const isOwner = sessionRole === "owner";
  const leaderWithoutDepartment = sessionRole === "leader" && !sessionDepartment;
  const isDisabled = !canInvite || leaderWithoutDepartment;
  const targetDepartment = isOwner ? department : sessionDepartment ?? "marketing";

  return (
    <section className="rounded-benell border border-benell-stroke bg-benell-surface p-5 shadow-benell">
      <h2 className="text-h2 font-semibold">Invitar usuario</h2>
      <p className="text-body mt-2 text-benell-text-soft">
        Envía invitaciones con departamento, rol del área y nivel de acceso.
      </p>

      <form
        className="mt-5 grid gap-3 md:grid-cols-2"
        onSubmit={async (event) => {
          event.preventDefault();
          setMessage(null);
          setIsSubmitting(true);

          const response = await fetch("/api/invitations", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ inviteeName, email, department: targetDepartment, departmentRole, roleKey }),
          });

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

          if (!response.ok) {
            setMessage(payload.error ?? "No se pudo enviar la invitación.");
            return;
          }

          setInviteeName("");
          setEmail("");
          setDepartment("marketing");
          setDepartmentRole("");
          setRoleKey("employee");
          setMessage(`Invitación enviada (id: ${payload.invitationId}).`);
        }}
      >
        <input
          type="text"
          value={inviteeName}
          onChange={(event) => setInviteeName(event.target.value)}
          placeholder="Nombre de la persona"
          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
          disabled={isDisabled || isSubmitting}
        />
        <input
          type="email"
          value={email}
          onChange={(event) => setEmail(event.target.value)}
          placeholder="correo@empresa.com"
          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
          disabled={isDisabled || isSubmitting}
        />
        <select
          value={targetDepartment}
          onChange={(event) => setDepartment(event.target.value as (typeof DEPARTMENT_OPTIONS)[number]["value"])}
          className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
          disabled={isDisabled || isSubmitting || !isOwner}
        >
          {DEPARTMENT_OPTIONS.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
        <input
          type="text"
          value={departmentRole}
          onChange={(event) => setDepartmentRole(event.target.value)}
          placeholder="Rol dentro del área (ej. Líder de campañas)"
          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
          disabled={isDisabled || isSubmitting}
        />
        <select
          value={roleKey}
          onChange={(event) => setRoleKey(event.target.value as UserRole)}
          className="text-body rounded-xl border border-benell-stroke bg-white px-3 py-2"
          disabled={isDisabled || isSubmitting}
        >
          {roleOptions.filter((role) => allowedRoles.includes(role)).map((role) => (
            <option key={role} value={role}>
              {ROLE_LABELS[role]}
            </option>
          ))}
        </select>
        <button
          type="submit"
          disabled={isDisabled || isSubmitting}
          className="text-body rounded-pill bg-benell-brown px-4 py-2 font-semibold text-white disabled:opacity-60 md:col-span-2"
        >
          {isSubmitting ? "Enviando..." : "Enviar"}
        </button>
      </form>

      {canInvite && !leaderWithoutDepartment ? (
        <p className="text-label mt-3 text-benell-text-soft">
          Tu rol `{sessionRole}` puede invitar con niveles: {allowedRoles.map((role) => ROLE_LABELS[role]).join(", ")}.
          {!isOwner && sessionDepartment ? ` Departamento: ${getDepartmentLabel(sessionDepartment)}.` : ""}
        </p>
      ) : leaderWithoutDepartment ? (
        <p className="text-label mt-3 text-benell-red">
          Tu usuario líder no tiene departamento asignado. Solicita a un dueño actualizar tu perfil.
        </p>
      ) : sessionRole ? (
        <p className="text-label mt-3 text-benell-red">Solo usuarios con rol dueño o líder pueden enviar invitaciones.</p>
      ) : (
        <p className="text-label mt-3 text-benell-red">Inicia sesión para invitar personas.</p>
      )}
      {message ? <p className="text-label mt-3 text-benell-text-soft">{message}</p> : null}
    </section>
  );
}
