'use client'

import { ChevronDown } from 'lucide-react'
import Link from 'next/link'
import { useEffect, useRef, useState } from 'react'
import {
  type DashboardLanguage,
  useDashboardI18n,
} from '@/components/I18nProvider'
import { carplaceUrl } from '@/lib/urls'

type FooterItem = {
  label: string
  href?: string
}

const appPrivacyHref = {
  en: `${carplaceUrl}/app-privacy-en`,
  fr: `${carplaceUrl}/app-privacy-fr`,
  ar: `${carplaceUrl}/app-privacy-ar`,
} as const

const localeOptions: Array<{ value: DashboardLanguage; label: string; flag: string }> = [
  { value: 'en', label: 'Global (English)', flag: '🇺🇸' },
  { value: 'ar', label: 'North Africa (Arabic)', flag: '🇲🇦' },
  { value: 'fr', label: 'Europe (French)', flag: '🇫🇷' },
]

function getFooterContent(language: DashboardLanguage): {
  primary: FooterItem[]
  secondary: FooterItem[]
  localeLabel: string
  rightsLabel: string
} {
  switch (language) {
    case 'fr':
      return {
        primary: [
          { label: 'À propos de nous', href: `${carplaceUrl}/footer/about-us` },
          { label: 'Conditions d’utilisation', href: `${carplaceUrl}/footer/terms-of-service` },
          { label: 'Sécurité', href: `${carplaceUrl}/footer/security` },
          { label: 'Conformité', href: `${carplaceUrl}/footer/compliance` },
          { label: 'Politique de confidentialité', href: appPrivacyHref.fr },
          { label: 'Politique relative aux cookies', href: `${carplaceUrl}/footer/cookie-policy` },
        ],
        secondary: [
          { label: 'Newsletter', href: `${carplaceUrl}/footer/newsletter` },
          { label: 'Contacter les ventes', href: `${carplaceUrl}/footer/contact-sales` },
          { label: 'Conditions générales', href: `${carplaceUrl}/footer/general-conditions` },
        ],
        localeLabel: 'Europe (French)',
        rightsLabel: 'Tous droits réservés.',
      }
    case 'ar':
      return {
        primary: [
          { label: 'من نحن', href: `${carplaceUrl}/footer/about-us` },
          { label: 'شروط الاستخدام', href: `${carplaceUrl}/footer/terms-of-service` },
          { label: 'الأمان', href: `${carplaceUrl}/footer/security` },
          { label: 'الامتثال', href: `${carplaceUrl}/footer/compliance` },
          { label: 'سياسة الخصوصية', href: appPrivacyHref.ar },
          { label: 'سياسة ملفات تعريف الارتباط', href: `${carplaceUrl}/footer/cookie-policy` },
        ],
        secondary: [
          { label: 'النشرة الإخبارية', href: `${carplaceUrl}/footer/newsletter` },
          { label: 'تواصل مع المبيعات', href: `${carplaceUrl}/footer/contact-sales` },
          { label: 'الشروط العامة', href: `${carplaceUrl}/footer/general-conditions` },
        ],
        localeLabel: 'North Africa (Arabic)',
        rightsLabel: 'جميع الحقوق محفوظة.',
      }
    case 'en':
    default:
      return {
        primary: [
          { label: 'About Us', href: `${carplaceUrl}/footer/about-us` },
          { label: 'Terms of Service', href: `${carplaceUrl}/footer/terms-of-service` },
          { label: 'Security', href: `${carplaceUrl}/footer/security` },
          { label: 'Compliance', href: `${carplaceUrl}/footer/compliance` },
          { label: 'Privacy Policy', href: appPrivacyHref.en },
          { label: 'Cookie Policy', href: `${carplaceUrl}/footer/cookie-policy` },
        ],
        secondary: [
          { label: 'Newsletter', href: `${carplaceUrl}/footer/newsletter` },
          { label: 'Contact Sales', href: `${carplaceUrl}/footer/contact-sales` },
          { label: 'General Conditions', href: `${carplaceUrl}/footer/general-conditions` },
        ],
        localeLabel: 'Global (English)',
        rightsLabel: 'All rights reserved.',
      }
  }
}

export default function PublicFooter() {
  const { language, setLanguage } = useDashboardI18n()
  const footerContent = getFooterContent(language)
  const availableLocaleOptions = localeOptions.filter((option) => option.value !== language)
  const currentLocale = localeOptions.find((option) => option.value === language) ?? localeOptions[0]
  const localeMenuRef = useRef<HTMLDivElement | null>(null)
  const [localeMenuOpen, setLocaleMenuOpen] = useState(false)

  useEffect(() => {
    function handlePointerDown(event: MouseEvent) {
      if (!localeMenuRef.current?.contains(event.target as Node)) {
        setLocaleMenuOpen(false)
      }
    }

    document.addEventListener('mousedown', handlePointerDown)
    return () => document.removeEventListener('mousedown', handlePointerDown)
  }, [])

  return (
    <footer className="border-t border-stone-200/80 bg-white/72 px-4 py-8 text-stone-600 backdrop-blur-xl transition-colors dark:border-blue-900 dark:bg-blue-950/72 dark:text-stone-300">
      <div className="mx-auto flex max-w-7xl flex-col items-center gap-5 px-0 text-center sm:px-2 lg:px-0">
        <nav className="flex flex-wrap items-center justify-center gap-y-3 text-sm">
          {footerContent.primary.map((item, index) => (
            <div key={item.label} className="flex items-center">
              <FooterNavItem item={item} />
              {index < footerContent.primary.length - 1 ? (
                <span className="px-2 text-stone-400 dark:text-stone-600" aria-hidden="true">|</span>
              ) : null}
            </div>
          ))}
        </nav>

        <div className="flex flex-wrap items-center justify-center gap-y-3 text-sm">
          {footerContent.secondary.map((item) => (
            <div key={item.label} className="flex items-center">
              <FooterNavItem item={item} />
              <span className="px-2 text-stone-400 dark:text-stone-600" aria-hidden="true">|</span>
            </div>
          ))}
          <div ref={localeMenuRef} className="relative px-3">
            <button
              type="button"
              onClick={() => setLocaleMenuOpen((open) => !open)}
              className="inline-flex items-center gap-2 text-orange-700 transition hover:text-blue-900 dark:text-orange-300 dark:hover:text-stone-100"
              aria-expanded={localeMenuOpen}
              aria-haspopup="menu"
            >
              <span aria-hidden="true" className="text-base leading-none">{currentLocale.flag}</span>
              <span>{footerContent.localeLabel}</span>
              <ChevronDown className={`h-4 w-4 transition-transform ${localeMenuOpen ? 'rotate-180' : ''}`} />
            </button>
            {localeMenuOpen ? (
              <div className="absolute left-1/2 top-full z-20 mt-3 w-56 -translate-x-1/2 overflow-hidden rounded-2xl border border-stone-200 bg-white/95 text-left shadow-[0_20px_60px_rgba(0,0,0,0.12)] backdrop-blur dark:border-blue-900 dark:bg-blue-950/95 dark:shadow-[0_20px_60px_rgba(0,0,0,0.35)]">
                {availableLocaleOptions.map((option) => (
                  <button
                    key={option.value}
                    type="button"
                    onClick={() => {
                      setLanguage(option.value)
                      setLocaleMenuOpen(false)
                    }}
                    className="flex w-full items-center gap-3 px-4 py-3 text-sm text-stone-700 transition hover:bg-stone-100 hover:text-blue-900 dark:text-stone-200 dark:hover:bg-blue-900/40 dark:hover:text-white"
                  >
                    <span aria-hidden="true" className="text-base leading-none">{option.flag}</span>
                    <span>{option.label}</span>
                  </button>
                ))}
              </div>
            ) : null}
          </div>
        </div>

        <p className="text-sm text-stone-500 dark:text-stone-400">
          &copy; {new Date().getFullYear()} RentalDriveGo. {footerContent.rightsLabel}
        </p>
      </div>
    </footer>
  )
}

function FooterNavItem({ item }: { item: FooterItem }) {
  const className = 'px-3 text-stone-600 transition hover:text-blue-900 dark:text-stone-300 dark:hover:text-white'

  if (item.href) {
    return (
      <Link href={item.href} className={className}>
        {item.label}
      </Link>
    )
  }

  return <span className={className}>{item.label}</span>
}
