import React, { useState, useEffect } from 'react';
import { Accessibility, ArrowLeft } from 'lucide-react';
import { Link } from 'react-router-dom';
import pageContentService from '../services/pageContentService';
import type { PageContent } from '../services/pageContentService';
import { useCompanySettings } from '../../../shared/contexts/CompanySettingsContext';
import { useTheme } from '../../../shared/contexts/ThemeContext';
import Loading from '../../../shared/components/Loading';
import { createSanitizedHtml, sanitizeHtml } from '../../../shared/utils/htmlSanitizer';
import { getThemeBackgroundClasses, getThemeTextClasses, getThemeCardClasses } from '../../../shared/utils/themeUtils';

const AccessibilityPage: React.FC = () => {
  const { settings } = useCompanySettings();
  const { theme } = useTheme();
  const [pageContent, setPageContent] = useState<PageContent | null>(null);
  const [loading, setLoading] = useState(true);
  
  const bgClasses = getThemeBackgroundClasses(theme.theme_layout_mode);
  const textClasses = getThemeTextClasses(theme.theme_layout_mode);
  const cardClasses = getThemeCardClasses(theme.theme_layout_mode);

  useEffect(() => {
    const fetchPageContent = async () => {
      try {
        setLoading(true);
        const response = await pageContentService.getAccessibilityContent();
        if (response.status === 'success' && response.data?.page_content) {
          const content = response.data.page_content;
          
          if (content.content) {
            // SECURITY: Sanitize HTML before assigning to innerHTML to prevent XSS
            const sanitizedContent = sanitizeHtml(content.content);
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = sanitizedContent;
            
            // Get theme-aware colors
            const isLightMode = theme.theme_layout_mode === 'light';
            const headingColor = isLightMode ? '#111827' : '#ffffff';
            const bodyColor = isLightMode ? '#111827' : '#d1d5db';
            const accentColor = '#d4af37'; // Gold color for links and strong
            
            const allElements = tempDiv.querySelectorAll('*');
            allElements.forEach((el) => {
              const htmlEl = el as HTMLElement;
              const tagName = htmlEl.tagName.toLowerCase();
              
              // Override inline colors to use theme-aware colors
              if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tagName)) {
                htmlEl.style.color = headingColor;
              } else if (['strong', 'b'].includes(tagName)) {
                htmlEl.style.color = accentColor;
              } else if (tagName === 'a') {
                htmlEl.style.color = accentColor;
              } else {
                htmlEl.style.color = bodyColor;
              }
            });
            
            content.content = tempDiv.innerHTML;
          }
          
          setPageContent(content);
          
          if (content.meta_title) {
            document.title = content.meta_title;
          }
          if (content.meta_description) {
            let metaDescription = document.querySelector('meta[name="description"]');
            if (!metaDescription) {
              metaDescription = document.createElement('meta');
              metaDescription.setAttribute('name', 'description');
              document.head.appendChild(metaDescription);
            }
            metaDescription.setAttribute('content', content.meta_description);
          }
        }
      } catch (err: unknown) {
        console.error('Error fetching page content:', err);
        // If page is disabled (404), set pageContent to null to show disabled message
        const isApiError = (e: unknown): e is { response?: { status?: number } } => {
          return typeof e === 'object' && e !== null;
        };
        if (isApiError(err) && err.response?.status === 404) {
          setPageContent(null);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchPageContent();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (loading) {
    return <Loading />;
  }

  if (!pageContent) {
    return (
      <div className={`min-h-screen ${bgClasses} w-screen relative -mt-6 -mb-6 flex items-center justify-center`}
        style={{ 
          marginLeft: 'calc(50% - 50vw)',
          marginRight: 'calc(50% - 50vw)',
          width: '100vw',
          paddingTop: '2rem',
          paddingBottom: '2rem',
          zIndex: 1
        }}
      >
        <div className="text-center">
          <Accessibility className="w-16 h-16 text-[var(--luxury-gold)]/50 mx-auto mb-4" />
          <h1 className={`text-2xl font-elegant font-bold ${textClasses.primary} mb-2`}>Accessibility</h1>
          <p className={textClasses.muted}>This page is currently unavailable.</p>
          <Link
            to="/"
            className="inline-flex items-center gap-2 text-[var(--luxury-gold)]/80 hover:text-[var(--luxury-gold)] mt-6 transition-all duration-300"
          >
            <ArrowLeft className="w-4 h-4" />
            <span>Back to Home</span>
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className={`min-h-screen ${bgClasses} w-screen relative -mt-6 -mb-6`}
      style={{ 
        marginLeft: 'calc(50% - 50vw)',
        marginRight: 'calc(50% - 50vw)',
        width: '100vw',
        paddingTop: '2rem',
        paddingBottom: '2rem',
        zIndex: 1
      }}
    >
      <div className="w-full px-3 sm:px-4 md:px-6 lg:px-8 py-8 sm:py-12 max-w-5xl mx-auto">
        <Link
          to="/"
          className="inline-flex items-center gap-2 text-[var(--luxury-gold)]/80 hover:text-[var(--luxury-gold)] mb-6 transition-all duration-300 group font-light tracking-wide text-xs sm:text-sm"
        >
          <ArrowLeft className="w-4 h-4 group-hover:-translate-x-1 transition-transform" />
          <span>Back to Home</span>
        </Link>

        <div className="mb-8 sm:mb-12 text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 mb-4 sm:mb-6 bg-gradient-to-br from-[var(--luxury-gold)]/20 to-[var(--luxury-gold-dark)]/10 rounded-full border border-[var(--luxury-gold)]/30">
            <Accessibility className="w-8 h-8 sm:w-10 sm:h-10 text-[var(--luxury-gold)]" />
          </div>
          <h1 className={`text-3xl sm:text-4xl lg:text-5xl font-elegant font-bold ${textClasses.primary} mb-3 sm:mb-4 tracking-tight leading-tight ${theme.theme_layout_mode === 'light' 
            ? 'bg-gradient-to-r from-gray-900 via-[var(--luxury-gold)] to-gray-900' 
            : 'bg-gradient-to-r from-white via-[var(--luxury-gold)] to-white'} bg-clip-text text-transparent`}>
            {pageContent.title || 'Accessibility'}
          </h1>
          {pageContent.subtitle && (
            <p className={`text-base sm:text-lg ${textClasses.secondary} font-light tracking-wide`}>
              {pageContent.subtitle}
            </p>
          )}
        </div>

        <div className={`${cardClasses} rounded-xl border border-[var(--luxury-gold)]/20 backdrop-blur-xl shadow-2xl shadow-[var(--luxury-gold)]/5 p-6 sm:p-8 lg:p-12`}>
          <div 
            className={`prose ${theme.theme_layout_mode === 'light' ? 'prose-slate' : 'prose-invert'} prose-lg max-w-none
              prose-headings:font-elegant prose-headings:font-semibold
              ${theme.theme_layout_mode === 'light' ? 'prose-headings:text-gray-900' : 'prose-headings:text-white'}
              prose-h2:text-2xl prose-h2:mt-8 prose-h2:mb-4 prose-h2:border-b prose-h2:border-[var(--luxury-gold)]/20 prose-h2:pb-2
              ${theme.theme_layout_mode === 'light' ? 'prose-p:text-gray-900 prose-ul:text-gray-900 prose-ol:text-gray-900 prose-li:text-gray-900' : 'prose-p:text-gray-300 prose-ul:text-gray-300 prose-ol:text-gray-300 prose-li:text-gray-300'}
              prose-p:font-light prose-p:leading-relaxed prose-p:mb-4
              prose-ul:font-light prose-ul:my-4
              prose-li:mb-2 prose-li:ml-4
              prose-strong:text-[var(--luxury-gold)] prose-strong:font-medium
              prose-a:text-[var(--luxury-gold)] prose-a:no-underline hover:prose-a:underline`}
            style={{ color: theme.theme_layout_mode === 'light' ? '#111827' : '#d1d5db' }}
            dangerouslySetInnerHTML={createSanitizedHtml(
              pageContent.content || pageContent.description || `<p style="color: ${theme.theme_layout_mode === 'light' ? '#111827' : '#d1d5db'};">No content available.</p>`
            )}
          />
        </div>

        {settings.company_email && (
          <div className="mt-8 text-center">
            <p className={`text-sm ${textClasses.muted} font-light`}>
              For accessibility inquiries, contact us at{' '}
              <a href={`mailto:${settings.company_email}`} className="text-[var(--luxury-gold)] hover:underline">
                {settings.company_email}
              </a>
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default AccessibilityPage;

