"use client";

import * as React from "react";
import { flushSync } from "react-dom";
import { usePathname, useSearchParams } from "next/navigation";
import { Spinner } from "@/components/ui/spinner";
import {
  DealsKanbanSkeleton,
  DealsLeadTableSkeleton,
} from "@/components/ui/loading";
import { Button } from "@/components/ui/button";
import { NoDataFound } from "@/components/ui/no-data-found";
import { Plus } from "lucide-react";
import {
  KanbanBoard,
  type KanbanBoardCopy,
} from "@/components/deals/kanban-helpers/kanban-board";
import { DealListView } from "@/components/deals/deal-list-view";
import { Deal, DealStage, Stage } from "@/components/deals/types";
import type { LeadsListParams } from "@/features/leads/types";
import type { KanbanClientBoardFilters } from "@/components/deals/kanban-helpers/deal-kanban-client-filters";
import type { CustomerPaymentKpis } from "@/api/rtk/customers-api";
import {
  useDealsContentHandlersSync,
  useDealsHeaderViewSync,
  useDealsPipelineContentStateSync,
} from "@/hooks/use-deals-pipeline-content-sync";
import { peekKanbanDataRefetchPending } from "@/components/deals/kanban-helpers/kanban-return-reset";

export interface DealsContentProps {
  sortedDeals: Deal[];
  activeBoard: { stages: Stage[] };
  boardUiKey: string;
  boardListParams: LeadsListParams | null;
  kanbanClientBoardFilters?: KanbanClientBoardFilters;
  canSubject?: "lead" | "deal";
  closedWonCustomerPaymentKpis?: CustomerPaymentKpis | null;
  closedWonCustomerPaymentKpisLoading?: boolean;
  teams?: Array<{ id: string; name: string }>;
}

export function DealsSkeleton() {
  return <DealsKanbanSkeleton />;
}

export function DealsContent({
  sortedDeals,
  activeBoard,
  boardUiKey,
  boardListParams,
  kanbanClientBoardFilters,
  canSubject = "deal",
  closedWonCustomerPaymentKpis,
  closedWonCustomerPaymentKpisLoading = false,
  teams,
}: DealsContentProps) {
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const queryKey = React.useMemo(() => searchParams.toString(), [searchParams]);
  const pc = useDealsPipelineContentStateSync();
  const view = useDealsHeaderViewSync();
  const handlers = useDealsContentHandlersSync();

  /** Forces a fresh Kanban tree when returning from list view (stable `useId` was reusing the same key). */
  const [kanbanRemountNonce, setKanbanRemountNonce] = React.useState(0);
  const prevViewRef = React.useRef<string | null>(null);
  React.useLayoutEffect(() => {
    if (peekKanbanDataRefetchPending()) {
      flushSync(() => setKanbanRemountNonce((n) => n + 1));
    }
  }, []);
  React.useEffect(() => {
    const prev = prevViewRef.current;
    prevViewRef.current = view;
    if (view === "kanban" && prev !== null && prev !== "kanban") {
      setKanbanRemountNonce((n) => n + 1);
    }
  }, [view]);

  const [showProgress, setShowProgress] = React.useState(false);
  const isUpdating = false;

  React.useEffect(() => {
    let timer: NodeJS.Timeout;
    if (isUpdating) {
      timer = setTimeout(() => setShowProgress(true), 400);
    } else {
      setShowProgress(false);
    }
    return () => clearTimeout(timer);
  }, [isUpdating]);

  const convertedDealIds = React.useMemo(
    () => new Set(pc.convertedDealIdList),
    [pc.convertedDealIdList],
  );

  const selectedIds = React.useMemo(
    () =>
      pc.selectedDealIdList.length
        ? new Set(pc.selectedDealIdList)
        : undefined,
    [pc.selectedDealIdList],
  );

  const listInfiniteLoad = React.useMemo(() => {
    if (!handlers.onListLoadMore) return undefined;
    return {
      hasMore: pc.listInfiniteHasMore,
      isLoadingMore: pc.listInfiniteIsLoadingMore,
      onLoadMore: handlers.onListLoadMore,
    };
  }, [
    handlers.onListLoadMore,
    pc.listInfiniteHasMore,
    pc.listInfiniteIsLoadingMore,
  ]);

  const kanbanBoardCopy = pc.kanbanBoardCopyPartial as Partial<KanbanBoardCopy>;

  const listViewDataLoading =
    view === "list" && (pc.pipelinesLoading || pc.dealsLoading);
  const kanbanViewDataLoading =
    view === "kanban" &&
    (pc.pipelinesLoading || (pc.dealsLoading && sortedDeals.length === 0));

  const refreshMessage =
    view === "list"
      ? canSubject === "lead"
        ? "Refreshing leads…"
        : "Refreshing deals…"
      : "Refreshing board…";

  const kanbanKey = `${boardUiKey}|${pathname}|${queryKey}|${kanbanRemountNonce}`;

  return (
    <div className="flex-1 min-h-0 overflow-hidden relative flex flex-col">
      {pc.dealsFetching && !pc.dealsLoading && (
        <div className="absolute top-4 right-4 z-40 animate-in fade-in slide-in-from-top-2 duration-300 pointer-events-none">
          <div className="flex items-center gap-3 bg-white/80 backdrop-blur-sm p-3 px-5 rounded-2xl shadow-premium border border-border/40 scale-90 origin-top-right">
            <Spinner className="size-4 text-accent" />
            <p className="text-[13px] font-bold text-text font-['Lexend_Deca'] tracking-tight">
              {refreshMessage}
            </p>
          </div>
        </div>
      )}

      <div className="min-h-0 flex-1 flex flex-col overflow-hidden">
        {listViewDataLoading ? (
          <div className="flex min-h-0 flex-1 flex-col items-stretch overflow-y-auto pr-1 scrollbar-themed">
            <DealsLeadTableSkeleton className="min-h-0" />
          </div>
        ) : kanbanViewDataLoading ? (
          <DealsSkeleton />
        ) : pc.pipelineCount === 0 ? (
          pc.boardPagingEntity === "leads" ? (
            <div className="h-full flex flex-col items-center justify-center px-4 py-12">
              <NoDataFound
                message="No pipeline found"
                description={pc.pipelineEmptyDescription}
              />
            </div>
          ) : (
            <div className="h-full flex flex-col items-center justify-center gap-5 text-center px-4 py-12">
              <p className="text-[15px] font-semibold text-gray-600 font-['Lexend_Deca']">
                No pipeline yet
              </p>
              <p className="text-[13px] text-gray-500 max-w-[320px]">
                {pc.pipelineEmptyDescription}
              </p>
              <Button
                size="sm"
                className="rounded-xl px-4 h-10 text-[13px] font-bold bg-accent text-white"
                onClick={handlers.onCreatePipeline}
              >
                <Plus size={16} className="mr-2" />
                Create pipeline
              </Button>
            </div>
          )
        ) : view === "kanban" ? (
          <KanbanBoard
            key={kanbanKey}
            stages={activeBoard.stages}
            deals={sortedDeals}
            convertedDealIds={convertedDealIds}
            onOpen={handlers.onOpenDeal}
            onEdit={handlers.onEditDeal}
            onDelete={handlers.onDeleteDeal}
            onMove={handlers.onMoveDeal}
            onPagedLeadMoveOptimistic={handlers.onPagedLeadMoveOptimistic}
            onInterceptLostMove={handlers.onInterceptLostMove}
            onInterceptDiscoveryMeetingMove={
              handlers.onInterceptDiscoveryMeetingMove
            }
            onReorderInStage={handlers.onReorderInStage}
            onAddStage={handlers.onAddStage}
            onReorderStages={handlers.onReorderStages}
            onAssignTask={
              pc.assignTaskEnabled ? handlers.onAssignTask : undefined
            }
            canManageStages={pc.isAdmin}
            isAddingStage={pc.isAddingStage}
            boardCopy={kanbanBoardCopy}
            emptyBoardTitle={pc.kanbanEmptyBoardTitle}
            emptyBoardDescription={pc.kanbanEmptyBoardDescription}
            boardPagingEnabled={pc.boardPagingEnabled}
            boardPagingEntity={pc.boardPagingEntity}
            businessPipelineId={pc.businessPipelineId}
            boardListParams={boardListParams ?? undefined}
            clientSearchQuery={pc.kanbanClientSearchQuery || undefined}
            kanbanClientBoardFilters={kanbanClientBoardFilters}
            boardUiKey={boardUiKey}
            onColumnDealsChange={handlers.onColumnDealsChange}
            canSubject={canSubject}
            closedWonCustomerPaymentKpis={closedWonCustomerPaymentKpis}
            closedWonCustomerPaymentKpisLoading={
              closedWonCustomerPaymentKpisLoading
            }
            teams={teams}
          />
        ) : (
          <div className="flex min-h-0 flex-1 flex-col items-start overflow-y-auto pr-1 scrollbar-themed">
            <DealListView
              deals={sortedDeals}
              stages={activeBoard.stages}
              selectAllAriaLabel={pc.listSelectAllAriaLabel}
              emptyTitle={pc.listEmptyTitle}
              emptySubtitle={pc.listEmptySubtitle}
              onOpen={handlers.onOpenDeal}
              onEdit={handlers.onEditDeal}
              onDelete={handlers.onDeleteDeal}
              sortCol={pc.sortCol}
              sortDir={pc.sortDir}
              onSort={handlers.onSort}
              selectedIds={selectedIds}
              onSelectId={handlers.onSelectId}
              onSelectAll={handlers.onSelectAll}
              listInfiniteLoad={listInfiniteLoad}
              canSubject={canSubject}
            />
          </div>
        )}

        {showProgress && (
          <div className="absolute bottom-6 right-6 z-50 animate-in slide-in-from-bottom-4 duration-300 pointer-events-none">
            <div className="flex items-center gap-3 bg-white/90 backdrop-blur-md p-4 px-6 rounded-2xl shadow-premium border border-border/40">
              <Spinner className="size-5 text-accent" />
              <p className="text-[14px] font-bold text-text font-['Lexend_Deca']">
                Updating Stage...
              </p>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
