'use client';

import { useEffect, useState } from 'react';
import { TLocales } from '@/models/layout';
import images from '@/assets/images/images';
import Image from 'next/image';
import { useTranslations } from 'next-intl';

const languages = [
  {
    title: 'EN',
    image: images.en,
    locale: 'en',
  },
  {
    title: 'FA',
    image: images.fa,
    locale: 'fa',
  },
];

export default function ModalLanguageSelector() {
  const [show, setShow] = useState(false);
  const t = useTranslations();
  useEffect(() => {
    const selected = localStorage.getItem('selectedLocale');
    const cookieLocale = document.cookie
      .split('; ')
      .find((item) => item.startsWith('locale='))
      ?.split('=')[1];

    if (!selected && !cookieLocale) setShow(true);
  }, []);

  const changeLocale = (locale: TLocales) => {
    localStorage.setItem('selectedLocale', locale);
    document.cookie = `locale=${locale}; path=/; max-age=31536000; samesite=lax`;
    const path = window.location.pathname.replace(/^\/(en|fa)/, '');
    window.location.pathname = `/${locale}${path}`;
  };
  const closeModal = () => setShow(false);

  if (!show) return null;

  return (
    <div
      className="fixed inset-0 z-100 flex items-center justify-center bg-black/50 backdrop-blur-sm"
      onClick={closeModal}
    >
      <div className="relative h-auto w-100 rounded-3xl bg-white p-6 shadow-2xl">
        <div className="flex justify-around gap-4">
          {languages.map((lang) => (
            <div
              key={lang.locale}
              onClick={() => changeLocale(lang.locale as TLocales)}
              className="flex w-32 flex-col items-center justify-between gap-2 rounded-xl border border-gray-300 bg-gray-50 px-4 py-3 text-sm font-medium text-gray-700 shadow-sm transition-all hover:border-blue-400 hover:bg-blue-100"
            >
              <span className="text-2xl">
                <Image src={lang.image} alt={lang.title} className="w-100" />
              </span>
              {lang.title}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
