"use client";

import * as React from "react";
import { format, parse, subMonths } from "date-fns";
import { X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Field, FieldContent, FieldLabel } from "@/components/ui/field";
import { ReactSelect } from "@/components/ui/react-select";
import { DivisionSelect } from "@/components/shared/division-select";
import { TeamSelect } from "@/components/shared/team-select";
import { LeadChannelSelect } from "@/components/shared/lead-channel-select";
import {
  buildMarketingMonthOptions,
  marketingMonthToDateRange,
} from "./marketing-analytics-filters";

export type SpendFiltersState = {
  month: string;
  divisionId?: string;
  teamId?: string;
  channel?: string;
};

export function getDefaultSpendFilters(): SpendFiltersState {
  return { month: format(new Date(), "yyyy-MM") };
}

export function getPreviousMonth(month: string): string {
  const parsed = parse(month, "yyyy-MM", new Date());
  return format(subMonths(parsed, 1), "yyyy-MM");
}

export function getLastMonthSpendFilters(
  base?: Pick<SpendFiltersState, "divisionId" | "teamId" | "channel">,
): SpendFiltersState {
  const month = getPreviousMonth(format(new Date(), "yyyy-MM"));
  return {
    month,
    divisionId: base?.divisionId,
    teamId: base?.teamId,
    channel: base?.channel,
  };
}

export function hasActiveSpendFilters(filters: SpendFiltersState): boolean {
  const defaults = getDefaultSpendFilters();
  return (
    Boolean(filters.divisionId) ||
    Boolean(filters.teamId) ||
    Boolean(filters.channel) ||
    filters.month !== defaults.month
  );
}

export function spendFiltersToQuery(
  filters: SpendFiltersState,
  page: number,
  limit: number,
) {
  const { from, to } = marketingMonthToDateRange(filters.month);

  return {
    page: String(page),
    limit: String(limit),
    from,
    to,
    divisionId: filters.divisionId,
    teamId: filters.teamId,
    channel: filters.channel,
  };
}

type SpendLedgerFiltersProps = {
  value: SpendFiltersState;
  onApply: (next: SpendFiltersState) => void;
  onClearFilters?: () => void;
};

export function SpendLedgerFilters({
  value,
  onApply,
  onClearFilters,
}: SpendLedgerFiltersProps) {
  const [draft, setDraft] = React.useState<SpendFiltersState>(value);

  React.useEffect(() => {
    setDraft(value);
  }, [value]);

  const set = (patch: Partial<SpendFiltersState>) =>
    setDraft((current) => ({ ...current, ...patch }));

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

  const hasActiveFilters = React.useMemo(
    () => hasActiveSpendFilters(draft) || hasActiveSpendFilters(value),
    [draft, value],
  );

  const handleClear = () => {
    const defaults = getDefaultSpendFilters();
    setDraft(defaults);
    onApply(defaults);
    onClearFilters?.();
  };

  return (
    <div className="rounded-2xl border border-white/40 bg-white/50 dark:bg-white/10 backdrop-blur-[15px] p-4 md:p-5 flex flex-col gap-4">
      <div className="flex justify-between items-center gap-4">
        <div className="flex flex-col gap-1">
          <h2 className="font-['Lexend'] text-sm font-bold text-[#1d1d39]">
            Filters
          </h2>
          <p className="text-[11px] text-gray-500 font-['Lexend_Deca']">
            Spend is tracked by calendar month — entries on any day roll up to
            that month.
          </p>
        </div>
        <div className="flex justify-end gap-2">
          <Button
            type="button"
            variant="outline"
            className="rounded-xl"
            onClick={() => {
              const defaults = getDefaultSpendFilters();
              setDraft(defaults);
              onApply(defaults);
            }}
          >
            This month
          </Button>
          <Button
            type="button"
            variant="outline"
            className="rounded-xl"
            onClick={() => {
              const lastMonth = getLastMonthSpendFilters(draft);
              setDraft(lastMonth);
              onApply(lastMonth);
            }}
          >
            Last month
          </Button>
          <Button
            type="button"
            onClick={() => onApply(draft)}
            className="rounded-xl"
          >
            Apply filters
          </Button>
        </div>
      </div>
      <div className="flex items-end gap-4">
        <div className="grid gap-3 md:grid-cols-4 flex-1 min-w-0">
          <Field className="gap-1">
            <FieldLabel className="text-[11px] font-semibold uppercase tracking-wider text-gray-500">
              Month
            </FieldLabel>
            <FieldContent>
              <ReactSelect
                value={draft.month}
                onValueChange={(v) => v && set({ month: v })}
                options={monthOptions}
                placeholder="Select month"
                triggerClassName="h-10 rounded-xl bg-gray-50"
                aria-label="Month filter"
              />
            </FieldContent>
          </Field>
          <Field className="gap-1">
            <FieldLabel className="text-[11px] font-semibold uppercase tracking-wider text-gray-500">
              Division
            </FieldLabel>
            <FieldContent>
              <DivisionSelect
                value={draft.divisionId ?? ""}
                onValueChange={(v) =>
                  set({
                    divisionId: v || undefined,
                    teamId: undefined,
                  })
                }
                allowEmpty
                emptyOptionLabel="All divisions"
                placeholder="All divisions"
                triggerClassName="h-10 rounded-xl bg-gray-50"
                aria-label="Division filter"
              />
            </FieldContent>
          </Field>
          <Field className="gap-1">
            <FieldLabel className="text-[11px] font-semibold uppercase tracking-wider text-gray-500">
              Team
            </FieldLabel>
            <FieldContent>
              <TeamSelect
                value={draft.teamId ?? ""}
                onValueChange={(v) => set({ teamId: v || undefined })}
                divisionId={draft.divisionId}
                requireDivision
                allowEmpty
                emptyOptionLabel="All teams"
                placeholder="All teams"
                triggerClassName="h-10 rounded-xl bg-gray-50"
                aria-label="Team filter"
              />
            </FieldContent>
          </Field>
          <Field className="gap-1">
            <FieldLabel className="text-[11px] font-semibold uppercase tracking-wider text-gray-500">
              Channel
            </FieldLabel>
            <FieldContent>
              <LeadChannelSelect
                value={draft.channel ?? ""}
                onValueChange={(v) => set({ channel: v || undefined })}
                valueField="name"
                allowEmpty
                emptyOptionLabel="All channels"
                placeholder="All channels"
                triggerClassName="h-10 rounded-xl bg-gray-50"
                aria-label="Channel filter"
              />
            </FieldContent>
          </Field>
        </div>
        <button
          type="button"
          onClick={handleClear}
          disabled={!hasActiveFilters}
          aria-label="Clear filters"
          className="ml-auto shrink-0 px-5 py-2.5 text-sm font-medium text-gray-600 hover:text-red-600 border border-gray-300 hover:border-red-300 rounded-xl flex items-center gap-2 disabled:opacity-50 disabled:pointer-events-none transition-colors"
        >
          Clear Filters
          <X className="size-4 shrink-0" aria-hidden />
        </button>
      </div>
    </div>
  );
}
