'use client';

import React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';

import AudioDescriptionIcon from '@/svgs/AudioDescriptionIcon';
import LibrasIcon from '@/svgs/LibrasIcon';
import CheckedIcon from '@/svgs/CheckedIcon';
import { i18n } from '@/i18n.config'

import styles from './LocaleSwitcher.module.scss';

export default function LocaleSwitcher({ selected = '' }: { selected: string }) {
  const pathname = usePathname();

  const redirectedPathname = (locale: string) => {
    if (!pathname) {
      return '/';
    }

    const isMissingLocale = i18n.locales.every(
      (locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`,
    )

    if (isMissingLocale) {
      if (locale === i18n.defaultLocale) {
        return pathname;
      }

      return `/${locale}${pathname}`;
    } else {
      const segments = pathname.split('/');

      if (locale === i18n.defaultLocale) {
        const isHome = segments.length === 2;

        if (isHome) {
          return '/';
        }

        segments.splice(1, 1);

        return segments.join('/');
      }

      segments[1] = locale;

      return segments.join('/');
    }
  };

  return (
    <div className={styles.LocaleSwitcher}>
      <ol>
        <li>
          <Link
            className={styles[`link${selected === 'pt' ? '--active' : ''}`]}
            href={redirectedPathname('pt')}
          >
            Português
            <span className={styles['icon--checked']}><CheckedIcon /></span>
          </Link>
        </li>
        <li>
          <Link
            className={styles[`link${selected === 'en' ? '--active' : ''}`]}
            href={redirectedPathname('en')}
          >
            English
            <span className={styles['icon--checked']}><CheckedIcon /></span>
          </Link>
        </li>
        <li>
          <Link
            className={styles[`link${selected === 'es' ? '--active' : ''}`]}
            href={redirectedPathname('es')}
          >
            Español
            <span className={styles['icon--checked']}><CheckedIcon /></span>
          </Link>
        </li>
        <li>
          <Link
            className={styles[`link${selected === 'pt-au' ? '--active' : ''}`]}
            href={redirectedPathname('pt-au')}
          >
            <span className={styles.icon}><AudioDescriptionIcon /></span>
            Português-AU
            <span className={styles['icon--checked']}><CheckedIcon /></span>
          </Link>
        </li>
        <li>
          <Link
            className={styles[`link${selected === 'libras' ? '--active' : ''}`]}
            href={redirectedPathname('libras')}
          >
            <span className={styles.icon}><LibrasIcon /></span>
            Libras
            <span className={styles['icon--checked']}><CheckedIcon /></span>
          </Link>
        </li>
      </ol>
    </div>
  );
};
