import {
  FilterDrawer,
  FilterSection,
  type FilterChip,
} from "@/routes/promo-code-campaigns/_components/FilterDrawer";
import {
  Checkbox,
  SegmentedControl,
  SimpleGrid,
  TextInput,
} from "@mantine/core";
import { DatePickerInput } from "@mantine/dates";
import {
  IconCalendarEvent,
  IconCalendarPlus,
  IconDevices,
  IconStack2,
  IconToggleLeft,
  IconUserCheck,
} from "@tabler/icons-react";
import { useEffect, useState } from "react";
import type { FilterState } from "./CampaignsTable/Filters";

type DateRange = [string | null, string | null];
type Membership = NonNullable<FilterState["membership"]>;

const PLATFORM_OPTIONS = ["iOS", "Android", "Web"];

const STATUS_OPTIONS = [
  "DRAFT",
  "SCHEDULED",
  "QUEUED",
  "SENDING",
  "STOPPED",
  "SENT",
  "COMPLETED",
  "FAILED",
  "PENDING",
];

const MEMBERSHIP_OPTIONS: { value: Membership; label: string }[] = [
  { value: "all", label: "All" },
  { value: "inCampaign", label: "In a campaign" },
  { value: "standalone", label: "Standalone" },
];

export const EMPTY_NOTIFICATION_FILTERS: FilterState = {
  platform: [],
  status: [],
  created: [null, null],
  scheduled: [null, null],
  publishedBy: "",
  membership: "all",
};

const toLabel = (status: string) =>
  status.charAt(0) + status.slice(1).toLowerCase();

const hasRange = (range?: DateRange) => Boolean(range?.[0] || range?.[1]);

const formatDay = (day: string) =>
  new Date(`${day}T00:00:00`).toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });

const rangeLabel = ([from, to]: DateRange) => {
  if (from && to) return `${formatDay(from)} – ${formatDay(to)}`;
  if (from) return `from ${formatDay(from)}`;
  return `until ${formatDay(to as string)}`;
};

export const countActiveFilters = (filters: FilterState): number =>
  filters.platform.length +
  filters.status.length +
  Number(hasRange(filters.created)) +
  Number(hasRange(filters.scheduled)) +
  Number(Boolean(filters.publishedBy?.trim())) +
  Number(Boolean(filters.membership && filters.membership !== "all"));

export function notificationFilterChips(
  filters: FilterState,
  onChange: (filters: FilterState) => void,
): FilterChip[] {
  const update = (patch: Partial<FilterState>) => () =>
    onChange({ ...filters, ...patch });
  const chips: FilterChip[] = [
    ...filters.platform.map((platform) => ({
      key: `platform-${platform}`,
      label: `Platform: ${platform}`,
      onRemove: update({
        platform: filters.platform.filter((p) => p !== platform),
      }),
    })),
    ...filters.status.map((status) => ({
      key: `status-${status}`,
      label: `Status: ${toLabel(status)}`,
      onRemove: update({ status: filters.status.filter((s) => s !== status) }),
    })),
  ];
  if (filters.membership && filters.membership !== "all") {
    chips.push({
      key: "membership",
      label:
        MEMBERSHIP_OPTIONS.find((o) => o.value === filters.membership)?.label ??
        "",
      onRemove: update({ membership: "all" }),
    });
  }
  if (filters.publishedBy?.trim()) {
    chips.push({
      key: "published-by",
      label: `Created by: ${filters.publishedBy.trim()}`,
      onRemove: update({ publishedBy: "" }),
    });
  }
  if (filters.created && hasRange(filters.created)) {
    chips.push({
      key: "created",
      label: `Created ${rangeLabel(filters.created)}`,
      onRemove: update({ created: [null, null] }),
    });
  }
  if (filters.scheduled && hasRange(filters.scheduled)) {
    chips.push({
      key: "scheduled",
      label: `Scheduled ${rangeLabel(filters.scheduled)}`,
      onRemove: update({ scheduled: [null, null] }),
    });
  }
  return chips;
}

const NotificationFilterDrawer: React.FC<{
  opened: boolean;
  onClose: () => void;
  filters: FilterState;
  onChange: (filters: FilterState) => void;
  extended?: boolean;
}> = ({ opened, onClose, filters, onChange, extended = false }) => {
  const [publishedBy, setPublishedBy] = useState(filters.publishedBy ?? "");

  useEffect(
    () => setPublishedBy(filters.publishedBy ?? ""),
    [filters.publishedBy],
  );

  useEffect(() => {
    if (publishedBy === (filters.publishedBy ?? "")) return;
    const timer = setTimeout(() => onChange({ ...filters, publishedBy }), 400);
    return () => clearTimeout(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [publishedBy]);

  return (
    <FilterDrawer
      opened={opened}
      onClose={onClose}
      activeCount={countActiveFilters(filters)}
      onReset={() => onChange(EMPTY_NOTIFICATION_FILTERS)}
    >
      <FilterSection
        icon={<IconToggleLeft size={15} />}
        title="Status"
        description="Where each notification is in its lifecycle"
      >
        <Checkbox.Group
          value={filters.status}
          onChange={(status) => onChange({ ...filters, status })}
        >
          <SimpleGrid cols={2} spacing="xs" verticalSpacing="xs">
            {STATUS_OPTIONS.map((status) => (
              <Checkbox key={status} value={status} label={toLabel(status)} />
            ))}
          </SimpleGrid>
        </Checkbox.Group>
      </FilterSection>

      {extended && (
        <>
          <FilterSection
            icon={<IconStack2 size={15} />}
            title="Campaign"
            description="Notifications inside a campaign or on their own"
          >
            <SegmentedControl
              fullWidth
              value={filters.membership ?? "all"}
              onChange={(membership) =>
                onChange({ ...filters, membership: membership as Membership })
              }
              data={MEMBERSHIP_OPTIONS}
            />
          </FilterSection>

          <FilterSection
            icon={<IconCalendarEvent size={15} />}
            title="Scheduled date"
            description="When the notification is set to send"
          >
            <DatePickerInput
              type="range"
              placeholder="Any date"
              value={filters.scheduled ?? [null, null]}
              onChange={(scheduled) =>
                onChange({ ...filters, scheduled: scheduled as DateRange })
              }
              allowSingleDateInRange
              clearable
              valueFormat="DD MMM YYYY"
            />
          </FilterSection>

          <FilterSection
            icon={<IconCalendarPlus size={15} />}
            title="Created date"
            description="When the notification was created"
          >
            <DatePickerInput
              type="range"
              placeholder="Any date"
              value={filters.created ?? [null, null]}
              onChange={(created) =>
                onChange({ ...filters, created: created as DateRange })
              }
              allowSingleDateInRange
              clearable
              valueFormat="DD MMM YYYY"
            />
          </FilterSection>

          <FilterSection
            icon={<IconUserCheck size={15} />}
            title="Created by"
            description="Email of the person who published it"
          >
            <TextInput
              placeholder="email contains…"
              value={publishedBy}
              onChange={(e) => setPublishedBy(e.currentTarget.value)}
            />
          </FilterSection>
        </>
      )}

      <FilterSection
        icon={<IconDevices size={15} />}
        title="Platform"
        description="Devices the notification targets"
        withDivider={false}
      >
        <Checkbox.Group
          value={filters.platform}
          onChange={(platform) => onChange({ ...filters, platform })}
        >
          <SimpleGrid cols={3} spacing="xs">
            {PLATFORM_OPTIONS.map((platform) => (
              <Checkbox key={platform} value={platform} label={platform} />
            ))}
          </SimpleGrid>
        </Checkbox.Group>
      </FilterSection>
    </FilterDrawer>
  );
};

export default NotificationFilterDrawer;
