import { Select, Text, Box } from "@mantine/core";
import { Trans, useLingui } from "@lingui/react/macro";
import { updateUserLocale } from "@/features/settings/server";
import { useAuth } from "@/contexts/auth-context";
import {
  ensureMessages,
  resolveLocale,
  LOCALE_LABELS,
  SUPPORTED_LOCALES,
  type AppLocale,
} from "@/lib/i18n";

const LocalePicker = () => {
  const { metadata, user, set } = useAuth();
  const { t } = useLingui();

  const handleChange = async (value: string | null) => {
    if (!value || !user) return;
    const locale = resolveLocale(value);
    await ensureMessages(locale);
    await updateUserLocale({ data: locale });
    set({ metadata: { ...metadata, locale } });
  };

  return (
    <Box>
      <Text fw={500} size="sm" mb="xs">
        <Trans>Language</Trans>
      </Text>
      <Select
        aria-label={t`Language`}
        data={SUPPORTED_LOCALES.map((locale: AppLocale) => ({
          value: locale,
          label: LOCALE_LABELS[locale],
        }))}
        value={resolveLocale(metadata.locale)}
        onChange={handleChange}
        allowDeselect={false}
      />
    </Box>
  );
};

export default LocalePicker;
