import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { 
  Hotel, 
  Facebook, 
  Twitter, 
  Instagram, 
  Mail, 
  Phone, 
  MapPin,
  Linkedin,
  Youtube,
  Award,
  Shield,
  Star,
  Trophy,
  Medal,
  BadgeCheck,
  CheckCircle,
  Heart,
  Crown,
  Gem,
  Zap,
  Target,
  TrendingUp,
  LucideIcon
} from 'lucide-react';
import CookiePreferencesLink from '../common/CookiePreferencesLink';
import ChatWidget from '../chat/ChatWidget';
import { pageContentService } from '../../services/api';
import type { PageContent } from '../../services/api/pageContentService';
import { useCompanySettings } from '../../contexts/CompanySettingsContext';

const Footer: React.FC = () => {
  const { settings } = useCompanySettings();
  const [pageContent, setPageContent] = useState<PageContent | null>(null);
  const [enabledPages, setEnabledPages] = useState<Set<string>>(new Set());

  useEffect(() => {
    const fetchPageContent = async () => {
      try {
        const response = await pageContentService.getFooterContent();
        if (response.status === 'success' && response.data?.page_content) {
          setPageContent(response.data.page_content);
        }
      } catch (err: any) {
        console.error('Error fetching footer content:', err);
      }
    };

    const checkEnabledPages = async () => {
      const enabled = new Set<string>();
      const policyPages = [
        { type: 'privacy', url: '/privacy', service: () => pageContentService.getPrivacyContent() },
        { type: 'terms', url: '/terms', service: () => pageContentService.getTermsContent() },
        { type: 'refunds', url: '/refunds', service: () => pageContentService.getRefundsContent() },
        { type: 'cancellation', url: '/cancellation', service: () => pageContentService.getCancellationContent() },
        { type: 'accessibility', url: '/accessibility', service: () => pageContentService.getAccessibilityContent() },
        { type: 'faq', url: '/faq', service: () => pageContentService.getFAQContent() },
      ];

      await Promise.all(
        policyPages.map(async (page) => {
          try {
            const response = await page.service();
            if (response.status === 'success' && response.data?.page_content?.is_active) {
              enabled.add(page.url);
            }
          } catch (err: any) {
            // If 404, page is disabled, don't add to enabled set
            if (err.response?.status !== 404) {
              console.error(`Error checking ${page.type} page:`, err);
            }
          }
        })
      );

      setEnabledPages(enabled);
    };

    fetchPageContent();
    checkEnabledPages();
  }, []);

  
  const displayPhone = settings.company_phone || null;
  const displayEmail = settings.company_email || null;
  const displayAddress = settings.company_address || '123 ABC Street, District 1\nHo Chi Minh City, Vietnam';
  const phoneNumber = displayPhone ? displayPhone.replace(/\s+/g, '').replace(/[()]/g, '') : '';
  const phoneHref = displayPhone ? 'tel:' + phoneNumber : '';
  
  
  const logoUrl = settings.company_logo_url
    ? (settings.company_logo_url.startsWith('http')
        ? settings.company_logo_url
        : `${import.meta.env.VITE_API_URL || 'http://localhost:8000'}${settings.company_logo_url}`)
    : null;

  
  const iconMap: Record<string, LucideIcon> = {
    Award,
    Star,
    Trophy,
    Medal,
    BadgeCheck,
    CheckCircle,
    Shield,
    Heart,
    Crown,
    Gem,
    Zap,
    Target,
    TrendingUp,
  };

  
  const badges = pageContent?.badges || [];

  
  const defaultQuickLinks = [
    { label: 'Home', url: '/' },
    { label: 'Rooms & Suites', url: '/rooms' },
    { label: 'My Bookings', url: '/bookings' },
    { label: 'About Us', url: '/about' }
  ];

  const defaultSupportLinks = [
    { label: 'FAQ', url: '/faq' },
    { label: 'Terms of Service', url: '/terms' },
    { label: 'Privacy Policy', url: '/privacy' },
    { label: 'Refunds Policy', url: '/refunds' },
    { label: 'Cancellation Policy', url: '/cancellation' },
    { label: 'Accessibility', url: '/accessibility' },
    { label: 'Contact Us', url: '/contact' }
  ];

  const quickLinks = pageContent?.footer_links?.quick_links && pageContent.footer_links.quick_links.length > 0
    ? pageContent.footer_links.quick_links
    : defaultQuickLinks;

  const allSupportLinks = pageContent?.footer_links?.support_links && pageContent.footer_links.support_links.length > 0
    ? pageContent.footer_links.support_links
    : defaultSupportLinks;

  // Filter support links to only show enabled policy pages
  const supportLinks = allSupportLinks.filter((link) => {
    // Always show Contact Us
    if (link.url === '/contact') return true;
    // Only show policy pages if they are enabled
    return enabledPages.has(link.url);
  });

  return (
    <footer className="relative bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-black text-gray-300 overflow-hidden">
      {/* Top Gold Accent Line */}
      <div className="absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-[#d4af37] to-transparent shadow-lg shadow-[#d4af37]/50"></div>
      
      {/* Decorative Pattern Overlay */}
      <div className="absolute inset-0 opacity-[0.03]" style={{
        backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M9 0h2v20H9zM25 0h2v20h-2zM41 0h2v20h-2zM57 0h2v20h-2zM0 9h20v2H0zM0 25h20v2H0zM0 41h20v2H0zM0 57h20v2H0zM40 9h20v2H40zM40 25h20v2H40zM40 41h20v2H40zM40 57h20v2H40zM9 40h2v20H9zM25 40h2v20h-2zM41 40h2v20h-2zM57 40h2v20h-2z' fill='%23d4af37'/%3E%3C/svg%3E")`
      }}></div>

      {/* Subtle Gradient Overlay */}
      <div className="absolute inset-0 bg-gradient-to-t from-black/20 via-transparent to-transparent pointer-events-none"></div>

      <div className="relative container mx-auto px-4 sm:px-6 lg:px-8 py-16 sm:py-20 lg:py-24">
        {/* Main Content Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-10 sm:gap-12 lg:gap-16 mb-16 sm:mb-20">
          {/* Brand Section */}
          <div className="lg:col-span-2">
            <div className="flex items-center space-x-4 mb-6 sm:mb-8">
              {logoUrl ? (
                <div className="relative group">
                  <div className="absolute inset-0 bg-gradient-to-r from-[#d4af37]/20 to-transparent rounded-lg blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                  <img 
                    src={logoUrl}
                    alt={settings.company_name}
                    className="h-12 sm:h-14 w-auto object-contain drop-shadow-2xl relative z-10 filter brightness-110"
                  />
                </div>
              ) : (
                <div className="relative group">
                  <div className="p-3 bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 rounded-lg border border-[#d4af37]/20 backdrop-blur-sm">
                    <Hotel className="w-8 h-8 sm:w-10 sm:h-10 text-[#d4af37] relative z-10 drop-shadow-lg" />
                  </div>
                  <div className="absolute inset-0 bg-[#d4af37]/20 blur-2xl opacity-50 group-hover:opacity-75 transition-opacity duration-500"></div>
                </div>
              )}
              <div>
                <h2 className="text-2xl sm:text-3xl font-display font-semibold text-white tracking-tight mb-1">
                  {settings.company_name || pageContent?.title || 'Luxury Hotel'}
                </h2>
                <p className="text-xs sm:text-sm text-[#d4af37] font-light tracking-[3px] sm:tracking-[4px] uppercase">
                  {settings.company_tagline || 'Excellence Redefined'}
                </p>
              </div>
            </div>
            <p className="text-sm sm:text-base text-gray-400 mb-8 leading-relaxed max-w-md font-light">
              {pageContent?.description || 'Experience unparalleled luxury and world-class hospitality. Your journey to exceptional comfort begins here.'}
            </p>
            
            {/* Badges */}
            {badges.length > 0 && badges.some(b => b.text) && (
              <div className="flex flex-wrap items-center gap-4 sm:gap-6 mb-8">
                {badges.map((badge, index) => {
                  if (!badge.text) return null;
                  const BadgeIcon = iconMap[badge.icon] || Award;
                  return (
                    <div 
                      key={index} 
                      className="group flex items-center space-x-2 px-3 py-2 bg-gradient-to-r from-[#d4af37]/5 to-transparent border border-[#d4af37]/10 rounded-lg hover:border-[#d4af37]/30 hover:from-[#d4af37]/10 transition-all duration-300"
                    >
                      <BadgeIcon className="w-4 h-4 sm:w-5 sm:h-5 text-[#d4af37] group-hover:scale-110 transition-transform duration-300" />
                      <span className="text-xs sm:text-sm font-medium tracking-wide text-gray-300 group-hover:text-[#d4af37] transition-colors">{badge.text}</span>
                    </div>
                  );
                })}
              </div>
            )}

            {/* Social Media Links */}
            <div className="flex items-center space-x-3 sm:space-x-4">
              {pageContent?.social_links?.facebook && (
                <a 
                  href={pageContent.social_links.facebook} 
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group relative w-12 h-12 sm:w-14 sm:h-14 flex items-center justify-center rounded-lg bg-gradient-to-br from-gray-800/60 to-gray-900/60 backdrop-blur-sm border border-gray-700/50 hover:border-[#d4af37]/60 transition-all duration-300 hover:bg-gradient-to-br hover:from-[#d4af37]/10 hover:to-[#c9a227]/10 hover:shadow-lg hover:shadow-[#d4af37]/20 hover:-translate-y-0.5"
                  aria-label="Facebook"
                >
                  <Facebook className="w-5 h-5 sm:w-6 sm:h-6 text-gray-400 group-hover:text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                  <div className="absolute inset-0 rounded-lg bg-[#d4af37]/0 group-hover:bg-[#d4af37]/10 blur-xl transition-all duration-500"></div>
                </a>
              )}
              {pageContent?.social_links?.twitter && (
                <a 
                  href={pageContent.social_links.twitter} 
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group relative w-12 h-12 sm:w-14 sm:h-14 flex items-center justify-center rounded-lg bg-gradient-to-br from-gray-800/60 to-gray-900/60 backdrop-blur-sm border border-gray-700/50 hover:border-[#d4af37]/60 transition-all duration-300 hover:bg-gradient-to-br hover:from-[#d4af37]/10 hover:to-[#c9a227]/10 hover:shadow-lg hover:shadow-[#d4af37]/20 hover:-translate-y-0.5"
                  aria-label="Twitter"
                >
                  <Twitter className="w-5 h-5 sm:w-6 sm:h-6 text-gray-400 group-hover:text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                  <div className="absolute inset-0 rounded-lg bg-[#d4af37]/0 group-hover:bg-[#d4af37]/10 blur-xl transition-all duration-500"></div>
                </a>
              )}
              {pageContent?.social_links?.instagram && (
                <a 
                  href={pageContent.social_links.instagram} 
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group relative w-12 h-12 sm:w-14 sm:h-14 flex items-center justify-center rounded-lg bg-gradient-to-br from-gray-800/60 to-gray-900/60 backdrop-blur-sm border border-gray-700/50 hover:border-[#d4af37]/60 transition-all duration-300 hover:bg-gradient-to-br hover:from-[#d4af37]/10 hover:to-[#c9a227]/10 hover:shadow-lg hover:shadow-[#d4af37]/20 hover:-translate-y-0.5"
                  aria-label="Instagram"
                >
                  <Instagram className="w-5 h-5 sm:w-6 sm:h-6 text-gray-400 group-hover:text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                  <div className="absolute inset-0 rounded-lg bg-[#d4af37]/0 group-hover:bg-[#d4af37]/10 blur-xl transition-all duration-500"></div>
                </a>
              )}
              {pageContent?.social_links?.linkedin && (
                <a 
                  href={pageContent.social_links.linkedin} 
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group relative w-12 h-12 sm:w-14 sm:h-14 flex items-center justify-center rounded-lg bg-gradient-to-br from-gray-800/60 to-gray-900/60 backdrop-blur-sm border border-gray-700/50 hover:border-[#d4af37]/60 transition-all duration-300 hover:bg-gradient-to-br hover:from-[#d4af37]/10 hover:to-[#c9a227]/10 hover:shadow-lg hover:shadow-[#d4af37]/20 hover:-translate-y-0.5"
                  aria-label="LinkedIn"
                >
                  <Linkedin className="w-5 h-5 sm:w-6 sm:h-6 text-gray-400 group-hover:text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                  <div className="absolute inset-0 rounded-lg bg-[#d4af37]/0 group-hover:bg-[#d4af37]/10 blur-xl transition-all duration-500"></div>
                </a>
              )}
              {pageContent?.social_links?.youtube && (
                <a 
                  href={pageContent.social_links.youtube} 
                  target="_blank"
                  rel="noopener noreferrer"
                  className="group relative w-12 h-12 sm:w-14 sm:h-14 flex items-center justify-center rounded-lg bg-gradient-to-br from-gray-800/60 to-gray-900/60 backdrop-blur-sm border border-gray-700/50 hover:border-[#d4af37]/60 transition-all duration-300 hover:bg-gradient-to-br hover:from-[#d4af37]/10 hover:to-[#c9a227]/10 hover:shadow-lg hover:shadow-[#d4af37]/20 hover:-translate-y-0.5"
                  aria-label="YouTube"
                >
                  <Youtube className="w-5 h-5 sm:w-6 sm:h-6 text-gray-400 group-hover:text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                  <div className="absolute inset-0 rounded-lg bg-[#d4af37]/0 group-hover:bg-[#d4af37]/10 blur-xl transition-all duration-500"></div>
                </a>
              )}
            </div>
          </div>

          {/* Quick Links */}
          <div>
            <h3 className="text-white font-elegant font-semibold text-lg sm:text-xl mb-6 sm:mb-8 relative inline-block tracking-wide">
              <span className="relative z-10">Quick Links</span>
              <span className="absolute bottom-0 left-0 w-full h-[2px] bg-gradient-to-r from-[#d4af37] via-[#d4af37]/50 to-transparent"></span>
            </h3>
            <ul className="space-y-3 sm:space-y-4">
              {quickLinks.map((link) => (
                <li key={link.url}>
                  <Link 
                    to={link.url}
                    className="group flex items-center text-sm sm:text-base text-gray-400 hover:text-[#d4af37] transition-all duration-300 relative font-light tracking-wide"
                  >
                    <span className="absolute left-0 w-0 h-[2px] bg-gradient-to-r from-[#d4af37] to-[#c9a227] group-hover:w-8 transition-all duration-300 rounded-full"></span>
                    <span className="ml-10 group-hover:translate-x-2 transition-transform duration-300 group-hover:font-medium">{link.label}</span>
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          {/* Guest Services */}
          <div>
            <h3 className="text-white font-elegant font-semibold text-lg sm:text-xl mb-6 sm:mb-8 relative inline-block tracking-wide">
              <span className="relative z-10">Guest Services</span>
              <span className="absolute bottom-0 left-0 w-full h-[2px] bg-gradient-to-r from-[#d4af37] via-[#d4af37]/50 to-transparent"></span>
            </h3>
            <ul className="space-y-3 sm:space-y-4">
              {supportLinks.map((link) => (
                <li key={link.url}>
                  <Link 
                    to={link.url}
                    className="group flex items-center text-sm sm:text-base text-gray-400 hover:text-[#d4af37] transition-all duration-300 relative font-light tracking-wide"
                  >
                    <span className="absolute left-0 w-0 h-[2px] bg-gradient-to-r from-[#d4af37] to-[#c9a227] group-hover:w-8 transition-all duration-300 rounded-full"></span>
                    <span className="ml-10 group-hover:translate-x-2 transition-transform duration-300 group-hover:font-medium">{link.label}</span>
                  </Link>
                </li>
              ))}
            </ul>
          </div>

          {/* Contact Information */}
          <div>
            <h3 className="text-white font-elegant font-semibold text-lg sm:text-xl mb-6 sm:mb-8 relative inline-block tracking-wide">
              <span className="relative z-10">Contact</span>
              <span className="absolute bottom-0 left-0 w-full h-[2px] bg-gradient-to-r from-[#d4af37] via-[#d4af37]/50 to-transparent"></span>
            </h3>
            <ul className="space-y-5 sm:space-y-6">
              <li className="flex items-start space-x-4 group">
                <div className="relative mt-1 flex-shrink-0">
                  <div className="p-2 bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 rounded-lg border border-[#d4af37]/20 group-hover:border-[#d4af37]/40 transition-all duration-300">
                    <MapPin className="w-4 h-4 sm:w-5 sm:h-5 text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                  </div>
                  <div className="absolute inset-0 bg-[#d4af37]/20 blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                </div>
                <span className="text-sm sm:text-base text-gray-400 group-hover:text-gray-300 transition-colors leading-relaxed font-light pt-1">
                  {(displayAddress
                    .split('\n').map((line, i) => (
                      <React.Fragment key={i}>
                        {line}
                        {i < displayAddress.split('\n').length - 1 && <br />}
                      </React.Fragment>
                    )))}
                </span>
              </li>
              {displayPhone && (
                <li className="flex items-center space-x-4 group">
                  <div className="relative flex-shrink-0">
                    <div className="p-2 bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 rounded-lg border border-[#d4af37]/20 group-hover:border-[#d4af37]/40 transition-all duration-300">
                      <Phone className="w-4 h-4 sm:w-5 sm:h-5 text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                    </div>
                    <div className="absolute inset-0 bg-[#d4af37]/20 blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                  </div>
                  <a href={phoneHref} className="text-sm sm:text-base text-gray-400 group-hover:text-[#d4af37] transition-colors font-light tracking-wide">
                    {displayPhone}
                  </a>
                </li>
              )}
              {displayEmail && (
                <li className="flex items-center space-x-4 group">
                  <div className="relative flex-shrink-0">
                    <div className="p-2 bg-gradient-to-br from-[#d4af37]/10 to-[#c9a227]/5 rounded-lg border border-[#d4af37]/20 group-hover:border-[#d4af37]/40 transition-all duration-300">
                      <Mail className="w-4 h-4 sm:w-5 sm:h-5 text-[#d4af37] transition-all duration-300 group-hover:scale-110" />
                    </div>
                    <div className="absolute inset-0 bg-[#d4af37]/20 blur-xl opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                  </div>
                  <a href={`mailto:${displayEmail}`} className="text-sm sm:text-base text-gray-400 group-hover:text-[#d4af37] transition-colors font-light tracking-wide break-all">
                    {displayEmail}
                  </a>
                </li>
              )}
            </ul>

            {/* Rating Section */}
            <div className="mt-8 sm:mt-10 pt-6 sm:pt-8 border-t border-gray-800/50">
              <div className="flex items-center space-x-1 mb-3">
                {[...Array(5)].map((_, i) => (
                  <Star key={i} className="w-4 h-4 sm:w-5 sm:h-5 fill-[#d4af37] text-[#d4af37] drop-shadow-lg" />
                ))}
              </div>
              <p className="text-xs sm:text-sm text-gray-500 font-light tracking-wide">Rated 5.0 by 10,000+ guests</p>
            </div>
          </div>
        </div>

        {/* Divider */}
        <div className="relative my-12 sm:my-16">
          <div className="absolute inset-0 flex items-center">
            <div className="w-full border-t border-gray-800/50"></div>
          </div>
          <div className="relative flex justify-center">
            <div className="bg-gradient-to-b from-[#0f0f0f] to-[#1a1a1a] px-6">
              <div className="w-24 sm:w-32 h-[2px] bg-gradient-to-r from-transparent via-[#d4af37]/50 to-transparent shadow-lg shadow-[#d4af37]/30"></div>
            </div>
          </div>
        </div>

        {/* Bottom Section */}
        <div className="flex flex-col md:flex-row justify-between items-center space-y-4 md:space-y-0">
          <div className="text-sm sm:text-base text-gray-500 font-light tracking-wide text-center md:text-left">
            {(() => {
              const currentYear = new Date().getFullYear();
              const copyrightText = pageContent?.copyright_text || '© {YEAR} Luxury Hotel. All rights reserved.';
              
              return copyrightText.replace(/{YEAR}/g, currentYear.toString());
            })()}
          </div>
          <div className="flex items-center space-x-4 sm:space-x-6 text-xs sm:text-sm text-gray-600">
            <Link to="/privacy" className="hover:text-[#d4af37] transition-colors cursor-pointer font-light tracking-wide">Privacy</Link>
            <span className="text-gray-700">•</span>
            <Link to="/terms" className="hover:text-[#d4af37] transition-colors cursor-pointer font-light tracking-wide">Terms</Link>
            <span className="text-gray-700">•</span>
            <Link to="/refunds" className="hover:text-[#d4af37] transition-colors cursor-pointer font-light tracking-wide">Refunds</Link>
            <span className="text-gray-700">•</span>
            <CookiePreferencesLink />
          </div>
        </div>
      </div>

      {/* Bottom Gold Accent Line */}
      <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-[#d4af37] to-transparent shadow-lg shadow-[#d4af37]/50"></div>
      
      {/* Chat Widget */}
      <ChatWidget />
    </footer>
  );
};

export default Footer;
