"use client";

import { useEffect, useMemo, useState } from "react";

import Box from "@mui/material/Box";
import ButtonBase from "@mui/material/ButtonBase";
import Menu from "@mui/material/Menu";
import Typography from "@mui/material/Typography";
import { alpha, useTheme } from "@mui/material/styles";

import { dashboardAssets } from "@/components/dashboard/dashboard-assets";
import { DashboardAssetIcon } from "@/components/dashboard/dashboard-asset-icon";
import { Dropdown, type DropdownOption } from "@/components/ui/dropdown";
import {
  cdcGpsfMeetingRequestI18n,
  getCdcGpsfMeetingRequestFont,
  type CdcGpsfMeetingRequestUiLang,
} from "@/features/cdc-gpsf/meeting-requests/cdc-gpsf-meeting-request-i18n";
import { useCdcGpsfMeetingRequests } from "@/features/cdc-gpsf/meeting-requests/hook/use-cdc-gpsf-meeting-requests";
import { resolveAssetUrl } from "@/features/cdc-gpsf/meeting-requests/service/cdc-gpsf-meeting-request-service";

import {
  CdcGpsfMeetingRequestsViewTabs,
  type CdcGpsfMeetingRequestsViewMode,
} from "./cdc-gpsf-meeting-requests-view-tabs";

type CdcGpsfMeetingRequestsFiltersProps = {
  activeView: CdcGpsfMeetingRequestsViewMode;
  language?: CdcGpsfMeetingRequestUiLang;
  onViewChange: (view: CdcGpsfMeetingRequestsViewMode) => void;

  workingGroupFilter: string[];
  onWorkingGroupFilterChange: (values: string[]) => void;

  governmentAgencyFilter: string[];
  onGovernmentAgencyFilterChange: (values: string[]) => void;

  statusFilter: string[];
  onStatusFilterChange: (values: string[]) => void;

  meetingDateFilter: string[];
  onMeetingDateFilterChange: (values: string[]) => void;
};

const months = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
];

function toSelectedValues(value: string | string[]) {
  return Array.isArray(value) ? value : [value];
}

type MeetingDateFilterProps = {
  label: string;
  width: number;
  language: CdcGpsfMeetingRequestUiLang;
  selectedValues: string[];
  onChange: (values: string[]) => void;
};

function MeetingDateFilter({
  label,
  width,
  language,
  selectedValues,
  onChange,
}: MeetingDateFilterProps) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const [monthIndex, setMonthIndex] = useState(new Date().getMonth());
  const [year, setYear] = useState(new Date().getFullYear());

  const open = Boolean(anchorEl);

  const selectedLabel = useMemo(() => {
    if (selectedValues.length === 0) return label;

    return selectedValues[0];
  }, [label, selectedValues]);

  const handleShowDate = () => {
    const month = months[monthIndex];

    onChange([`${month} ${year}`]);
    setAnchorEl(null);
  };

  return (
    <>
      <ButtonBase
        onClick={(event) => setAnchorEl(event.currentTarget)}
        sx={{
          width,
          height: 40,
          flex: "0 0 auto",
          px: 1.5,
          borderRadius: "6px",
          border: `1px solid ${
            open ? "#1f6fb2" : isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"
          }`,
          bgcolor: isDark ? alpha("#ffffff", 0.05) : "#ffffff",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          gap: 1,
          overflow: "hidden",
        }}
      >
        <Typography
          noWrap
          sx={{
            color: isDark ? alpha("#ffffff", 0.7) : "#717680",
            fontSize: 13,
            fontWeight: 500,
            fontFamily: getCdcGpsfMeetingRequestFont(language),
            minWidth: 0,
          }}
        >
          {selectedLabel}
        </Typography>

        <DashboardAssetIcon
          src={dashboardAssets.chevronDownSmall}
          width={8}
          height={5}
          sx={{ flexShrink: 0 }}
        />
      </ButtonBase>

      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={() => setAnchorEl(null)}
        slotProps={{
          paper: {
            sx: {
              mt: 1,
              width: 250,
              borderRadius: "14px",
              border: `1px solid ${
                isDark ? alpha("#ffffff", 0.12) : "#e9eaeb"
              }`,
              backgroundColor: isDark ? "#101828" : "#ffffff",
              boxShadow: "0px 12px 30px rgba(16, 24, 40, 0.16)",
              overflow: "hidden",
            },
          },
        }}
      >
        <Box sx={{ p: 2 }}>
          <Box
            sx={{
              display: "grid",
              gridTemplateColumns: "1fr 1fr",
              alignItems: "center",
              textAlign: "center",
              columnGap: 2,
            }}
          >
            <ButtonBase
              onClick={() =>
                setMonthIndex((previous) =>
                  previous === 0 ? months.length - 1 : previous - 1,
                )
              }
              sx={{ height: 26, borderRadius: "8px" }}
            >
              <Typography sx={{ fontSize: 20, lineHeight: 1 }}>⌃</Typography>
            </ButtonBase>

            <ButtonBase
              onClick={() => setYear((previous) => previous + 1)}
              sx={{ height: 26, borderRadius: "8px" }}
            >
              <Typography sx={{ fontSize: 20, lineHeight: 1 }}>⌃</Typography>
            </ButtonBase>

            <Typography
              sx={{
                py: 1,
                fontSize: 18,
                fontWeight: 500,
                color: isDark ? "#ffffff" : "#4a4a4a",
                fontFamily: getCdcGpsfMeetingRequestFont(language),
              }}
            >
              {months[monthIndex]}
            </Typography>

            <Typography
              sx={{
                py: 1,
                fontSize: 18,
                fontWeight: 500,
                color: isDark ? "#ffffff" : "#4a4a4a",
                fontFamily: getCdcGpsfMeetingRequestFont(language),
              }}
            >
              {year}
            </Typography>

            <ButtonBase
              onClick={() =>
                setMonthIndex((previous) =>
                  previous === months.length - 1 ? 0 : previous + 1,
                )
              }
              sx={{ height: 26, borderRadius: "8px" }}
            >
              <Typography sx={{ fontSize: 20, lineHeight: 1 }}>⌄</Typography>
            </ButtonBase>

            <ButtonBase
              onClick={() => setYear((previous) => previous - 1)}
              sx={{ height: 26, borderRadius: "8px" }}
            >
              <Typography sx={{ fontSize: 20, lineHeight: 1 }}>⌄</Typography>
            </ButtonBase>
          </Box>

          <Box sx={{ mt: 1.5, display: "flex", justifyContent: "flex-end" }}>
            <ButtonBase
              onClick={handleShowDate}
              sx={{
                height: 30,
                width: 86,
                borderRadius: "6px",
                bgcolor: "#1f6fb2",
                color: "#ffffff",
                fontSize: 12,
                fontWeight: 600,
                fontFamily: getCdcGpsfMeetingRequestFont(language),
                "&:hover": { bgcolor: "#195f99" },
              }}
            >
              Show
            </ButtonBase>
          </Box>
        </Box>
      </Menu>
    </>
  );
}

export function CdcGpsfMeetingRequestsFilters({
  activeView,
  language = "km",
  onViewChange,
  workingGroupFilter,
  onWorkingGroupFilterChange,
  governmentAgencyFilter,
  onGovernmentAgencyFilterChange,
  statusFilter,
  onStatusFilterChange,
  meetingDateFilter,
  onMeetingDateFilterChange,
}: CdcGpsfMeetingRequestsFiltersProps) {
  const t = cdcGpsfMeetingRequestI18n(language);

  const {
    agencies,
    workingGroups,
    fetchGovernmentAgencies,
    fetchWorkingGroups,
  } = useCdcGpsfMeetingRequests();

  useEffect(() => {
    fetchWorkingGroups();
    fetchGovernmentAgencies();
  }, [fetchWorkingGroups, fetchGovernmentAgencies]);

  const workingGroupOptions = useMemo<DropdownOption[]>(
    () =>
      workingGroups.map((item) => ({
        label: item.name,
        value: String(item.id),
      })),
    [workingGroups],
  );

  const governmentAgencyOptions = useMemo<DropdownOption[]>(
    () =>
      agencies.map((item) => ({
        label: item.name,
        value: String(item.id),
        logo: resolveAssetUrl(item.logo) || null,
      })),
    [agencies],
  );

  const statusOptions = useMemo<DropdownOption[]>(
    () => [
      { label: t.statuses.Drafted, value: "Drafted" },
      { label: t.statuses.Submitted, value: "Submitted" },
      { label: t.statuses["Under Review"], value: "Under Review" },
      { label: t.statuses.Scheduled, value: "Scheduled" },
      { label: t.statuses.Completed, value: "Completed" },
    ],
    [t.statuses],
  );

  return (
    <Box
      sx={{
        mt: 3,
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        gap: 2,
        flexWrap: "nowrap",
        width: "100%",
      }}
    >
      <Box
        sx={{
          display: "flex",
          alignItems: "center",
          gap: 0.75,
          flexWrap: "nowrap",
          flex: "0 1 auto",
          minWidth: 0,
          overflow: "hidden",
        }}
      >
        <Box sx={{ width: 170, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label={t.workingGroup}
            options={workingGroupOptions}
            value={workingGroupFilter}
            multiple
            showCheckbox
            displayMode="count"
            menuMinWidth={386}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) =>
              onWorkingGroupFilterChange(toSelectedValues(value))
            }
          />
        </Box>

        <Box sx={{ width: 220, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label={t.governmentAgency}
            options={governmentAgencyOptions}
            value={governmentAgencyFilter}
            multiple
            showCheckbox
            displayMode="count"
            menuMinWidth={386}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) =>
              onGovernmentAgencyFilterChange(toSelectedValues(value))
            }
          />
        </Box>

        <Box sx={{ width: 180, minWidth: 0, flexShrink: 0 }}>
          <Dropdown
            label={t.meetingStatus}
            options={statusOptions}
            value={statusFilter}
            multiple
            showCheckbox
            displayMode="count"
            menuMinWidth={280}
            menuMaxHeight={232}
            width="100%"
            onChange={(value) => onStatusFilterChange(toSelectedValues(value))}
          />
        </Box>

        <MeetingDateFilter
          label={t.meetingDate}
          width={165}
          language={language}
          selectedValues={meetingDateFilter}
          onChange={onMeetingDateFilterChange}
        />
      </Box>

      <Box sx={{ flexShrink: 0, display: "flex", justifyContent: "flex-end" }}>
        <CdcGpsfMeetingRequestsViewTabs
          activeView={activeView}
          language={language}
          onViewChange={onViewChange}
        />
      </Box>
    </Box>
  );
}
