"use client";

/**
 * Filters for the accounts table, in the same shape as the promo-code pages:
 * a badged trigger, a right-hand drawer, and removable chips on the page so a
 * narrowed dataset is never silently narrowed. Filters apply on change.
 */

import {
  Badge,
  Button,
  Drawer,
  Group,
  Indicator,
  MultiSelect,
  Stack,
  Switch,
  Text,
  TextInput,
} from "@mantine/core";
import { IconFilter, IconRotate, IconSearch, IconX } from "@tabler/icons-react";

export interface MemberFilterValues {
  searchTerm: string;
  accountTypeIds: string[];
  accountStatusIds: string[];
  activeOnly: boolean;
  inactiveOnly: boolean;
  createdFrom: string;
  createdTo: string;
}

export const EMPTY_MEMBER_FILTERS: MemberFilterValues = {
  searchTerm: "",
  accountTypeIds: [],
  accountStatusIds: [],
  activeOnly: false,
  inactiveOnly: false,
  createdFrom: "",
  createdTo: "",
};

export const countActiveMemberFilters = (v: MemberFilterValues) =>
  (v.searchTerm ? 1 : 0) +
  (v.accountTypeIds.length ? 1 : 0) +
  (v.accountStatusIds.length ? 1 : 0) +
  (v.activeOnly ? 1 : 0) +
  (v.inactiveOnly ? 1 : 0) +
  (v.createdFrom ? 1 : 0) +
  (v.createdTo ? 1 : 0);

export function MemberFilterTrigger({
  activeCount,
  onClick,
}: {
  activeCount: number;
  onClick: () => void;
}) {
  return (
    <Indicator
      disabled={activeCount === 0}
      label={activeCount}
      size={18}
      offset={4}
    >
      <Button
        variant="default"
        leftSection={<IconFilter size={16} />}
        onClick={onClick}
      >
        Filters
      </Button>
    </Indicator>
  );
}

export function ActiveMemberFilterChips({
  values,
  options,
  onChange,
  onReset,
}: {
  values: MemberFilterValues;
  options: { accountTypes: Option[]; accountStatuses: Option[] };
  onChange: (next: MemberFilterValues) => void;
  onReset: () => void;
}) {
  const chips: { key: string; label: string; onRemove: () => void }[] = [];
  const labelFor = (list: Option[], id: string) =>
    list.find((option) => option.value === id)?.label ?? id;

  if (values.searchTerm) {
    chips.push({
      key: "searchTerm",
      label: `Search: ${values.searchTerm}`,
      onRemove: () => onChange({ ...values, searchTerm: "" }),
    });
  }
  values.accountTypeIds.forEach((id) =>
    chips.push({
      key: `type-${id}`,
      label: `Type: ${labelFor(options.accountTypes, id)}`,
      onRemove: () =>
        onChange({
          ...values,
          accountTypeIds: values.accountTypeIds.filter((v) => v !== id),
        }),
    }),
  );
  values.accountStatusIds.forEach((id) =>
    chips.push({
      key: `status-${id}`,
      label: `Status: ${labelFor(options.accountStatuses, id)}`,
      onRemove: () =>
        onChange({
          ...values,
          accountStatusIds: values.accountStatusIds.filter((v) => v !== id),
        }),
    }),
  );
  if (values.activeOnly) {
    chips.push({
      key: "activeOnly",
      label: "Active only",
      onRemove: () => onChange({ ...values, activeOnly: false }),
    });
  }
  if (values.inactiveOnly) {
    chips.push({
      key: "inactiveOnly",
      label: "Inactive only",
      onRemove: () => onChange({ ...values, inactiveOnly: false }),
    });
  }
  if (values.createdFrom) {
    chips.push({
      key: "createdFrom",
      label: `Synced from ${values.createdFrom}`,
      onRemove: () => onChange({ ...values, createdFrom: "" }),
    });
  }
  if (values.createdTo) {
    chips.push({
      key: "createdTo",
      label: `Synced to ${values.createdTo}`,
      onRemove: () => onChange({ ...values, createdTo: "" }),
    });
  }

  if (chips.length === 0) {
    return null;
  }

  return (
    <Group gap={6} wrap="wrap">
      {chips.map((chip) => (
        <Badge
          key={chip.key}
          variant="light"
          rightSection={
            <IconX
              size={12}
              style={{ cursor: "pointer" }}
              onClick={chip.onRemove}
            />
          }
        >
          {chip.label}
        </Badge>
      ))}
      <Button
        variant="subtle"
        size="compact-xs"
        leftSection={<IconRotate size={13} />}
        onClick={onReset}
      >
        Reset
      </Button>
    </Group>
  );
}

interface Option {
  value: string;
  label: string;
}

export function MemberFilterDrawer({
  opened,
  onClose,
  values,
  options,
  onChange,
  onReset,
}: {
  opened: boolean;
  onClose: () => void;
  values: MemberFilterValues;
  options: { accountTypes: Option[]; accountStatuses: Option[] };
  onChange: (next: MemberFilterValues) => void;
  onReset: () => void;
}) {
  return (
    <Drawer
      opened={opened}
      onClose={onClose}
      position="right"
      size={380}
      title={
        <Text fw={600} fz={15}>
          Filter Accounts
        </Text>
      }
    >
      <Stack gap="lg">
        <TextInput
          label="Search"
          description="Name, email, member or membership number"
          leftSection={<IconSearch size={15} />}
          value={values.searchTerm}
          onChange={(e) =>
            onChange({ ...values, searchTerm: e.currentTarget.value })
          }
        />

        <MultiSelect
          label="Account Type"
          data={options.accountTypes}
          value={values.accountTypeIds}
          onChange={(next) => onChange({ ...values, accountTypeIds: next })}
          searchable
          clearable
        />

        <MultiSelect
          label="Account Status"
          data={options.accountStatuses}
          value={values.accountStatusIds}
          onChange={(next) => onChange({ ...values, accountStatusIds: next })}
          searchable
          clearable
        />

        <Stack gap={6}>
          <Text fw={500} size="sm">
            Record state
          </Text>
          <Switch
            label="Active only"
            checked={values.activeOnly}
            onChange={(e) =>
              onChange({
                ...values,
                activeOnly: e.currentTarget.checked,
                inactiveOnly: e.currentTarget.checked
                  ? false
                  : values.inactiveOnly,
              })
            }
          />
          <Switch
            label="Inactive only"
            checked={values.inactiveOnly}
            onChange={(e) =>
              onChange({
                ...values,
                inactiveOnly: e.currentTarget.checked,
                activeOnly: e.currentTarget.checked ? false : values.activeOnly,
              })
            }
          />
        </Stack>

        <Group grow>
          <TextInput
            label="Synced from"
            placeholder="YYYY-MM-DD"
            value={values.createdFrom}
            onChange={(e) =>
              onChange({ ...values, createdFrom: e.currentTarget.value })
            }
          />
          <TextInput
            label="Synced to"
            placeholder="YYYY-MM-DD"
            value={values.createdTo}
            onChange={(e) =>
              onChange({ ...values, createdTo: e.currentTarget.value })
            }
          />
        </Group>

        <Group justify="space-between">
          <Button
            variant="subtle"
            leftSection={<IconRotate size={15} />}
            onClick={onReset}
          >
            Reset all
          </Button>
          <Button onClick={onClose}>Done</Button>
        </Group>
      </Stack>
    </Drawer>
  );
}
