import React, { useState, useEffect } from 'react';
import { Scale, 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 Loading from '../../../shared/components/Loading';
import { createSanitizedHtml, sanitizeHtml } from '../../../shared/utils/htmlSanitizer';

const TermsPage: React.FC = () => {
  const { settings } = useCompanySettings();
  const [pageContent, setPageContent] = useState<PageContent | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchPageContent = async () => {
      try {
        setLoading(true);
        const response = await pageContentService.getTermsContent();
        if (response.status === 'success' && response.data?.page_content) {
          const content = response.data.page_content;
          
          // Process HTML content to ensure text is visible
          if (content.content) {
            // SECURITY: Sanitize HTML before assigning to innerHTML to prevent XSS
            const sanitizedContent = sanitizeHtml(content.content);
            // Create a temporary div to parse HTML
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = sanitizedContent;
            
            // Add color styles to elements that don't have them
            const allElements = tempDiv.querySelectorAll('*');
            allElements.forEach((el) => {
              const htmlEl = el as HTMLElement;
              const tagName = htmlEl.tagName.toLowerCase();
              const currentColor = htmlEl.style.color;
              
              // Only add color if not already set
              if (!currentColor || currentColor === 'black' || currentColor === '#000' || currentColor === '#000000') {
                if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tagName)) {
                  htmlEl.style.color = '#ffffff';
                } else if (['strong', 'b'].includes(tagName)) {
                  htmlEl.style.color = '#d4af37';
                } else if (tagName === 'a') {
                  htmlEl.style.color = '#d4af37';
                } else {
                  htmlEl.style.color = '#d1d5db';
                }
              }
            });
            
            // Update content with processed HTML
            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: any) {
        console.error('Error fetching page content:', err);
        // If page is disabled (404), set pageContent to null to show disabled message
        if (err.response?.status === 404) {
          setPageContent(null);
        }
      } finally {
        setLoading(false);
      }
    };

    fetchPageContent();
  }, []);

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

  if (!pageContent) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] 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">
          <Scale className="w-16 h-16 text-[#d4af37]/50 mx-auto mb-4" />
          <h1 className="text-2xl font-elegant font-bold text-white mb-2">Terms & Conditions</h1>
          <p className="text-gray-400">This page is currently unavailable.</p>
          <Link
            to="/"
            className="inline-flex items-center gap-2 text-[#d4af37]/80 hover:text-[#d4af37] 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 bg-gradient-to-b from-[#0f0f0f] via-[#1a1a1a] to-[#0f0f0f] 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">
        {/* Back Link */}
        <Link
          to="/"
          className="inline-flex items-center gap-2 text-[#d4af37]/80 hover:text-[#d4af37] 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>

        {/* Header */}
        <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-[#d4af37]/20 to-[#c9a227]/10 rounded-full border border-[#d4af37]/30">
            <Scale className="w-8 h-8 sm:w-10 sm:h-10 text-[#d4af37]" />
          </div>
          <h1 className="text-3xl sm:text-4xl lg:text-5xl font-elegant font-bold text-white mb-3 sm:mb-4 tracking-tight leading-tight bg-gradient-to-r from-white via-[#d4af37] to-white bg-clip-text text-transparent">
            {pageContent.title || 'Terms & Conditions'}
          </h1>
          {pageContent.subtitle && (
            <p className="text-base sm:text-lg text-gray-300 font-light tracking-wide">
              {pageContent.subtitle}
            </p>
          )}
        </div>

        {/* Content */}
        <div className="bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-xl border border-[#d4af37]/20 backdrop-blur-xl shadow-2xl shadow-[#d4af37]/5 p-6 sm:p-8 lg:p-12">
          <div 
            className="prose prose-invert prose-lg max-w-none text-gray-300
              prose-headings:text-white prose-headings:font-elegant prose-headings:font-semibold
              prose-h2:text-2xl prose-h2:mt-8 prose-h2:mb-4 prose-h2:border-b prose-h2:border-[#d4af37]/20 prose-h2:pb-2
              prose-p:text-gray-300 prose-p:font-light prose-p:leading-relaxed prose-p:mb-4
              prose-ul:text-gray-300 prose-ul:font-light prose-ul:my-4
              prose-li:text-gray-300 prose-li:mb-2 prose-li:ml-4
              prose-strong:text-[#d4af37] prose-strong:font-medium
              prose-a:text-[#d4af37] prose-a:no-underline hover:prose-a:underline
              [&_*]:text-gray-300 [&_h1]:text-white [&_h2]:text-white [&_h3]:text-white [&_h4]:text-white [&_h5]:text-white [&_h6]:text-white
              [&_strong]:text-[#d4af37] [&_b]:text-[#d4af37] [&_a]:text-[#d4af37]"
            style={{ color: '#d1d5db' }}
            dangerouslySetInnerHTML={createSanitizedHtml(
              pageContent.content || pageContent.description || '<p style="color: #d1d5db;">No content available.</p>'
            )}
          />
        </div>

        {/* Footer Note */}
        {settings.company_email && (
          <div className="mt-8 text-center">
            <p className="text-sm text-gray-400 font-light">
              For questions about these terms, contact us at{' '}
              <a href={`mailto:${settings.company_email}`} className="text-[#d4af37] hover:underline">
                {settings.company_email}
              </a>
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default TermsPage;

