"use client";

import Box from "@mui/material/Box";

import { useAppLanguage } from "@/components/providers/app-language-provider";
import { Dropdown, type DropdownOption } from "@/components/ui/dropdown";
import { PlenaryResetButton } from "@/features/pswg/plenary/components/plenary-reset-button";
import {
  defaultPlenaryFilters,
  plenaryFilterConfigs,
  type PlenaryFiltersValue,
} from "@/features/pswg/plenary/plenary-data";
import {
  getPlenaryLocalizedText,
  normalizePlenaryLanguage,
} from "@/features/pswg/plenary/plenary-i18n";

type PlenaryFiltersProps = {
  filters: PlenaryFiltersValue;
  onFiltersChange: (filters: PlenaryFiltersValue) => void;
};

export function PlenaryFilters({
  filters,
  onFiltersChange,
}: PlenaryFiltersProps) {
  const { language } = useAppLanguage();
  const currentLanguage = normalizePlenaryLanguage(language);

  const updateFilter = (
    key: keyof PlenaryFiltersValue,
    nextValue: string | string[]
  ) => {
    onFiltersChange({
      ...filters,
      [key]: Array.isArray(nextValue) ? nextValue : [nextValue],
    });
  };

  const resetFilters = () => {
    onFiltersChange({ ...defaultPlenaryFilters });
  };

  return (
    <Box
      sx={{
        display: "grid",
        gridTemplateColumns: { xs: "1fr", md: "minmax(0, 1fr) auto" },
        alignItems: "start",
        gap: 1.25,
      }}
    >
      <Box
        sx={{
          display: "flex",
          flexWrap: { xs: "wrap", md: "nowrap" },
          gap: 1.25,
          minWidth: 0,
          overflowX: { xs: "visible", md: "auto" },
          pb: { xs: 0, md: 0.25 },
          scrollbarWidth: "none",
          "&::-webkit-scrollbar": {
            display: "none",
          },
        }}
      >
        {plenaryFilterConfigs.map((filter) => {
          const localizedOptions: DropdownOption[] = filter.options.map(
            (option) => ({
              label: getPlenaryLocalizedText(option.label, currentLanguage),
              value: option.value,
            })
          );

          return (
            <Box
              key={filter.key}
              sx={{ width: filter.width, minWidth: 0, flexShrink: 0 }}
            >
              <Dropdown
                label={getPlenaryLocalizedText(filter.label, currentLanguage)}
                options={localizedOptions}
                value={filters[filter.key]}
                multiple
                showCheckbox
                displayMode="count"
                menuMinWidth={280}
                menuMaxHeight={232}
                width="100%"
                onChange={(nextValue) => updateFilter(filter.key, nextValue)}
              />
            </Box>
          );
        })}
      </Box>

      <PlenaryResetButton onClick={resetFilters} />
    </Box>
  );
}
