"use client";

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

import { Dropdown, type DropdownOption } from "@/components/ui/dropdown";
import { DashboardResetButton } from "@/features/ministry/dashboard/components/dashboard-reset-button";
import { useIssueStatusOptions } from "@/features/ministry/meeting-summary/hook/use-issue-status-options";
import { useWgIssuesFilterOptions } from "@/features/pswg/working-group-issues/hook/use-working-group-issues";
import { useCdcGpsfWorkingGroupOptions } from "@/features/cdc-gpsf/dashboard/hook/use-cdc-gpsf-dashboard";
import {
  cdcGpsfReportOptions,
  cdcGpsfYearOptions,
  defaultCdcGpsfDashboardFilters,
  type CdcGpsfDashboardFiltersValue,
} from "@/features/cdc-gpsf/dashboard/cdc-gpsf-dashboard-data";

type CdcGpsfDashboardFiltersProps = {
  filters: CdcGpsfDashboardFiltersValue;
  onFiltersChange: (filters: CdcGpsfDashboardFiltersValue) => void;
};

// Every single-select dropdown gets an "All ..." choice at the top so the
// user can clear just that one filter. Its value is "" = no filter. (When
// the value is "", the dropdown shows its label as the placeholder text.)
function withAllOption(
  options: DropdownOption[],
  allLabel: string,
): DropdownOption[] {
  return [{ label: allLabel, value: "" }, ...options];
}

export function CdcGpsfDashboardFilters({
  filters,
  onFiltersChange,
}: CdcGpsfDashboardFiltersProps) {
  // Real dropdown options from the backend, so every value is a database id
  // the dashboard API understands.
  const workingGroupOptions = useCdcGpsfWorkingGroupOptions();
  const statusQuery = useIssueStatusOptions(); // Solved / In Progress / Not Addressed
  const { agencies, categories } = useWgIssuesFilterOptions();

  const workingGroupDropdownOptions = withAllOption(
    workingGroupOptions,
    "All working groups",
  );
  const categoryDropdownOptions = withAllOption(
    categories.map((category) => ({
      label: category.name,
      value: String(category.id),
    })),
    "All categories",
  );
  const statusDropdownOptions = withAllOption(
    (statusQuery.data ?? []).map((status) => ({
      label: status.name,
      value: String(status.id),
    })),
    "All statuses",
  );
  const agencyDropdownOptions = withAllOption(
    agencies.map((agency) => ({
      label: agency.name,
      value: String(agency.id),
    })),
    "All agencies",
  );

  const updateFilters = (nextFilters: Partial<CdcGpsfDashboardFiltersValue>) => {
    onFiltersChange({ ...filters, ...nextFilters });
  };

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

  return (
    <Box
      sx={{
        position: "relative",
        zIndex: 20,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 1.5,
        width: "100%",
      }}
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 0.75,
          flexWrap: "nowrap",
          minWidth: 0,
          overflowX: "auto",
          overflowY: "visible",
          scrollbarWidth: "none",
          "&::-webkit-scrollbar": {
            display: "none",
          },
        }}
      >
        <Box sx={{ width: 170, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label="Working Group"
            options={workingGroupDropdownOptions}
            value={filters.workingGroup}
            showCheckbox
            menuMinWidth={386}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) =>
              updateFilters({ workingGroup: String(value) })
            }
          />
        </Box>

        <Box sx={{ width: 134, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label="Category"
            options={categoryDropdownOptions}
            value={filters.category}
            showCheckbox
            menuMinWidth={280}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) => updateFilters({ category: String(value) })}
          />
        </Box>

        <Box sx={{ width: 134, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label="Status"
            options={statusDropdownOptions}
            value={filters.status}
            showCheckbox
            menuMinWidth={280}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) => updateFilters({ status: String(value) })}
          />
        </Box>

        <Box sx={{ width: 170, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label="Primary Agency"
            options={agencyDropdownOptions}
            value={filters.agency}
            showCheckbox
            menuMinWidth={386}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) => updateFilters({ agency: String(value) })}
          />
        </Box>

        <Box sx={{ width: 116, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label="Year"
            options={cdcGpsfYearOptions}
            value={filters.year}
            width="100%"
            onChange={(value) => updateFilters({ year: String(value) })}
          />
        </Box>

        {/* Progress Report is visual only for now — the backend has no
            report period column yet, so this selection is never sent. */}
        <Box sx={{ width: 170, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label="Progress Report"
            options={cdcGpsfReportOptions}
            value={filters.report}
            multiple
            showCheckbox
            displayMode="count"
            menuMinWidth={280}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) =>
              updateFilters({
                report: Array.isArray(value) ? value : [value],
              })
            }
          />
        </Box>
      </Box>

      <Box sx={{ flex: "0 0 auto" }}>
        <DashboardResetButton onClick={resetFilters} />
      </Box>
    </Box>
  );
}
