import { ColumnDef } from "@tanstack/react-table";
import {
  ArrowUpDown,
  MoreHorizontal,
  Pencil,
  Send,
  Trash2,
  UserCheck,
  UserX,
} from "lucide-react";
import { t } from "i18next";
import { Button } from "@/shared/common/ui/button";
import { Badge } from "@/shared/common/ui/badge";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/common/ui/dropdown-menu";
import { OrgAdminUser } from "@/super-admin/hooks/useOrgAdmins";

export const ORG_ADMIN_ROLE_KEY = "organization_admin";
export const UNIT_ADMIN_ROLE_KEY = "unit_admin";

export interface AdminRoleInfo {
  isOrgAdmin: boolean;
  isUnitAdmin: boolean;
  unitId?: string;
}

/**
 * all-admins/:id returns users who are org admins of the org OR unit admins of
 * one of its units; userRoles carries every role of the user, so match the org
 * explicitly for the org-admin grant.
 */
// ponytail: unit relation isn't loaded, so a unit_admin grant from another org
// can't be told apart — acceptable, the server only returns admins of this org.
export function getAdminRoleInfo(
  admin: OrgAdminUser,
  selectedOrgId: string,
): AdminRoleInfo {
  const roles = admin.userRoles ?? [];
  const isOrgAdmin = roles.some(
    (r) =>
      r.role?.key === ORG_ADMIN_ROLE_KEY &&
      r.organizationId === selectedOrgId,
  );
  const unitRole = roles.find(
    (r) => r.role?.key === UNIT_ADMIN_ROLE_KEY && r.unitId,
  );
  return {
    isOrgAdmin,
    isUnitAdmin: !!unitRole,
    unitId: unitRole?.unitId ?? undefined,
  };
}

interface ColumnCallbacks {
  selectedOrgId: string;
  localizedName: (name?: { am?: string; en?: string }) => string;
  onEdit: (admin: OrgAdminUser) => void;
  onResend: (admin: OrgAdminUser) => void;
  onToggleActive: (admin: OrgAdminUser) => void;
  onRemove: (admin: OrgAdminUser, roleInfo: AdminRoleInfo) => void;
}

export function getOrgAdminsColumnDefn({
  selectedOrgId,
  localizedName,
  onEdit,
  onResend,
  onToggleActive,
  onRemove,
}: ColumnCallbacks): ColumnDef<OrgAdminUser>[] {
  return [
    {
      id: "name",
      accessorFn: (row) => localizedName(row.name),
      header: ({ column }) => (
        <Button
          variant="ghost"
          className="px-0 hover:bg-transparent"
          onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
        >
          {t("orgAdmins.columns.name")}
          <ArrowUpDown className="ml-2 h-4 w-4" />
        </Button>
      ),
      cell: ({ row }) => (
        <div>
          <p className="font-medium text-slate-800 dark:text-slate-100">
            {localizedName(row.original.name) || "—"}
          </p>
          <p className="text-xs text-muted-foreground">
            {row.original.username}
          </p>
        </div>
      ),
    },
    {
      id: "email",
      accessorFn: (row) => row.email ?? "",
      header: () => t("orgAdmins.columns.email"),
      cell: ({ row }) => (
        <span className="text-sm">{row.original.email || "—"}</span>
      ),
    },
    {
      id: "phoneNumber",
      accessorFn: (row) => row.phoneNumber ?? "",
      header: () => t("orgAdmins.columns.phone"),
      cell: ({ row }) => (
        <span className="text-sm">{row.original.phoneNumber || "—"}</span>
      ),
    },
    {
      id: "role",
      header: () => t("orgAdmins.columns.role"),
      cell: ({ row }) => {
        const info = getAdminRoleInfo(row.original, selectedOrgId);
        return (
          <div className="flex flex-wrap gap-1">
            {info.isOrgAdmin && (
              <Badge className="bg-indigo-100 text-indigo-700 hover:bg-indigo-100 dark:bg-indigo-950 dark:text-indigo-300">
                {t("orgAdmins.roleOrgAdmin")}
              </Badge>
            )}
            {info.isUnitAdmin && (
              <Badge className="bg-sky-100 text-sky-700 hover:bg-sky-100 dark:bg-sky-950 dark:text-sky-300">
                {t("orgAdmins.roleUnitAdmin")}
              </Badge>
            )}
          </div>
        );
      },
    },
    {
      id: "status",
      accessorFn: (row) =>
        !row.hasSetPassword
          ? "invited"
          : row.isActive
            ? "active"
            : "inactive",
      header: () => t("orgAdmins.columns.status"),
      cell: ({ row }) => {
        const admin = row.original;
        if (!admin.hasSetPassword) {
          return (
            <Badge className="bg-amber-100 text-amber-700 hover:bg-amber-100 dark:bg-amber-950 dark:text-amber-300">
              {t("orgAdmins.statusInvited")}
            </Badge>
          );
        }
        return admin.isActive ? (
          <Badge className="bg-emerald-100 text-emerald-700 hover:bg-emerald-100 dark:bg-emerald-950 dark:text-emerald-300">
            {t("orgAdmins.statusActive")}
          </Badge>
        ) : (
          <Badge className="bg-slate-200 text-slate-600 hover:bg-slate-200 dark:bg-slate-800 dark:text-slate-300">
            {t("orgAdmins.statusInactive")}
          </Badge>
        );
      },
    },
    {
      id: "createdAt",
      accessorFn: (row) => row.createdAt ?? "",
      header: () => t("orgAdmins.columns.addedOn"),
      cell: ({ row }) =>
        row.original.createdAt
          ? new Date(row.original.createdAt).toLocaleDateString()
          : "—",
    },
    {
      id: "actions",
      header: () => t("orgAdmins.columns.actions"),
      enableHiding: false,
      cell: ({ row }) => {
        const admin = row.original;
        const roleInfo = getAdminRoleInfo(admin, selectedOrgId);
        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" className="h-8 w-8 p-0">
                <MoreHorizontal className="h-4 w-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem onClick={() => onEdit(admin)}>
                <Pencil className="mr-2 h-4 w-4" />
                {t("orgAdmins.actions.edit")}
              </DropdownMenuItem>
              {!admin.hasSetPassword && (
                <DropdownMenuItem onClick={() => onResend(admin)}>
                  <Send className="mr-2 h-4 w-4" />
                  {t("orgAdmins.actions.resend")}
                </DropdownMenuItem>
              )}
              <DropdownMenuItem onClick={() => onToggleActive(admin)}>
                {admin.isActive ? (
                  <>
                    <UserX className="mr-2 h-4 w-4" />
                    {t("orgAdmins.actions.deactivate")}
                  </>
                ) : (
                  <>
                    <UserCheck className="mr-2 h-4 w-4" />
                    {t("orgAdmins.actions.activate")}
                  </>
                )}
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem
                className="text-red-600 focus:text-red-600"
                onClick={() => onRemove(admin, roleInfo)}
              >
                <Trash2 className="mr-2 h-4 w-4" />
                {t("orgAdmins.actions.remove")}
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
    },
  ];
}
