import { Select, Group, Text } from '@pikku/mantine/core'
import { useLocation, useNavigate, useParams, useRouter } from '@tanstack/react-router'
import { LANGUAGES } from '@/config'
import { useI18n } from '@/context/i18n-provider'

export default function LanguageSelector() {
  const t = useI18n()
  const params = useParams({ strict: false }) as { lang?: string }
  const pathname = useLocation({ select: (l) => l.pathname })
  const navigate = useNavigate()
  const router = useRouter()

  // Extract lang from params or pathname (for routes like /en/legal/imprint)
  const lang = params.lang || pathname.split('/')[1]

  const selectedLanguage = LANGUAGES.find(language => language.value === lang)!

  const switchLanguage = (to: string | null) => {
    if (to && to !== lang) {
      // Store language preference in cookie
      document.cookie = `NEXT_LOCALE=${to}; path=/; max-age=31536000; SameSite=Lax`

      // Create new path with updated language
      const newPath = pathname.replace(`/${lang}`, `/${to}`)

      // Navigate to new language
      navigate({ to: newPath })
      router.invalidate()
    }
  }

  return (
    <Select
      size='sm'
      w={140}
      value={lang}
      data={LANGUAGES}
      onChange={switchLanguage}
      leftSection={<img src={selectedLanguage.flag} alt={selectedLanguage.label} width={18} height={18} />}
      renderOption={({ option }) => {
        const language = LANGUAGES.find(lang => lang.value === option.value)
        if (language) {
          return (
            <Group gap="xs">
              <img
                src={language.flag}
                alt={language.label}
                width={18}
                height={18}
              />
              <Text visibleFrom='md'>{t(`language.${language.value}` as any)}</Text>
            </Group>
          )
        }
      }}
    />
  )
}
