"use client";

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

import { useAppLanguage } from "@/components/providers/app-language-provider";
import type { LanguageCode } from "./header-data";

const languageOptions: Record<
  LanguageCode,
  {
    flagImage: string;
    label: string;
    nextLanguage: LanguageCode;
    switchLabel: string;
  }
> = {
  kh: {
    flagImage: "/images/logo/km.png",
    label: "Khmer",
    nextLanguage: "en",
    switchLabel: "Switch to English",
  },
  en: {
    flagImage: "/images/logo/en.png",
    label: "English",
    nextLanguage: "kh",
    switchLabel: "ប្តូរទៅភាសាខ្មែរ",
  },
};

export function LanguageSwitcher() {
  const theme = useTheme();
  const { language, setLanguage } = useAppLanguage();
  const currentLanguage = languageOptions[language];

  function handleSwitchLanguage() {
    setLanguage(currentLanguage.nextLanguage);
  }

  return (
    <Tooltip title={currentLanguage.switchLabel} arrow>
      <ButtonBase
        aria-label={currentLanguage.switchLabel}
        onClick={handleSwitchLanguage}
        sx={{
          width: 40,
          height: 40,
          borderRadius: "50%",
          display: "grid",
          placeItems: "center",
          "&:hover": {
            bgcolor: theme.palette.action.hover,
          },
          "&:focus-visible": {
            outline: `2px solid ${theme.palette.primary.main}`,
            outlineOffset: 2,
          },
        }}
      >
        <Box
          sx={{
            width: 28,
            height: 28,
            borderRadius: "50%",
            overflow: "hidden",
            border: `1px solid ${
              theme.palette.mode === "dark"
                ? alpha(theme.palette.common.white, 0.3)
                : alpha(theme.palette.common.black, 0.12)
            }`,
            boxShadow:
              theme.palette.mode === "dark"
                ? "0 1px 4px rgba(0,0,0,0.35)"
                : "0 1px 4px rgba(16,24,40,0.15)",
          }}
        >
          <Box
            component="img"
            src={currentLanguage.flagImage}
            alt={currentLanguage.label}
            sx={{
              width: "100%",
              height: "100%",
              display: "block",
              objectFit: "cover",
            }}
          />
        </Box>
      </ButtonBase>
    </Tooltip>
  );
}
