"use client";

import type { ComponentType } from "react";

import ButtonBase from "@mui/material/ButtonBase";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import type { SvgIconProps } from "@mui/material/SvgIcon";
import { alpha, type SxProps, type Theme, useTheme } from "@mui/material/styles";

import { GridViewIcon, ListViewIcon } from "@/components/ui/icon";

export type ListGridViewMode = "list" | "grid";

export type ListGridViewToggleProps<T extends string = ListGridViewMode> = {
  value: T;
  onChange?: (value: T) => void;
  listLabel?: string;
  gridLabel?: string;
  listValue?: T;
  gridValue?: T;
  ListIcon?: ComponentType<SvgIconProps>;
  GridIcon?: ComponentType<SvgIconProps>;
  fontFamily?: string;
  sx?: SxProps<Theme>;
};

export function ListGridViewToggle<T extends string = ListGridViewMode>({
  value,
  onChange,
  listLabel = "List",
  gridLabel = "Grid",
  listValue = "list" as T,
  gridValue = "grid" as T,
  ListIcon = ListViewIcon,
  GridIcon = GridViewIcon,
  fontFamily,
  sx,
}: ListGridViewToggleProps<T>) {
  const theme = useTheme();
  const isDark = theme.palette.mode === "dark";

  const options = [
    { key: listValue, label: listLabel, Icon: ListIcon },
    { key: gridValue, label: gridLabel, Icon: GridIcon },
  ];

  return (
    <Stack
      direction="row"
      sx={[
        {
          width: 150,
          height: 40,
          bgcolor: isDark ? alpha("#ffffff", 0.04) : "#ffffff",
          border: `1px solid ${isDark ? alpha("#ffffff", 0.12) : "#f5f5f5"}`,
          borderRadius: "6px",
          p: "3px",
          gap: "3px",
          flexShrink: 0,
        },
        ...(Array.isArray(sx) ? sx : sx ? [sx] : []),
      ]}
    >
      {options.map(({ key, label, Icon }) => {
        const active = value === key;

        return (
          <ButtonBase
            key={key}
            onClick={() => onChange?.(key)}
            sx={{
              flex: 1,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              gap: 1,
              height: 31,
              borderRadius: "2px",
              color: active
                ? theme.palette.primary.contrastText
                : theme.palette.text.primary,
              bgcolor: active
                ? theme.palette.primary.main
                : isDark
                  ? alpha("#ffffff", 0.04)
                  : "#ffffff",
            }}
          >
            <Icon sx={{ fontSize: 20, color: "inherit" }} />
            <Typography
              sx={{
                fontSize: 12,
                fontWeight: 500,
                color: "inherit",
                ...(fontFamily ? { fontFamily } : {}),
              }}
            >
              {label}
            </Typography>
          </ButtonBase>
        );
      })}
    </Stack>
  );
}
