"use client";

import * as React from "react";
import { Loader2, UserPlus } from "lucide-react";
import { toast } from "sonner";

import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import {
  useGetAllUsersQuery,
  useGetRolesQuery,
} from "@/api/rtk";
import { useGetTeamsQuery } from "@/api/rtk/teams-api";
import { useAuthToken } from "@/hooks/use-auth-token";
import { pickRoleIdFromOrgRoles } from "@/components/deals/contributor-user-picker";
import { useBulkAssignLeadsMutation } from "@/features/leads/hooks/use-bulk-assign-leads-mutation";
import type { BulkAssignLeadsResult } from "@/features/leads/types";

import {
  BulkAssignFields,
  buildBulkAssignPayload,
  emptyBulkAssignFieldsValue,
  hasBulkAssignChanges,
  type BulkAssignFieldsValue,
} from "./bulk-assign-fields";

export type BulkAssignLeadsModalProps = {
  open: boolean;
  onClose: () => void;
  leadIds: string[];
  /** Optional id->display-name map so chips show real names. */
  labelById?: Record<string, string | undefined>;
  /** Fires after a successful apply so the host can clear the selection. */
  onApplied?: (result: BulkAssignLeadsResult) => void;
};

/**
 * Quick in-list bulk-assign modal. Renders the shared `BulkAssignFields` over
 * the supplied `leadIds`. The dedicated `/leads/bulk-assign` page reuses the
 * same fields component and the same TanStack mutation.
 */
export function BulkAssignLeadsModal({
  open,
  onClose,
  leadIds,
  labelById,
  onApplied,
}: BulkAssignLeadsModalProps) {
  const { token } = useAuthToken();
  const [value, setValue] = React.useState<BulkAssignFieldsValue>(
    emptyBulkAssignFieldsValue,
  );

  React.useEffect(() => {
    if (open) {
      setValue(emptyBulkAssignFieldsValue);
    }
  }, [open]);

  const { data: teams = [] } = useGetTeamsQuery(undefined, { skip: !open });
  const { data: orgRoles = [] } = useGetRolesQuery(undefined, {
    skip: !open || !token,
  });
  const { data: allUsers = [] } = useGetAllUsersQuery(undefined, {
    skip: !open || !token,
  });

  const aeRoleId = React.useMemo(
    () => pickRoleIdFromOrgRoles(orgRoles, ["ae", "account executive"]),
    [orgRoles],
  );
  const bdrRoleId = React.useMemo(
    () =>
      pickRoleIdFromOrgRoles(orgRoles, [
        "bdr",
        "business development representative",
      ]),
    [orgRoles],
  );

  const allUsersLabelById = React.useMemo(() => {
    const map: Record<string, string | undefined> = {};
    for (const u of allUsers) {
      map[u.id] = u.name || u.email || u.id;
    }
    if (labelById) {
      for (const [id, label] of Object.entries(labelById)) {
        if (label) map[id] = label;
      }
    }
    return map;
  }, [allUsers, labelById]);

  const mutation = useBulkAssignLeadsMutation();
  const isPending = mutation.isPending;
  const canApply = leadIds.length > 0 && hasBulkAssignChanges(value);

  const handleApply = async () => {
    if (!canApply) return;
    const payload = buildBulkAssignPayload(leadIds, value);
    try {
      const result = await mutation.mutateAsync(payload);
      const updated = result?.updated ?? 0;
      const skipped = result?.skipped ?? 0;
      if (skipped > 0) {
        toast.success(`${updated} updated · ${skipped} skipped`, {
          description:
            "Some leads were skipped because you are not allowed to edit them.",
        });
      } else {
        toast.success(`${updated} leads updated`);
      }
      onApplied?.(result);
      onClose();
    } catch (err) {
      const message =
        err instanceof Error
          ? err.message
          : "Failed to apply bulk assignment";
      toast.error(message);
    }
  };

  return (
    <Dialog open={open} onOpenChange={(v) => (!v ? onClose() : undefined)}>
      <DialogContent
        className="sm:max-w-[560px] w-[96vw] p-0 overflow-hidden"
        aria-describedby={undefined}
      >
        <div className="flex items-center gap-3 px-6 pt-6 pb-4 border-b border-border/40 bg-accent/5">
          <div className="size-9 rounded-xl bg-accent flex items-center justify-center shrink-0">
            <UserPlus size={16} className="text-white" />
          </div>
          <div>
            <DialogTitle className="text-[16px] font-extrabold font-['Lexend'] text-text leading-tight">
              Quick Assign
            </DialogTitle>
            <p className="text-[12px] text-gray-500 font-['Lexend_Deca'] mt-0.5">
              Assign team and contributors across {leadIds.length}{" "}
              {leadIds.length === 1 ? "lead" : "leads"}
            </p>
          </div>
        </div>

        <div className="px-6 py-5 max-h-[60vh] overflow-y-auto scrollbar-themed">
          <BulkAssignFields
            value={value}
            onChange={setValue}
            teams={teams}
            aeRoleId={aeRoleId}
            bdrRoleId={bdrRoleId}
            labelById={allUsersLabelById}
          />
        </div>

        <div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-border/40">
          <Button
            variant="ghost"
            size="sm"
            onClick={onClose}
            disabled={isPending}
          >
            Cancel
          </Button>
          <Button
            size="sm"
            onClick={handleApply}
            disabled={!canApply || isPending}
            className="gap-1.5 min-w-28"
          >
            {isPending ? (
              <>
                <Loader2 size={13} className="animate-spin" /> Applying…
              </>
            ) : (
              <>
                <UserPlus size={13} /> Apply to {leadIds.length}
              </>
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
