import React, { forwardRef } from 'react';
import { clsx } from 'clsx';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  Heart,
  ExternalLink,
  Mail,
  Phone,
  Globe,
  FileText,
  HelpCircle,
  MessageSquare
} from 'lucide-react';

export interface FooterLink {
  id: string;
  label: string;
  href: string;
  external?: boolean;
  icon?: React.ComponentType<{ className?: string }>;
}

export interface FooterSection {
  id: string;
  title: string;
  links: FooterLink[];
}

export interface SocialLink {
  id: string;
  label: string;
  href: string;
  icon: React.ComponentType<{ className?: string }>;
}

export interface CompanyInfo {
  name: string;
  description?: string;
  logo?: React.ReactNode;
  email?: string;
  phone?: string;
  address?: string;
  website?: string;
}

export interface FooterProps {
  className?: string;
  /**
   * Company information
   */
  companyInfo?: CompanyInfo;
  /**
   * Footer sections with links
   */
  sections?: FooterSection[];
  /**
   * Social media links
   */
  socialLinks?: SocialLink[];
  /**
   * Copyright text (auto-generated if not provided)
   */
  copyrightText?: string;
  /**
   * Show version info
   */
  showVersion?: boolean;
  /**
   * Version string
   */
  version?: string;
  /**
   * Show language selector
   */
  showLanguageSelector?: boolean;
  /**
   * Available languages
   */
  languages?: Array<{ code: string; name: string }>;
  /**
   * Current language
   */
  currentLanguage?: string;
  /**
   * Language change handler
   */
  onLanguageChange?: (language: string) => void;
  /**
   * Show theme toggle
   */
  showThemeToggle?: boolean;
  /**
   * Theme toggle handler
   */
  onThemeToggle?: () => void;
  /**
   * Show privacy links
   */
  showPrivacyLinks?: boolean;
  /**
   * Compact mode (smaller footer)
   */
  compact?: boolean;
  /**
   * Custom content
   */
  children?: React.ReactNode;
}

export interface FooterRef {
  scrollIntoView: () => void;
}

/**
 * Footer - Application footer with links and copyright info
 * 
 * Features:
 * - Company information and branding
 * - Organized link sections for easy navigation
 * - Social media links with proper icons
 * - Copyright notice with automatic year
 * - Version information display
 * - Language selector for i18n
 * - Privacy and legal links
 * - Responsive design with mobile adaptations
 * - Accessible link handling with external indicators
 * - Customizable sections and content
 */
export const Footer = forwardRef<FooterRef, FooterProps>(({
  className,
  companyInfo,
  sections,
  socialLinks,
  copyrightText,
  showVersion = true,
  version = '2.0.0',
  showPrivacyLinks = true,
  compact = false,
  children,
}, ref) => {
  const { t } = useTranslation();
  const footerRef = React.useRef<HTMLDivElement>(null);
  const currentYear = new Date().getFullYear();

  // Company info - full for public pages, minimal for internal
  const defaultCompanyInfo: CompanyInfo = compact ? {
    name: t('common:app.name', 'Panadería IA'),
  } : {
    name: t('common:app.name', 'Panadería IA'),
    description: t('common:footer.company_description', 'Sistema inteligente de gestión para panaderías. Optimiza tu producción, inventario y ventas con inteligencia artificial.'),
    email: 'contact@bakewise.ai',
    website: 'https://bakewise.ai',
  };

  const company = companyInfo || defaultCompanyInfo;

  // Sections - full for public pages, empty for internal
  const defaultSections: FooterSection[] = compact ? [] : [
    {
      id: 'product',
      title: t('common:footer.sections.product', 'Producto'),
      links: [
        { id: 'features', label: t('common:footer.links.features', 'Funcionalidades'), href: '/features' },
        { id: 'dashboard', label: t('common:footer.links.dashboard', 'Dashboard'), href: '/dashboard' },
        { id: 'inventory', label: t('common:footer.links.inventory', 'Inventario'), href: '/inventory' },
        { id: 'production', label: t('common:footer.links.production', 'Producción'), href: '/production' },
        { id: 'sales', label: t('common:footer.links.sales', 'Ventas'), href: '/sales' },
        { id: 'forecasting', label: t('common:footer.links.forecasting', 'Predicciones'), href: '/forecasting' },
      ],
    },
    {
      id: 'support',
      title: t('common:footer.sections.support', 'Soporte'),
      links: [
        { id: 'help', label: t('common:footer.links.help', 'Centro de Ayuda'), href: '/help', icon: HelpCircle },
        { id: 'docs', label: t('common:footer.links.docs', 'Documentación'), href: '/help/docs', icon: FileText },
        { id: 'contact', label: t('common:footer.links.contact', 'Contacto'), href: '/help/support', icon: MessageSquare },
        { id: 'feedback', label: t('common:footer.links.feedback', 'Feedback'), href: '/help/feedback' },
      ],
    },
    {
      id: 'company',
      title: t('common:footer.sections.company', 'Empresa'),
      links: [
        { id: 'about', label: t('common:footer.links.about', 'Acerca de'), href: '/about' },
        { id: 'blog', label: t('common:footer.links.blog', 'Blog'), href: '/blog' },
        { id: 'careers', label: t('common:footer.links.careers', 'Empleo'), href: '/careers' },
      ],
    },
  ];

  const footerSections = sections || defaultSections;

  // Social links - none for internal business application, full set for public pages
  const defaultSocialLinks: SocialLink[] = [];

  const socialLinksToShow = socialLinks || defaultSocialLinks;


  // Scroll into view
  const scrollIntoView = React.useCallback(() => {
    footerRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }, []);

  // Expose ref methods
  React.useImperativeHandle(ref, () => ({
    scrollIntoView,
  }), [scrollIntoView]);

  // Render link
  const renderLink = (link: FooterLink) => {
    const LinkIcon = link.icon;

    const linkContent = (
      <span className="flex items-center gap-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] transition-colors duration-200">
        {LinkIcon && <LinkIcon className="w-4 h-4" />}
        {link.label}
        {link.external && <ExternalLink className="w-3 h-3" />}
      </span>
    );

    if (link.external) {
      return (
        <a
          key={link.id}
          href={link.href}
          target="_blank"
          rel="noopener noreferrer"
          className="hover:underline focus:outline-none focus:underline"
        >
          {linkContent}
        </a>
      );
    }

    return (
      <Link
        key={link.id}
        to={link.href}
        className="hover:underline focus:outline-none focus:underline"
      >
        {linkContent}
      </Link>
    );
  };

  // Render social link
  const renderSocialLink = (social: SocialLink) => {
    const SocialIcon = social.icon;

    return (
      <a
        key={social.id}
        href={social.href}
        target="_blank"
        rel="noopener noreferrer"
        className="p-2 rounded-lg text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-secondary)] transition-colors duration-200"
        aria-label={social.label}
      >
        <SocialIcon className="w-5 h-5" />
      </a>
    );
  };

  return (
    <footer
      ref={footerRef}
      className={clsx(
        'bg-[var(--bg-secondary)] border-t border-[var(--border-primary)]',
        'mt-auto', // Push to bottom when using flex layout
        compact ? 'py-6' : 'py-12',
        className
      )}
      role="contentinfo"
    >
      <div className="max-w-7xl mx-auto px-4 lg:px-6">
        {/* Custom children - only show if provided */}
        {children && (
          <div className="mb-6">
            {children}
          </div>
        )}

        {/* Full footer content for public pages */}
        {!compact && (
          <>
            {/* Company info and links */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8 mb-8">
              {/* Company info */}
              <div className="space-y-4">
                <div className="flex items-center gap-3">
                  {company.logo}
                  <h3 className="text-lg font-semibold text-[var(--text-primary)]">{company.name}</h3>
                </div>
                {company.description && (
                  <p className="text-sm text-[var(--text-secondary)]">{company.description}</p>
                )}
                {/* Contact info */}
                <div className="space-y-2">
                  {company.email && (
                    <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)]">
                      <Mail className="w-4 h-4" />
                      <a href={`mailto:${company.email}`} className="hover:text-[var(--text-primary)]">
                        {company.email}
                      </a>
                    </div>
                  )}
                  {company.phone && (
                    <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)]">
                      <Phone className="w-4 h-4" />
                      <a href={`tel:${company.phone}`} className="hover:text-[var(--text-primary)]">
                        {company.phone}
                      </a>
                    </div>
                  )}
                  {company.website && (
                    <div className="flex items-center gap-2 text-sm text-[var(--text-secondary)]">
                      <Globe className="w-4 h-4" />
                      <a href={company.website} target="_blank" rel="noopener noreferrer" className="hover:text-[var(--text-primary)]">
                        {company.website}
                      </a>
                    </div>
                  )}
                </div>
              </div>

              {/* Footer sections */}
              {footerSections.map((section) => (
                <div key={section.id} className="space-y-4">
                  <h4 className="text-base font-medium text-[var(--text-primary)]">{section.title}</h4>
                  <nav className="space-y-2">
                    {section.links.map((link) => renderLink(link))}
                  </nav>
                </div>
              ))}
            </div>

            {/* Social links */}
            {socialLinksToShow.length > 0 && (
              <div className="border-t border-[var(--border-primary)] pt-6 mb-6">
                <div className="flex flex-col sm:flex-row items-center justify-between gap-4">
                  <p className="text-sm text-[var(--text-secondary)]">{t('common:footer.social_follow', 'Síguenos en redes sociales')}</p>
                  <div className="flex items-center gap-2">
                    {socialLinksToShow.map((social) => renderSocialLink(social))}
                  </div>
                </div>
              </div>
            )}
          </>
        )}

        {/* Minimal bottom bar */}
        <div className="flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-[var(--text-tertiary)]">
          {/* Copyright and version */}
          <div className="flex items-center gap-4">
            <span>© {currentYear} {company.name}</span>
            {showVersion && (
              <span>v{version}</span>
            )}
          </div>

          {/* Made with love in Madrid */}
          {!compact && (
            <div className="flex items-center gap-2 text-[var(--text-tertiary)]">
              <Heart className="w-4 h-4 text-red-500 fill-red-500" />
              <span>{t('common:footer.made_with_love', 'Hecho con amor en Madrid')}</span>
            </div>
          )}

          {/* Essential utilities only */}
          <div className="flex items-center gap-4">
            {/* Privacy links - minimal set */}
            {showPrivacyLinks && (
              <div className="flex items-center gap-3">
                <Link
                  to="/privacy"
                  className="text-[var(--text-tertiary)] hover:text-[var(--text-primary)] transition-colors duration-200"
                >
                  {t('common:footer.links.privacy', 'Privacidad')}
                </Link>
                <Link
                  to="/terms"
                  className="text-[var(--text-tertiary)] hover:text-[var(--text-primary)] transition-colors duration-200"
                >
                  {t('common:footer.links.terms', 'Términos')}
                </Link>
              </div>
            )}
          </div>
        </div>

        {/* Copyright text override */}
        {copyrightText && (
          <div className="text-center text-sm text-[var(--text-tertiary)] mt-4 pt-4 border-t border-[var(--border-primary)]">
            {copyrightText}
          </div>
        )}
      </div>
    </footer>
  );
});

Footer.displayName = 'Footer';