"use client";

import * as React from "react";
import { format } from "date-fns";
import { Download, FileSpreadsheet, Loader2 } from "lucide-react";
import { toast } from "sonner";

import {
  useLazyExportDealsToCSVQuery,
  useLazyExportDealsToExcelQuery,
} from "@/api/endpoints/deals-api";
import { useGetAllUsersQuery, useGetRolesQuery } from "@/api/endpoints";
import { useLazyExportCustomersToExcelQuery } from "@/api/endpoints/customers-api";
import { useLazyGetExportActivitiesExcelQuery } from "@/api/endpoints/activities-api";
import {
  useLazyExportTransactionsExcelQuery,
  useLazyExportTransactionsPdfQuery,
} from "@/api/endpoints/transactions-api";
import { useGetTeamsQuery } from "@/api/endpoints/teams-api";
import { useGetClosedLeadTagsQuery } from "@/api/endpoints/deal-meta-api";
import {
  useLazyExportServiceSalesExcelQuery,
  useLazyExportServiceSalesPdfQuery,
} from "@/api/endpoints/reports-api";
import {
  useLazyExportMarketingAnalyticsExcelQuery,
  useLazyExportMarketingAnalyticsPdfQuery,
} from "@/api/endpoints/marketing-api";
import {
  useLazyExportSalesTargetsPdfQuery,
  useLazyGetAeAttainmentSummaryQuery,
} from "@/api/endpoints/sales-targets-api";
import {
  useLazyExportBdrMetricsPdfQuery,
  type BdrMetricsBucket,
} from "@/api/endpoints/bdr-metrics-api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { MonthPicker } from "@/components/ui/month-picker";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ReactSelect } from "@/components/ui/react-select";
import { SearchInput } from "@/components/ui/search-input";
import { Card, CardHeader } from "@/components/settings/ui";
import {
  ACTIVITY_TYPE_OPTIONS,
  BDR_METRICS_BUCKET_OPTIONS,
  buildPipelineStageOptions,
  canExportModule,
  CUSTOMER_STATUS_OPTIONS,
  DEFAULT_SERVICE_SALES_RANGE,
  EXPORT_FORMAT_OPTIONS,
  getAvailableExportModules,
  getExportFormatsForModule,
  getSalesTargetExportFormats,
  SALES_TARGET_FORMAT_OPTIONS,
  slugifyExportFilenamePart,
  TRANSACTION_STATUS_OPTIONS,
  type ExportFormat,
  type ExportModuleId,
} from "@/components/settings/export-query-builder-config";
import { pickRoleIdFromOrgRoles } from "@/components/deals/contributor-user-picker";
import {
  buildMarketingMonthOptions,
  getDefaultMarketingAnalyticsFilters,
  marketingFiltersToQuery,
  type MarketingFiltersState,
} from "@/components/marketing/marketing-analytics-filters";
import { buildClosedLostLeadsExportUrl } from "@/features/closed-lost-leads/api/build-closed-lost-leads-export-url";
import { formatTeamLabelForUi } from "@/lib/deal-display";
import { buildTeamDivisionLookup } from "@/lib/build-revenue-sheet-from-db";
import { usePipelinesQuery } from "@/hooks/use-pipelines-query";
import { useRevenueSheetExport } from "@/hooks/use-revenue-sheet-export";
import { useBlobExportWorker } from "@/hooks/use-blob-export-worker";
import { useAuthToken } from "@/hooks/use-auth-token";
import { EXCEL_EXPORT_MIME } from "@/lib/build-xlsx-export";
import { downloadBlob } from "@/lib/download-blob";
import {
  canExportSalesTargetsPdf,
  isAccountExecutiveRoleName,
  isBdrRoleName,
  type PermissionSource,
} from "@/lib/permissions";
import { cn } from "@/lib/utils";

export type ExportQueryBuilderTabProps = {
  permissionSource?: PermissionSource | null;
};

type AssigneeUser = {
  id: string;
  name?: string | null;
  email?: string | null;
  role?: { id?: string; name?: string | null } | null;
};

function currentPeriodDefaults() {
  const now = new Date();
  return {
    month: now.getMonth() + 1,
    year: now.getFullYear(),
    monthKey: format(now, "yyyy-MM"),
    dateFrom: format(new Date(now.getFullYear(), now.getMonth(), 1), "yyyy-MM-dd"),
    dateTo: format(now, "yyyy-MM-dd"),
  };
}

function normalizeRoleLabel(name?: string | null): string {
  return (name ?? "").trim().toLowerCase().replace(/\s+/g, " ");
}

function buildAssigneeFilterOptions(
  users: AssigneeUser[],
  match: (user: AssigneeUser) => boolean,
): { value: string; label: string }[] {
  const matched = users.filter(match);
  const pool = matched.length > 0 ? matched : users;
  return [...pool]
    .sort((a, b) =>
      (a.name || a.email || a.id).localeCompare(b.name || b.email || b.id),
    )
    .map((user) => ({
      value: user.id,
      label: user.name || user.email || user.id,
    }));
}

export function ExportQueryBuilderTab({
  permissionSource,
}: ExportQueryBuilderTabProps) {
  const { token } = useAuthToken();
  const defaults = React.useMemo(() => currentPeriodDefaults(), []);
  const availableModules = React.useMemo(
    () => getAvailableExportModules(permissionSource),
    [permissionSource],
  );

  const { data: pipelines = [], isLoading: pipelinesLoading } =
    usePipelinesQuery();
  const { data: teams } = useGetTeamsQuery(undefined, { skip: !token });
  const { data: allUsers = [] } = useGetAllUsersQuery(undefined, {
    skip: !token,
  });
  const { data: orgRoles = [] } = useGetRolesQuery(undefined, { skip: !token });
  const { data: closedLeadTagCatalog = [] } = useGetClosedLeadTagsQuery(
    undefined,
    { skip: !token },
  );

  const [exportModule, setExportModule] = React.useState<ExportModuleId>(
    availableModules[0]?.id ?? "lead",
  );
  const [exportFormat, setExportFormat] = React.useState<ExportFormat>("excel");
  const [pipelineId, setPipelineId] = React.useState("");
  const [stageId, setStageId] = React.useState("");
  const [customerStatus, setCustomerStatus] = React.useState("all");
  const [customerTeam, setCustomerTeam] = React.useState("all");
  const [customerMonth, setCustomerMonth] = React.useState("all");
  const [customerMonthPickerOpen, setCustomerMonthPickerOpen] =
    React.useState(false);
  const [closedLostSearch, setClosedLostSearch] = React.useState("");
  const [closedLostAeId, setClosedLostAeId] = React.useState("");
  const [closedLostBdrId, setClosedLostBdrId] = React.useState("");
  const [closedLostTag, setClosedLostTag] = React.useState("");
  const [activityMonth, setActivityMonth] = React.useState(defaults.month);
  const [activityYear, setActivityYear] = React.useState(defaults.year);
  const [activityType, setActivityType] = React.useState("all");
  const [activityTeam, setActivityTeam] = React.useState("all");
  const [activityRepId, setActivityRepId] = React.useState("");
  const [transactionFrom, setTransactionFrom] = React.useState(defaults.dateFrom);
  const [transactionTo, setTransactionTo] = React.useState(defaults.dateTo);
  const [transactionStatus, setTransactionStatus] = React.useState("all");
  const [transactionTeamId, setTransactionTeamId] = React.useState("all");
  const [transactionSearch, setTransactionSearch] = React.useState("");
  const [serviceSalesTeamId, setServiceSalesTeamId] = React.useState("all");
  const [marketingFilters, setMarketingFilters] =
    React.useState<MarketingFiltersState>(getDefaultMarketingAnalyticsFilters);
  const [salesTargetYear, setSalesTargetYear] = React.useState(defaults.year);
  const [salesTargetMonth, setSalesTargetMonth] = React.useState(defaults.month);
  const [salesTargetTeamId, setSalesTargetTeamId] = React.useState("all");
  const [bdrTeamId, setBdrTeamId] = React.useState("all");
  const [bdrUserId, setBdrUserId] = React.useState("all");
  const [bdrFrom, setBdrFrom] = React.useState(defaults.dateFrom);
  const [bdrTo, setBdrTo] = React.useState(defaults.dateTo);
  const [bdrBucket, setBdrBucket] =
    React.useState<BdrMetricsBucket>("assigned");

  const [triggerLeadDealExcel, { isFetching: exportingLeadDealExcel }] =
    useLazyExportDealsToExcelQuery();
  const [triggerLeadDealCsv, { isFetching: exportingLeadDealCsv }] =
    useLazyExportDealsToCSVQuery();
  const [triggerCustomerExport, { isFetching: exportingCustomer }] =
    useLazyExportCustomersToExcelQuery();
  const [triggerActivityExport, { isFetching: exportingActivity }] =
    useLazyGetExportActivitiesExcelQuery();
  const [triggerTransactionExcel, { isFetching: exportingTransactionExcel }] =
    useLazyExportTransactionsExcelQuery();
  const [triggerTransactionPdf, { isFetching: exportingTransactionPdf }] =
    useLazyExportTransactionsPdfQuery();
  const [triggerServiceSalesExcel, { isFetching: exportingServiceSalesExcel }] =
    useLazyExportServiceSalesExcelQuery();
  const [triggerServiceSalesPdf, { isFetching: exportingServiceSalesPdf }] =
    useLazyExportServiceSalesPdfQuery();
  const [triggerMarketingExcel, { isFetching: exportingMarketingExcel }] =
    useLazyExportMarketingAnalyticsExcelQuery();
  const [triggerMarketingPdf, { isFetching: exportingMarketingPdf }] =
    useLazyExportMarketingAnalyticsPdfQuery();
  const [triggerSalesTargetsPdf, { isFetching: exportingSalesTargetsPdf }] =
    useLazyExportSalesTargetsPdfQuery();
  const [fetchAttainmentSummary, { isFetching: fetchingAttainmentSummary }] =
    useLazyGetAeAttainmentSummaryQuery();
  const { exportRevenueSheet, isExportingRevenueSheet } = useRevenueSheetExport();
  const [triggerBdrMetricsPdf, { isFetching: exportingBdrMetricsPdf }] =
    useLazyExportBdrMetricsPdfQuery();
  const { downloadFromUrl, exporting: exportingClosedLost } =
    useBlobExportWorker();

  const exporting =
    exportingLeadDealExcel ||
    exportingLeadDealCsv ||
    exportingCustomer ||
    exportingActivity ||
    exportingTransactionExcel ||
    exportingTransactionPdf ||
    exportingClosedLost ||
    exportingServiceSalesExcel ||
    exportingServiceSalesPdf ||
    exportingMarketingExcel ||
    exportingMarketingPdf ||
    exportingSalesTargetsPdf ||
    fetchingAttainmentSummary ||
    isExportingRevenueSheet ||
    exportingBdrMetricsPdf;

  const activeModule =
    availableModules.find((module) => module.id === exportModule) ??
    availableModules[0];
  const filterKind = activeModule?.filterKind ?? "pipeline_stage";
  const formatOptions = React.useMemo(() => {
    if (exportModule === "sales_targets") {
      const allowedFormats = getSalesTargetExportFormats(permissionSource);
      return SALES_TARGET_FORMAT_OPTIONS.filter((option) =>
        allowedFormats.includes(option.value),
      );
    }
    return EXPORT_FORMAT_OPTIONS.filter((option) =>
      getExportFormatsForModule(exportModule).includes(option.value),
    );
  }, [exportModule, permissionSource]);

  const revenueDivisionByTeamId = React.useMemo(
    () => buildTeamDivisionLookup(teams ?? []),
    [teams],
  );

  const pipelineOptions = React.useMemo(
    () =>
      pipelines.map((pipeline) => ({
        value: pipeline.id,
        label: pipeline.name,
      })),
    [pipelines],
  );

  const selectedPipeline = React.useMemo(
    () => pipelines.find((pipeline) => pipeline.id === pipelineId),
    [pipelineId, pipelines],
  );

  const stageOptions = React.useMemo(() => {
    if (exportModule === "deal") {
      return buildPipelineStageOptions(selectedPipeline, "Deal");
    }
    if (exportModule === "lead") {
      return buildPipelineStageOptions(selectedPipeline, "Lead");
    }
    return [];
  }, [exportModule, selectedPipeline]);

  const customerTeamOptions = React.useMemo(
    () => [
      { value: "all", label: "All teams" },
      ...(teams?.map((team) => ({
        value: team.name.toLowerCase().split(" ")[1] || team.name.toLowerCase(),
        label: formatTeamLabelForUi(team.name),
      })) ?? []),
    ],
    [teams],
  );

  const teamIdOptions = React.useMemo(
    () => [
      { value: "all", label: "All teams" },
      ...(teams?.map((team) => ({
        value: team.id,
        label: formatTeamLabelForUi(team.name),
      })) ?? []),
    ],
    [teams],
  );

  const activityTeamOptions = React.useMemo(
    () => [
      { value: "all", label: "All teams" },
      ...(teams?.map((team) => ({
        value: team.name.toLowerCase().split(" ")[1] || team.name.toLowerCase(),
        label: formatTeamLabelForUi(team.name),
      })) ?? []),
    ],
    [teams],
  );

  const activityRepOptions = React.useMemo(
    () => buildAssigneeFilterOptions(allUsers as AssigneeUser[], () => true),
    [allUsers],
  );

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

  const closedLostAeOptions = React.useMemo(
    () =>
      buildAssigneeFilterOptions(allUsers as AssigneeUser[], (user) => {
        if (aeRoleId && user.role?.id === aeRoleId) return true;
        const role = normalizeRoleLabel(user.role?.name);
        return isAccountExecutiveRoleName(role) || role.includes("account executive");
      }),
    [allUsers, aeRoleId],
  );

  const closedLostBdrOptions = React.useMemo(
    () =>
      buildAssigneeFilterOptions(allUsers as AssigneeUser[], (user) => {
        if (bdrRoleId && user.role?.id === bdrRoleId) return true;
        const role = normalizeRoleLabel(user.role?.name);
        return isBdrRoleName(role) || role.includes("business development");
      }),
    [allUsers, bdrRoleId],
  );

  const bdrUserOptions = React.useMemo(
    () => [
      { value: "all", label: "All BDRs" },
      ...buildAssigneeFilterOptions(allUsers as AssigneeUser[], (user) => {
        if (bdrRoleId && user.role?.id === bdrRoleId) return true;
        const role = normalizeRoleLabel(user.role?.name);
        return isBdrRoleName(role) || role.includes("business development");
      }),
    ],
    [allUsers, bdrRoleId],
  );

  const closedLeadTagOptions = React.useMemo(
    () =>
      closedLeadTagCatalog.map((tag) => ({
        value: tag.name,
        label: tag.name,
      })),
    [closedLeadTagCatalog],
  );

  const marketingMonthOptions = React.useMemo(
    () => buildMarketingMonthOptions(),
    [],
  );

  const selectedStageLabel =
    stageOptions.find((option) => option.value === stageId)?.label ?? "";
  const selectedCustomerMonthDate = React.useMemo(() => {
    if (customerMonth === "all" || !customerMonth) return undefined;
    const match = customerMonth.match(/^(\d{4})-(\d{2})$/);
    if (!match) return undefined;
    return new Date(Number(match[1]), Number(match[2]) - 1, 1);
  }, [customerMonth]);

  React.useEffect(() => {
    if (!availableModules.some((module) => module.id === exportModule)) {
      setExportModule(availableModules[0]?.id ?? "lead");
    }
  }, [availableModules, exportModule]);

  React.useEffect(() => {
    const formats =
      exportModule === "sales_targets"
        ? getSalesTargetExportFormats(permissionSource)
        : getExportFormatsForModule(exportModule);
    if (!formats.includes(exportFormat)) {
      setExportFormat(formats[0] ?? "excel");
    }
  }, [exportFormat, exportModule, permissionSource]);

  React.useEffect(() => {
    if (
      filterKind === "pipeline_stage" ||
      filterKind === "closed_lost_filters"
    ) {
      if (!pipelineId && pipelines.length > 0) {
        const defaultPipeline =
          pipelines.find((pipeline) => pipeline.isDefault) ?? pipelines[0];
        setPipelineId(defaultPipeline.id);
      }
    }
  }, [filterKind, pipelineId, pipelines]);

  React.useEffect(() => {
    if (filterKind !== "pipeline_stage") return;
    if (!stageOptions.length) {
      setStageId("");
      return;
    }
    if (!stageOptions.some((option) => option.value === stageId)) {
      setStageId(stageOptions[0]?.value ?? "");
    }
  }, [filterKind, stageId, stageOptions]);

  const handleExportError = (error: unknown) => {
    console.error("Export query failed:", error);
    const status =
      error &&
      typeof error === "object" &&
      "status" in error &&
      typeof (error as { status: unknown }).status === "number"
        ? (error as { status: number }).status
        : undefined;

    if (status === 403) {
      toast.error("You do not have permission to export this module.");
      return;
    }

    const message =
      typeof error === "object" && error !== null
        ? (error as { data?: { message?: string }; message?: string }).data
            ?.message ||
          (error as { message?: string }).message ||
          "Failed to export data"
        : "Failed to export data";
    toast.error(message);
  };

  const handleExport = async () => {
    if (!activeModule || !canExportModule(permissionSource, activeModule.id)) {
      toast.error("You do not have permission to export this module.");
      return;
    }

    const stamp = new Date().toISOString().slice(0, 10);

    try {
      if (exportModule === "lead" || exportModule === "deal") {
        if (!pipelineId || !stageId) {
          toast.error("Select a pipeline and stage");
          return;
        }

        const stageType = exportModule === "deal" ? "Deal" : "Lead";
        const moduleSlug = exportModule === "deal" ? "deals" : "leads";
        const baseName = `${moduleSlug}-${slugifyExportFilenamePart(selectedPipeline?.name ?? "pipeline")}-${slugifyExportFilenamePart(selectedStageLabel)}-${stamp}`;

        if (exportFormat === "csv") {
          const blob = await triggerLeadDealCsv({
            pipelineId,
            stageType,
          }).unwrap();
          downloadBlob(blob, `${baseName}.csv`, "text/csv");
        } else {
          const blob = await triggerLeadDealExcel({
            pipelineId,
            stageType,
            stageId,
          }).unwrap();
          downloadBlob(blob, `${baseName}.xlsx`, EXCEL_EXPORT_MIME);
        }

        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "customer") {
        const blob = await triggerCustomerExport({
          status: customerStatus,
          team: customerTeam,
          month: customerMonth,
        }).unwrap();

        const statusLabel =
          CUSTOMER_STATUS_OPTIONS.find((option) => option.value === customerStatus)
            ?.label ?? "customers";
        downloadBlob(
          blob,
          `customers-${slugifyExportFilenamePart(statusLabel)}-${stamp}.xlsx`,
          EXCEL_EXPORT_MIME,
        );
        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "closed_lost_lead") {
        await downloadFromUrl(
          buildClosedLostLeadsExportUrl({
            ...(pipelineId ? { pipelineId } : {}),
            ...(closedLostSearch.trim()
              ? { search: closedLostSearch.trim() }
              : {}),
            ...(closedLostAeId ? { aeUserId: closedLostAeId } : {}),
            ...(closedLostBdrId ? { bdrUserId: closedLostBdrId } : {}),
            ...(closedLostTag ? { closedLeadTags: closedLostTag } : {}),
          }),
          `closed-lost-leads-${stamp}.xlsx`,
          EXCEL_EXPORT_MIME,
        );
        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "activity") {
        const blob = await triggerActivityExport({
          month: activityMonth,
          year: activityYear,
          type: activityType === "all" ? undefined : activityType,
          team: activityTeam === "all" ? undefined : activityTeam,
          repId: activityRepId || undefined,
        }).unwrap();

        downloadBlob(
          blob,
          `activities-${activityYear}-${String(activityMonth).padStart(2, "0")}-${stamp}.xlsx`,
          EXCEL_EXPORT_MIME,
        );
        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "transaction") {
        const params = {
          teamId: transactionTeamId !== "all" ? transactionTeamId : undefined,
          from: transactionFrom || undefined,
          to: transactionTo || undefined,
          ledgerStatus:
            transactionStatus === "all"
              ? undefined
              : (transactionStatus as "paid" | "pending"),
          search: transactionSearch.trim() || undefined,
        };

        if (exportFormat === "pdf") {
          const blob = await triggerTransactionPdf(params).unwrap();
          downloadBlob(blob, `transactions-${stamp}.pdf`, "application/pdf");
        } else {
          const blob = await triggerTransactionExcel(params).unwrap();
          downloadBlob(blob, `transactions-${stamp}.xlsx`, EXCEL_EXPORT_MIME);
        }

        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "service_sales") {
        const query = {
          range: DEFAULT_SERVICE_SALES_RANGE,
          teamFilter: serviceSalesTeamId !== "all" ? serviceSalesTeamId : "all",
        };

        if (exportFormat === "pdf") {
          const blob = await triggerServiceSalesPdf(query).unwrap();
          downloadBlob(blob, `service-sold-report_${stamp}.pdf`, "application/pdf");
        } else {
          const blob = await triggerServiceSalesExcel(query).unwrap();
          downloadBlob(blob, `service-sold-report_${stamp}.xlsx`, EXCEL_EXPORT_MIME);
        }

        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "marketing_analytics") {
        const query = marketingFiltersToQuery(marketingFilters);

        if (exportFormat === "pdf") {
          const blob = await triggerMarketingPdf(query).unwrap();
          downloadBlob(
            blob,
            `marketing-analytics_${stamp}.pdf`,
            "application/pdf",
          );
        } else {
          const blob = await triggerMarketingExcel(query).unwrap();
          downloadBlob(
            blob,
            `marketing-analytics_${stamp}.xlsx`,
            EXCEL_EXPORT_MIME,
          );
        }

        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "sales_targets") {
        const monthLabel = format(
          new Date(salesTargetYear, salesTargetMonth - 1, 1),
          "MMMM yyyy",
        );

        if (exportFormat === "excel") {
          const summary = await fetchAttainmentSummary({
            year: salesTargetYear,
            month: salesTargetMonth,
          }).unwrap();

          let exportTeams = summary?.teams ?? [];
          if (salesTargetTeamId !== "all") {
            exportTeams = exportTeams.filter(
              (team) => team.teamId === salesTargetTeamId,
            );
          }

          if (!exportTeams.length) {
            toast.error("No attainment data for this month yet.");
            return;
          }

          await exportRevenueSheet({
            year: salesTargetYear,
            month: salesTargetMonth,
            monthLabel,
            teams: exportTeams,
            divisionByTeamId: revenueDivisionByTeamId,
          });
          return;
        }

        if (!canExportSalesTargetsPdf(permissionSource ?? null)) {
          toast.error("You do not have permission to export the targets PDF.");
          return;
        }

        const blob = await triggerSalesTargetsPdf({
          year: salesTargetYear,
          month: salesTargetMonth,
          teamId:
            salesTargetTeamId !== "all" ? salesTargetTeamId : undefined,
        }).unwrap();
        downloadBlob(
          blob,
          `sales-targets-${salesTargetYear}-${String(salesTargetMonth).padStart(2, "0")}-${stamp}.pdf`,
          "application/pdf",
        );
        toast.success("Export downloaded");
        return;
      }

      if (exportModule === "bdr_metrics") {
        const blob = await triggerBdrMetricsPdf({
          teamId: bdrTeamId !== "all" ? bdrTeamId : undefined,
          bdrId: bdrUserId !== "all" ? bdrUserId : undefined,
          from: bdrFrom || undefined,
          to: bdrTo || undefined,
          bucket: bdrBucket,
        }).unwrap();
        downloadBlob(blob, `bdr-report_${stamp}.pdf`, "application/pdf");
        toast.success("Export downloaded");
      }
    } catch (error) {
      handleExportError(error);
    }
  };

  const exportReady = React.useMemo(() => {
    if (!activeModule || !canExportModule(permissionSource, activeModule.id)) {
      return false;
    }

    switch (filterKind) {
      case "pipeline_stage":
        return Boolean(pipelineId && stageId);
      case "closed_lost_filters":
        return true;
      case "customer_filters":
        return true;
      case "activity_period":
        return activityMonth >= 1 && activityMonth <= 12 && activityYear >= 2000;
      case "transaction_period":
        return Boolean(transactionFrom && transactionTo);
      case "report_range":
        return true;
      case "marketing_filters":
        return Boolean(marketingFilters.month);
      case "sales_target_period":
        return salesTargetMonth >= 1 && salesTargetMonth <= 12 && salesTargetYear >= 2000;
      case "bdr_metrics_period":
        return Boolean(bdrFrom && bdrTo);
      default:
        return false;
    }
  }, [
    activeModule,
    activityMonth,
    activityYear,
    bdrFrom,
    bdrTo,
    filterKind,
    marketingFilters.month,
    permissionSource,
    pipelineId,
    salesTargetMonth,
    salesTargetYear,
    stageId,
    transactionFrom,
    transactionTo,
  ]);

  const exportButtonLabel =
    exportModule === "sales_targets" && exportFormat === "excel"
      ? "Download revenue sheet"
      : exportFormat === "pdf"
        ? "Export to PDF"
        : exportFormat === "csv"
          ? "Export to CSV"
          : "Export to Excel";

  if (!availableModules.length) {
    return (
      <div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-[13px] text-amber-900">
        You do not have export permissions for any module yet.
      </div>
    );
  }

  const moduleLabel = activeModule?.label ?? "Records";

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <div className="h-10 w-10 rounded-xl bg-[#6C63FF]/10 flex items-center justify-center text-[#6C63FF]">
          <FileSpreadsheet size={18} strokeWidth={2.25} />
        </div>
        <div>
          <h2 className="text-[18px] font-extrabold text-gray-900 font-['Lexend'] tracking-tight leading-tight">
            Export query builder
          </h2>
          <p className="text-[12px] text-gray-500 mt-0.5">
            Central place for all CRM exports — pick a module, set filters, and
            download Excel, CSV, or PDF.
          </p>
        </div>
      </div>

      <Card>
        <CardHeader
          title="Build export query"
          description={activeModule?.description ?? ""}
        />
        <div className="p-6 space-y-5">
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                Module
              </p>
              <ReactSelect
                value={exportModule}
                onValueChange={(value) =>
                  setExportModule(value as ExportModuleId)
                }
                options={availableModules.map((module) => ({
                  value: module.id,
                  label: module.label,
                }))}
                disabled={exporting}
                triggerClassName="h-10 rounded-xl w-full text-[13px]"
              />
            </div>

            {formatOptions.length > 1 && (
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Format
                </p>
                <ReactSelect
                  value={exportFormat}
                  onValueChange={(value) =>
                    setExportFormat(value as ExportFormat)
                  }
                  options={formatOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            )}

            {(filterKind === "pipeline_stage" ||
              filterKind === "closed_lost_filters") && (
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Pipeline
                </p>
                <ReactSelect
                  value={pipelineId || undefined}
                  onValueChange={setPipelineId}
                  options={pipelineOptions}
                  placeholder={
                    pipelinesLoading ? "Loading pipelines…" : "All pipelines"
                  }
                  disabled={pipelinesLoading || exporting || !pipelineOptions.length}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            )}

            {filterKind === "pipeline_stage" && (
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Stage
                </p>
                <ReactSelect
                  value={stageId || undefined}
                  onValueChange={setStageId}
                  options={stageOptions}
                  placeholder={
                    !pipelineId
                      ? "Select a pipeline first"
                      : stageOptions.length
                        ? "Select stage"
                        : `No ${exportModule === "deal" ? "deal" : "lead"} stages found`
                  }
                  disabled={
                    !pipelineId ||
                    !stageOptions.length ||
                    exporting ||
                    pipelinesLoading
                  }
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            )}

            {filterKind === "customer_filters" && (
              <>
                <div>
                  <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                    Status
                  </p>
                  <ReactSelect
                    value={customerStatus}
                    onValueChange={setCustomerStatus}
                    options={[...CUSTOMER_STATUS_OPTIONS]}
                    disabled={exporting}
                    triggerClassName="h-10 rounded-xl w-full text-[13px]"
                  />
                </div>
                <div>
                  <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                    Team
                  </p>
                  <ReactSelect
                    value={customerTeam}
                    onValueChange={setCustomerTeam}
                    options={customerTeamOptions}
                    disabled={exporting}
                    triggerClassName="h-10 rounded-xl w-full text-[13px]"
                  />
                </div>
              </>
            )}

            {filterKind === "activity_period" && (
              <>
                <div>
                  <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                    Month
                  </p>
                  <ReactSelect
                    value={String(activityMonth)}
                    onValueChange={(value) => setActivityMonth(Number(value))}
                    options={Array.from({ length: 12 }, (_, index) => ({
                      value: String(index + 1),
                      label: format(new Date(2024, index, 1), "MMMM"),
                    }))}
                    disabled={exporting}
                    triggerClassName="h-10 rounded-xl w-full text-[13px]"
                  />
                </div>
                <div>
                  <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                    Year
                  </p>
                  <Input
                    type="number"
                    min={2000}
                    max={2100}
                    value={activityYear}
                    onChange={(event) =>
                      setActivityYear(Number(event.target.value))
                    }
                    disabled={exporting}
                    className="h-10 rounded-xl"
                  />
                </div>
              </>
            )}

            {filterKind === "report_range" && (
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Team
                </p>
                <ReactSelect
                  value={serviceSalesTeamId}
                  onValueChange={setServiceSalesTeamId}
                  options={teamIdOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            )}

            {filterKind === "marketing_filters" && (
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Month
                </p>
                <ReactSelect
                  value={marketingFilters.month}
                  onValueChange={(value) =>
                    setMarketingFilters((prev) => ({ ...prev, month: value }))
                  }
                  options={marketingMonthOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            )}

            {filterKind === "sales_target_period" && (
              <>
                <div>
                  <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                    Month
                  </p>
                  <ReactSelect
                    value={String(salesTargetMonth)}
                    onValueChange={(value) =>
                      setSalesTargetMonth(Number(value))
                    }
                    options={Array.from({ length: 12 }, (_, index) => ({
                      value: String(index + 1),
                      label: format(new Date(2024, index, 1), "MMMM"),
                    }))}
                    disabled={exporting}
                    triggerClassName="h-10 rounded-xl w-full text-[13px]"
                  />
                </div>
                <div>
                  <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                    Year
                  </p>
                  <Input
                    type="number"
                    min={2000}
                    max={2100}
                    value={salesTargetYear}
                    onChange={(event) =>
                      setSalesTargetYear(Number(event.target.value))
                    }
                    disabled={exporting}
                    className="h-10 rounded-xl"
                  />
                </div>
              </>
            )}
          </div>

          {filterKind === "customer_filters" && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="md:col-span-1">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Created month
                </p>
                <Popover
                  open={customerMonthPickerOpen}
                  onOpenChange={setCustomerMonthPickerOpen}
                >
                  <PopoverTrigger asChild>
                    <Button
                      type="button"
                      variant="outline"
                      className={cn(
                        "h-10 w-full justify-start rounded-xl text-[13px] font-normal",
                        customerMonth === "all" && "text-muted-foreground",
                      )}
                    >
                      {selectedCustomerMonthDate
                        ? format(selectedCustomerMonthDate, "MMMM yyyy")
                        : "All months"}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <MonthPicker
                      selected={selectedCustomerMonthDate}
                      onSelect={(month) => {
                        setCustomerMonth(format(month, "yyyy-MM"));
                        setCustomerMonthPickerOpen(false);
                      }}
                    />
                    {customerMonth !== "all" && (
                      <div className="border-t border-border/40 p-2">
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          className="h-8 w-full text-[12px] font-bold"
                          onClick={() => {
                            setCustomerMonth("all");
                            setCustomerMonthPickerOpen(false);
                          }}
                        >
                          Clear month
                        </Button>
                      </div>
                    )}
                  </PopoverContent>
                </Popover>
              </div>
            </div>
          )}

          {filterKind === "closed_lost_filters" && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="md:col-span-3">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Search
                </p>
                <SearchInput
                  value={closedLostSearch}
                  onChange={(event) => setClosedLostSearch(event.target.value)}
                  placeholder="Name, phone, email, reason…"
                  disabled={exporting}
                  className="h-10 rounded-xl"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Assign AE
                </p>
                <ReactSelect
                  value={closedLostAeId || undefined}
                  onValueChange={setClosedLostAeId}
                  options={closedLostAeOptions}
                  allowEmpty
                  emptyOptionLabel="All AEs"
                  placeholder="All AEs"
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Assign BDR
                </p>
                <ReactSelect
                  value={closedLostBdrId || undefined}
                  onValueChange={setClosedLostBdrId}
                  options={closedLostBdrOptions}
                  allowEmpty
                  emptyOptionLabel="All BDRs"
                  placeholder="All BDRs"
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              {closedLeadTagOptions.length > 0 && (
                <div>
                  <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                    Extra content tag
                  </p>
                  <ReactSelect
                    value={closedLostTag || undefined}
                    onValueChange={setClosedLostTag}
                    options={closedLeadTagOptions}
                    allowEmpty
                    emptyOptionLabel="All tags"
                    placeholder="All tags"
                    disabled={exporting}
                    triggerClassName="h-10 rounded-xl w-full text-[13px]"
                  />
                </div>
              )}
            </div>
          )}

          {filterKind === "activity_period" && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Activity type
                </p>
                <ReactSelect
                  value={activityType}
                  onValueChange={setActivityType}
                  options={[...ACTIVITY_TYPE_OPTIONS]}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Team
                </p>
                <ReactSelect
                  value={activityTeam}
                  onValueChange={setActivityTeam}
                  options={activityTeamOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Rep
                </p>
                <ReactSelect
                  value={activityRepId || undefined}
                  onValueChange={setActivityRepId}
                  options={activityRepOptions}
                  allowEmpty
                  emptyOptionLabel="All reps"
                  placeholder="All reps"
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            </div>
          )}

          {filterKind === "transaction_period" && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  From date
                </p>
                <Input
                  type="date"
                  value={transactionFrom}
                  onChange={(event) => setTransactionFrom(event.target.value)}
                  disabled={exporting}
                  className="h-10 rounded-xl"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  To date
                </p>
                <Input
                  type="date"
                  value={transactionTo}
                  onChange={(event) => setTransactionTo(event.target.value)}
                  disabled={exporting}
                  className="h-10 rounded-xl"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Status
                </p>
                <ReactSelect
                  value={transactionStatus}
                  onValueChange={setTransactionStatus}
                  options={[...TRANSACTION_STATUS_OPTIONS]}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Team
                </p>
                <ReactSelect
                  value={transactionTeamId}
                  onValueChange={setTransactionTeamId}
                  options={teamIdOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div className="md:col-span-2">
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Search
                </p>
                <SearchInput
                  value={transactionSearch}
                  onChange={(event) => setTransactionSearch(event.target.value)}
                  placeholder="Deal label, description…"
                  disabled={exporting}
                  className="h-10 rounded-xl"
                />
              </div>
            </div>
          )}

          {filterKind === "marketing_filters" && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Team
                </p>
                <ReactSelect
                  value={marketingFilters.teamId ?? ""}
                  onValueChange={(value) =>
                    setMarketingFilters((prev) => ({
                      ...prev,
                      teamId: value || undefined,
                    }))
                  }
                  options={teamIdOptions.filter((option) => option.value !== "all")}
                  allowEmpty
                  emptyOptionLabel="All teams"
                  placeholder="All teams"
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            </div>
          )}

          {filterKind === "sales_target_period" && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Team
                </p>
                <ReactSelect
                  value={salesTargetTeamId}
                  onValueChange={setSalesTargetTeamId}
                  options={teamIdOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
            </div>
          )}

          {filterKind === "bdr_metrics_period" && (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Team
                </p>
                <ReactSelect
                  value={bdrTeamId}
                  onValueChange={setBdrTeamId}
                  options={teamIdOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  BDR
                </p>
                <ReactSelect
                  value={bdrUserId}
                  onValueChange={setBdrUserId}
                  options={bdrUserOptions}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  Lead bucket
                </p>
                <ReactSelect
                  value={bdrBucket}
                  onValueChange={(value) =>
                    setBdrBucket(value as BdrMetricsBucket)
                  }
                  options={BDR_METRICS_BUCKET_OPTIONS}
                  disabled={exporting}
                  triggerClassName="h-10 rounded-xl w-full text-[13px]"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  From date
                </p>
                <Input
                  type="date"
                  value={bdrFrom}
                  onChange={(event) => setBdrFrom(event.target.value)}
                  disabled={exporting}
                  className="h-10 rounded-xl"
                />
              </div>
              <div>
                <p className="text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5">
                  To date
                </p>
                <Input
                  type="date"
                  value={bdrTo}
                  onChange={(event) => setBdrTo(event.target.value)}
                  disabled={exporting}
                  className="h-10 rounded-xl"
                />
              </div>
            </div>
          )}

          <div className="rounded-xl border border-[#6C63FF]/15 bg-[#6C63FF]/5 px-4 py-3 text-[12px] text-gray-600 leading-relaxed">
            <span className="font-semibold text-[#6C63FF]">Preview:</span> Export{" "}
            <span className="font-semibold text-gray-800">{moduleLabel}</span> as{" "}
            <span className="font-semibold text-gray-800">
              {formatOptions.find((option) => option.value === exportFormat)?.label ??
                exportFormat}
            </span>
            {filterKind === "pipeline_stage" && (
              <>
                {" "}
                from{" "}
                <span className="font-semibold text-gray-800">
                  {selectedPipeline?.name ?? "—"}
                </span>{" "}
                in stage{" "}
                <span className="font-semibold text-gray-800">
                  {selectedStageLabel || "—"}
                </span>
              </>
            )}
            {filterKind === "customer_filters" && (
              <>
                {" "}
                with status{" "}
                <span className="font-semibold text-gray-800">
                  {
                    CUSTOMER_STATUS_OPTIONS.find(
                      (option) => option.value === customerStatus,
                    )?.label
                  }
                </span>
              </>
            )}
            {filterKind === "activity_period" && (
              <>
                {" "}
                for{" "}
                <span className="font-semibold text-gray-800">
                  {format(new Date(activityYear, activityMonth - 1, 1), "MMMM yyyy")}
                </span>
              </>
            )}
            {filterKind === "transaction_period" && (
              <>
                {" "}
                from{" "}
                <span className="font-semibold text-gray-800">{transactionFrom}</span>{" "}
                to{" "}
                <span className="font-semibold text-gray-800">{transactionTo}</span>
              </>
            )}
            {filterKind === "marketing_filters" && (
              <>
                {" "}
                for{" "}
                <span className="font-semibold text-gray-800">
                  {
                    marketingMonthOptions.find(
                      (option) => option.value === marketingFilters.month,
                    )?.label
                  }
                </span>
              </>
            )}
            {filterKind === "sales_target_period" && (
              <>
                {" "}
                for{" "}
                <span className="font-semibold text-gray-800">
                  {format(
                    new Date(salesTargetYear, salesTargetMonth - 1, 1),
                    "MMMM yyyy",
                  )}
                </span>
              </>
            )}
            .
          </div>

          <div className="flex justify-end">
            <Button
              type="button"
              onClick={() => void handleExport()}
              disabled={!exportReady || exporting}
              className="h-10 px-5 rounded-xl gap-2 font-bold text-[13px]"
            >
              {exporting ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  Exporting…
                </>
              ) : (
                <>
                  <Download className="size-4" />
                  {exportButtonLabel}
                </>
              )}
            </Button>
          </div>
        </div>
      </Card>
    </div>
  );
}
