"use client";

import * as React from "react";
import { ChevronRight, ChevronLeft } from "lucide-react";
import { cn } from "@/lib/utils";
import { useAppDispatch } from "@/store/hooks";
import { setKanbanGroupExpanded } from "@/store/slices/kanban-ui-slice";
import { dealsVisibleInColumn, getColumnFetchStageIds } from "../deal-utils";
import { mergeUnifiedSearchBucketsForStageIds } from "./kanban-board-helpers";
import { useKanbanBoardContext } from "./kanban-board-context";
import { KanbanColumn } from "./kanban-column";
import type { Deal, Stage, KanbanGroupProps } from "../types";

export const KanbanGroup = React.memo(function KanbanGroup({
  group,
  deals,
  isDragging,
  dragHandleProps,
}: KanbanGroupProps) {
  const dispatch = useAppDispatch();
  const {
    boardUiKey,
    expandedByParentId,
    canManageStages,
    boardPagingEnabled,
    stageCounts,
    unifiedSearchBuckets,
    columnSerialByStageId,
    refetchOnMountStageId,
  } = useKanbanBoardContext();

  const parentId = group.parentId;
  const isExpanded = expandedByParentId[parentId] ?? false;
  const userToggledRef = React.useRef(false);

  const setSubStagesExpanded = React.useCallback((expanded: boolean) => {
    userToggledRef.current = true;
    dispatch(setKanbanGroupExpanded({ boardKey: boardUiKey, parentId, expanded }));
  }, [boardUiKey, dispatch, parentId]);

  React.useEffect(() => {
    if (userToggledRef.current) return;
    const subStages = group.columns.filter((s: Stage) => s.isSubStage);
    const subStagesWithDeals = subStages.filter((subStage: Stage) => {
      if (boardPagingEnabled) return (stageCounts[subStage.id] ?? 0) > 0;
      return deals.some((d: Deal) => d.stage === subStage.id);
    });
    if (subStagesWithDeals.length > 0 && !isExpanded) {
      dispatch(setKanbanGroupExpanded({ boardKey: boardUiKey, parentId, expanded: true }));
    }
  }, [boardUiKey, boardPagingEnabled, dispatch, group.columns, deals, isExpanded, stageCounts, parentId]);

  const columnDealsMap = React.useMemo(() => {
    const map = new Map<string, Deal[]>();
    for (const stage of group.columns) {
      map.set(stage.id, dealsVisibleInColumn(group, stage, isExpanded, deals));
    }
    return map;
  }, [group, isExpanded, deals]);

  const columnFetchStageIdsMap = React.useMemo(() => {
    const map = new Map<string, string[]>();
    for (const stage of group.columns) {
      map.set(stage.id, getColumnFetchStageIds(group, stage, isExpanded));
    }
    return map;
  }, [group, isExpanded]);

  return (
    <div
      className={cn(
        "flex flex-col shrink-0 gap-3 max-[1499px]:gap-1.5 max-[1499px]:pt-1 bg-[rgba(116,116,116,0.03)] border-2 border-dashed border-gray-300/40 p-2.5 max-[1499px]:p-1.5 rounded-[20px]",
        isDragging && "opacity-90 ring-2 ring-accent/20",
      )}
    >
      <div className="flex items-center justify-between px-4 py-1">
        <div
          className={cn("flex items-center flex-1 touch-none", canManageStages && "cursor-grab active:cursor-grabbing")}
          {...(canManageStages ? dragHandleProps : {})}
        >
          <h3 className="text-[14px] font-extrabold text-gray-700/80 uppercase tracking-[0.05em]">
            {group.parentName}
          </h3>
        </div>
      </div>
      <div className="flex items-start pt-1">
        {group.columns.map((stage: Stage) => {
          const isParent = !stage.isSubStage;
          const show = isParent || isExpanded;
          const fetchStageIds = columnFetchStageIdsMap.get(stage.id) ?? [];
          return (
            <div
              key={stage.id}
              className={cn(
                "transition-[width,opacity,margin] duration-500 ease-in-out h-full",
                show ? "w-[305px] min-w-[305px] opacity-100 mr-4 overflow-visible" : "w-0 min-w-0 opacity-0 mr-0 overflow-hidden pointer-events-none",
              )}
            >
              {show ? (
                <div className="w-[305px] relative">
                  <KanbanColumn
                    stage={stage}
                    deals={columnDealsMap.get(stage.id) ?? []}
                    fetchStageIds={fetchStageIds}
                    unifiedSearchBucket={mergeUnifiedSearchBucketsForStageIds(
                      fetchStageIds.length > 0 ? fetchStageIds : [stage.id],
                      unifiedSearchBuckets,
                    )}
                    stagedLeadsColumnIndex={columnSerialByStageId.get(stage.id) ?? 999}
                    refetchOnMount={refetchOnMountStageId === stage.id}
                  />
                  {isParent && group.columns.length > 1 && (
                    <button
                      type="button"
                      className="absolute -right-2 top-1/2 -translate-y-1/2 h-8 w-8 rounded-full bg-white shadow-md z-10 border border-accent/20 hover:bg-accent/5 flex items-center justify-center"
                      onClick={() => setSubStagesExpanded(!isExpanded)}
                      title={isExpanded ? "Hide Sub Stages" : "Show Sub Stages"}
                    >
                      {isExpanded ? <ChevronLeft size={16} /> : <ChevronRight size={16} />}
                    </button>
                  )}
                </div>
              ) : null}
            </div>
          );
        })}
      </div>
    </div>
  );
});
