/**
 * Cookie Consent Banner
 * GDPR Compliant
 */

'use client';

import React, { useState } from 'react';
import { Link, usePathname } from '@/i18n/navigation';
import { useTranslations } from 'next-intl';
import { motion, AnimatePresence } from 'framer-motion';
import { Cookie, X, Settings, Check, Shield } from 'lucide-react';
import { useCookieConsent } from '@/lib/context/cookie-context';
import type { CookiePreferences } from '@/lib/api/gdpr';

export default function CookieConsent() {
  const t = useTranslations('components.cookieConsent');
  const {
    preferences,
    showBanner,
    showSettings,
    isLoading,
    setShowBanner,
    setShowSettings,
    acceptAll,
    acceptEssentialOnly,
    savePreferences,
    openPreferences,
  } = useCookieConsent();

  const [localPrefs, setLocalPrefs] = useState<CookiePreferences>(preferences);
  const pathname = usePathname();
  const isDashboard = pathname?.startsWith('/dashboard');
  const mobileOffset = isDashboard ? 'bottom-16 lg:bottom-0' : 'bottom-0';
  const mobileButtonOffset = isDashboard ? 'bottom-20 lg:bottom-4' : 'bottom-4';

  React.useEffect(() => {
    setLocalPrefs(preferences);
  }, [preferences]);

  const handleSaveCustom = async () => {
    await savePreferences(localPrefs);
  };

  if (isLoading) {
    return null;
  }

  return (
    <>
      {/* Floating Cookie Button (shown when banner is closed) */}
      <AnimatePresence>
        {!showBanner && (
          <motion.button
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            transition={{ type: 'spring', stiffness: 260, damping: 20 }}
            onClick={openPreferences}
            className={`fixed left-4 z-40 p-3 bg-brand-navy text-white rounded-full shadow-lg hover:bg-brand-navy/90 focus:outline-none focus:ring-2 focus:ring-brand-turquoise focus:ring-offset-2 transition-colors ${mobileButtonOffset}`}
            aria-label={t('openAria')}
          >
            <Cookie className="w-5 h-5" />
          </motion.button>
        )}
      </AnimatePresence>

      {/* Cookie Banner */}
      <AnimatePresence>
        {showBanner && (
          <motion.div
            initial={{ y: 100, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 100, opacity: 0 }}
            transition={{ type: 'spring', stiffness: 300, damping: 30 }}
            className={`fixed left-0 right-0 z-50 bg-white border-t border-gray-200 shadow-2xl ${mobileOffset}`}
          >
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
              <AnimatePresence mode="wait">
                {!showSettings ? (
                  // Simple banner
                  <motion.div
                    key="simple"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                    className="flex flex-col lg:flex-row items-start lg:items-center justify-between gap-4"
                  >
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        <Cookie className="w-5 h-5 text-brand-navy" />
                        <h3 className="text-lg font-semibold text-brand-navy">
                          {t('banner.title')}
                        </h3>
                      </div>
                      <p className="text-sm text-gray-600 max-w-2xl">
                        {t('banner.body')}{' '}
                        <Link
                          href="/cookies"
                          className="text-brand-turquoise hover:text-brand-turquoise/80 underline"
                        >
                          {t('banner.learnMore')}
                        </Link>
                      </p>
                    </div>

                    <div className="flex flex-col sm:flex-row gap-3 w-full lg:w-auto">
                      <button
                        onClick={() => setShowSettings(true)}
                        className="flex items-center justify-center gap-2 px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-turquoise transition-colors"
                      >
                        <Settings className="w-4 h-4" />
                        {t('banner.customize')}
                      </button>
                      <button
                        onClick={acceptEssentialOnly}
                        className="px-4 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-turquoise transition-colors"
                      >
                        {t('banner.essentialOnly')}
                      </button>
                      <button
                        onClick={acceptAll}
                        className="flex items-center justify-center gap-2 px-6 py-2.5 text-sm font-medium text-white bg-brand-navy rounded-lg hover:bg-brand-navy/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-turquoise transition-colors"
                      >
                        <Check className="w-4 h-4" />
                        {t('banner.acceptAll')}
                      </button>
                    </div>
                  </motion.div>
                ) : (
                  // Detailed settings
                  <motion.div
                    key="settings"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    exit={{ opacity: 0 }}
                  >
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center gap-2">
                        <Shield className="w-5 h-5 text-brand-navy" />
                        <h3 className="text-lg font-semibold text-brand-navy">
                          {t('settings.title')}
                        </h3>
                      </div>
                      <button
                        onClick={() => setShowSettings(false)}
                        className="p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100 transition-colors"
                        aria-label={t('settings.closeAria')}
                      >
                        <X className="w-5 h-5" />
                      </button>
                    </div>

                    <div className="grid gap-3 mb-6 max-h-[40vh] overflow-y-auto pr-2">
                      {/* Essential Cookies */}
                      <div className="flex items-start justify-between p-4 bg-gray-50 rounded-lg border border-gray-100">
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <h4 className="text-sm font-semibold text-gray-900">
                              {t('settings.essential.title')}
                            </h4>
                            <span className="px-2 py-0.5 text-xs font-medium text-brand-navy bg-brand-navy/10 rounded-full">
                              {t('settings.essential.alwaysOn')}
                            </span>
                          </div>
                          <p className="mt-1 text-sm text-gray-600">
                            {t('settings.essential.body')}
                          </p>
                        </div>
                        <div className="ml-4 flex items-center">
                          <input
                            type="checkbox"
                            checked={true}
                            disabled
                            className="h-5 w-5 text-brand-navy border-gray-300 rounded cursor-not-allowed opacity-60"
                          />
                        </div>
                      </div>

                      {/* Functional Cookies */}
                      <div className="flex items-start justify-between p-4 bg-gray-50 rounded-lg border border-gray-100">
                        <div className="flex-1">
                          <h4 className="text-sm font-semibold text-gray-900">
                            {t('settings.functional.title')}
                          </h4>
                          <p className="mt-1 text-sm text-gray-600">
                            {t('settings.functional.body')}
                          </p>
                        </div>
                        <div className="ml-4 flex items-center">
                          <input
                            type="checkbox"
                            checked={localPrefs.functional}
                            onChange={e =>
                              setLocalPrefs({ ...localPrefs, functional: e.target.checked })
                            }
                            className="h-5 w-5 text-brand-navy border-gray-300 rounded focus:ring-brand-turquoise cursor-pointer"
                          />
                        </div>
                      </div>

                      {/* Analytics Cookies */}
                      <div className="flex items-start justify-between p-4 bg-gray-50 rounded-lg border border-gray-100">
                        <div className="flex-1">
                          <h4 className="text-sm font-semibold text-gray-900">
                            {t('settings.analytics.title')}
                          </h4>
                          <p className="mt-1 text-sm text-gray-600">
                            {t('settings.analytics.body')}
                          </p>
                        </div>
                        <div className="ml-4 flex items-center">
                          <input
                            type="checkbox"
                            checked={localPrefs.analytics}
                            onChange={e =>
                              setLocalPrefs({ ...localPrefs, analytics: e.target.checked })
                            }
                            className="h-5 w-5 text-brand-navy border-gray-300 rounded focus:ring-brand-turquoise cursor-pointer"
                          />
                        </div>
                      </div>

                      {/* Marketing Cookies */}
                      <div className="flex items-start justify-between p-4 bg-gray-50 rounded-lg border border-gray-100">
                        <div className="flex-1">
                          <h4 className="text-sm font-semibold text-gray-900">
                            {t('settings.marketing.title')}
                          </h4>
                          <p className="mt-1 text-sm text-gray-600">
                            {t('settings.marketing.body')}
                          </p>
                        </div>
                        <div className="ml-4 flex items-center">
                          <input
                            type="checkbox"
                            checked={localPrefs.marketing}
                            onChange={e =>
                              setLocalPrefs({ ...localPrefs, marketing: e.target.checked })
                            }
                            className="h-5 w-5 text-brand-navy border-gray-300 rounded focus:ring-brand-turquoise cursor-pointer"
                          />
                        </div>
                      </div>
                    </div>

                    <div className="flex flex-col sm:flex-row gap-3">
                      <button
                        onClick={handleSaveCustom}
                        className="flex-1 flex items-center justify-center gap-2 px-6 py-2.5 text-sm font-medium text-white bg-brand-navy rounded-lg hover:bg-brand-navy/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-turquoise transition-colors"
                      >
                        <Check className="w-4 h-4" />
                        {t('settings.save')}
                      </button>
                      <button
                        onClick={acceptAll}
                        className="flex-1 px-6 py-2.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-brand-turquoise transition-colors"
                      >
                        {t('settings.acceptAll')}
                      </button>
                    </div>

                    <p className="mt-4 text-xs text-gray-500 text-center">
                      {t('settings.footer')}{' '}
                      <Link href="/cookies" className="text-brand-turquoise hover:underline">
                        {t('settings.policyLink')}
                      </Link>
                    </p>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
