"use client";

import * as React from "react";
import {
  CalendarPlus,
  ChevronLeft,
  ChevronRight,
  Copy,
  FileDown,
  Loader2,
  RefreshCw,
  Target,
  Users,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { ButtonGroup } from "@/components/ui/button-group";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { ReactSelect } from "@/components/ui/react-select";
import { formatTeamLabelForUi } from "@/lib/deal-display";
import { cn } from "@/lib/utils";

export type SalesTargetsTeamFilterOption = {
  id: string;
  name: string;
};

export type SalesTargetsPageHeaderState = {
  scopeToLedTeamsOnly: boolean;
  monthLabel: string;
  refreshing: boolean;
  creatingMonth: boolean;
  copyingPreviousMonth: boolean;
  exportingPdf: boolean;
  exportPdfDisabled: boolean;
  /** When false, hide Export PDF (MANAGE catalog only). */
  showExportPdf: boolean;
  monthNeedsInit: boolean;
  /** When true, the selected period already has a SalesTargetMonth row. */
  selectedMonthInitialized: boolean;
  canAddMonth: boolean;
  showCopyPreviousMonth: boolean;
  showAssignRepTargetsButton: boolean;
  assignRepTargetsDisabled: boolean;
  previousMonthDisabled: boolean;
  nextMonthDisabled: boolean;
  teamFilterId: string;
  teamFilterOptions: SalesTargetsTeamFilterOption[];
  /** When false, hide team filter (e.g. single-team team lead). */
  showTeamFilter: boolean;
};

export type SalesTargetsPageHeaderActions = {
  onOpenAssignReps?: () => void;
  onRefresh: () => void;
  onExportPdf: () => void;
  onEnsureMonth: () => void;
  onCopyPreviousMonth?: () => void;
  onPreviousMonth?: () => void;
  onNextMonth?: () => void;
  onTeamFilterChange?: (teamId: string) => void;
};

export type SalesTargetsPageHeaderProps = {
  state: SalesTargetsPageHeaderState;
  actions: SalesTargetsPageHeaderActions;
};

export function SalesTargetsPageHeader({
  state,
  actions,
}: SalesTargetsPageHeaderProps) {
  const {
    scopeToLedTeamsOnly,
    monthLabel,
    refreshing,
    creatingMonth,
    copyingPreviousMonth,
    exportingPdf,
    exportPdfDisabled,
    showExportPdf,
    monthNeedsInit,
    selectedMonthInitialized,
    canAddMonth,
    showCopyPreviousMonth,
    showAssignRepTargetsButton,
    assignRepTargetsDisabled,
    previousMonthDisabled,
    nextMonthDisabled,
    teamFilterId,
    teamFilterOptions,
    showTeamFilter: showTeamFilterProp,
  } = state;
  const {
    onOpenAssignReps,
    onRefresh,
    onExportPdf,
    onEnsureMonth,
    onCopyPreviousMonth,
    onPreviousMonth,
    onNextMonth,
    onTeamFilterChange,
  } = actions;

  const showTeamFilter =
    showTeamFilterProp ??
    (teamFilterOptions.length > 0 && typeof onTeamFilterChange === "function");
  const teamFilterSelectOptions = React.useMemo(() => {
    const options: { value: string; label: string }[] = [];
    if (!scopeToLedTeamsOnly) {
      options.push({ value: "all", label: "All teams" });
    }
    teamFilterOptions.forEach((t) => {
      options.push({
        value: t.id,
        label: formatTeamLabelForUi(t.name),
      });
    });
    return options;
  }, [scopeToLedTeamsOnly, teamFilterOptions]);

  return (
    <header className="flex shrink-0 flex-col gap-4 md:gap-5">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div className="flex min-w-0 items-start gap-3">
          <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-accent/10 text-accent ring-1 ring-accent/20">
            <Target className="size-5" aria-hidden />
          </span>
          <div className="min-w-0">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="font-['Lexend'] text-xl font-bold tracking-tight text-text md:text-2xl">
                Sales targets
              </h1>
              <div className="flex items-center rounded-full border border-accent/25 bg-accent/10">
                <Button
                  type="button"
                  variant="ghost"
                  size="icon-sm"
                  className="h-6 w-6 rounded-l-full hover:bg-accent/20"
                  onClick={onPreviousMonth}
                  disabled={previousMonthDisabled}
                  aria-label="Previous month"
                >
                  <ChevronLeft className="size-3 text-accent" />
                </Button>
                <span className="px-2 font-['Lexend_Deca'] text-[10px] font-bold uppercase tracking-wider text-accent">
                  {monthLabel}
                </span>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon-sm"
                  className="h-6 w-6 rounded-r-full hover:bg-accent/20"
                  onClick={onNextMonth}
                  disabled={nextMonthDisabled}
                  aria-label="Next month"
                >
                  <ChevronRight className="size-3 text-accent" />
                </Button>
              </div>
            </div>

          </div>
        </div>

        <TooltipProvider>
          <ButtonGroup
            role="toolbar"
            aria-label="Sales target actions"
          >
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  type="button"
                  variant="outline"
                  size="icon-sm"
                  disabled={refreshing}
                  onClick={onRefresh}
                  aria-label="Refresh sales targets"
                >
                  <RefreshCw
                    className={cn("size-3.5", refreshing && "animate-spin")}
                    aria-hidden
                  />
                  <span className="sr-only">Refresh</span>
                </Button>
              </TooltipTrigger>
              <TooltipContent>Refresh</TooltipContent>
            </Tooltip>
            {showExportPdf && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    type="button"
                    variant="outline"
                    size="icon-sm"
                    disabled={exportPdfDisabled || exportingPdf}
                    onClick={onExportPdf}
                    aria-label={
                      exportingPdf
                        ? "Generating sales targets PDF"
                        : "Export sales targets as PDF"
                    }
                  >
                    {exportingPdf ? (
                      <Loader2 className="size-3.5 animate-spin" aria-hidden />
                    ) : (
                      <FileDown className="size-3.5" aria-hidden />
                    )}
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  {exportingPdf ? "Exporting…" : "Export PDF"}
                </TooltipContent>
              </Tooltip>
            )}
            {canAddMonth && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="inline-flex">
                    <Button
                      type="button"
                      size="icon-sm"
                      variant={monthNeedsInit ? "default" : "outline"}
                      disabled={
                        selectedMonthInitialized ||
                        creatingMonth ||
                        copyingPreviousMonth
                      }
                      onClick={onEnsureMonth}
                      aria-label="Initialize month"
                    >
                      {creatingMonth ? (
                        <Loader2 className="size-3.5 animate-spin" aria-hidden />
                      ) : (
                        <CalendarPlus className="size-3.5" aria-hidden />
                      )}
                    </Button>
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  {selectedMonthInitialized
                    ? `${monthLabel} is already initialized`
                    : "Initialize month"}
                </TooltipContent>
              </Tooltip>
            )}
            {showCopyPreviousMonth && monthNeedsInit && typeof onCopyPreviousMonth === "function" && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    type="button"
                    size="icon-sm"
                    variant="outline"
                    disabled={creatingMonth || copyingPreviousMonth}
                    onClick={onCopyPreviousMonth}
                    aria-label="Initialize by copying previous month"
                  >
                    {copyingPreviousMonth ? (
                      <Loader2 className="size-3.5 animate-spin" aria-hidden />
                    ) : (
                      <Copy className="size-3.5" aria-hidden />
                    )}
                  </Button>
                </TooltipTrigger>
                <TooltipContent>
                  Copy previous month (team AE targets and rep assignments)
                </TooltipContent>
              </Tooltip>
            )}
            {showAssignRepTargetsButton && typeof onOpenAssignReps === "function" && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <span className="inline-flex">
                    <Button
                      type="button"
                      size="icon-sm"
                      variant="outline"
                      disabled={assignRepTargetsDisabled}
                      onClick={onOpenAssignReps}
                      aria-label="Assign rep targets"
                    >
                      <Users className="size-3.5" aria-hidden />
                    </Button>
                  </span>
                </TooltipTrigger>
                <TooltipContent>
                  {assignRepTargetsDisabled
                    ? `Initialize ${monthLabel} before assigning rep targets`
                    : "Assign rep targets"}
                </TooltipContent>
              </Tooltip>
            )}
          </ButtonGroup>
        </TooltipProvider>
      </div>

      {showTeamFilter && (
        <div className="w-full sm:w-64 min-[1500px]:w-[108px] min-[1500px]:max-w-[108px]">
          <ReactSelect
            size="sm"
            value={teamFilterId}
            options={teamFilterSelectOptions}
            onValueChange={onTeamFilterChange}
            placeholder="Filter by team..."
            aria-label="Filter by team"
            triggerClassName="min-[1500px]:max-w-[108px] min-[1500px]:min-w-[96px] font-['Lexend_Deca'] font-semibold"
          />
        </div>
      )}
    </header>
  );
}
