import React, { useState, useRef, useEffect } from 'react';
import { Check, ChevronRight } from 'lucide-react';
import { renderDisclaimerContent } from '../utils/renderDisclaimerContent';

export interface DisclaimerSection {
  title: string;
  content: React.ReactNode;
  required?: boolean;
}

export interface DisclaimerContent {
  title: string;
  required?: boolean;
  content: {
    title: string;
    sections: {
      heading: string;
      text: string;
      list?: string[];
    }[];
  };
}

export interface ThemeConfig {
  modal: string;
  header: string;
  tabBorder: string;
  activeTab: string;
  inactiveTab: string;
  completedTab: string;
  content: string;
  footer: string;
  checkbox: {
    base: string;
    checked: string;
    disabled: string;
  };
  text: {
    enabled: string;
    disabled: string;
  };
}

export interface DisclaimerModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  disclaimerContent?: Record<string, DisclaimerContent>;
  disclaimerSections?: DisclaimerSection[];
  theme?: 'dark' | 'light';
  customTheme?: ThemeConfig;
  setAllAgreed?: (allAgreed: boolean) => void;
  onAllSectionsAgreed?: (allAgreed: boolean) => void;
  accentColor?: string;
}

const getThemeClasses = (theme: 'dark' | 'light'): ThemeConfig => {
  const themes: Record<'dark' | 'light', ThemeConfig> = {
    dark: {
      modal: 'bg-gray-900 text-white',
      header: 'border-gray-800 bg-gray-900/95 backdrop-blur-sm',
      tabBorder: 'border-gray-800',
      activeTab: 'text-blue-400 border-blue-400',
      inactiveTab: 'text-gray-400 border-transparent hover:text-blue-400/80',
      completedTab: 'text-emerald-400',
      content: 'prose-invert',
      footer: 'border-gray-800 bg-gray-900/95 backdrop-blur-sm',
      checkbox: {
        base: 'border-gray-600 group-hover:border-blue-400',
        checked: 'bg-blue-500 border-blue-500',
        disabled: 'opacity-50 cursor-not-allowed'
      },
      text: {
        enabled: 'text-gray-200',
        disabled: 'text-gray-500'
      }
    },
    light: {
      modal: 'bg-white text-gray-900',
      header: 'border-gray-200 bg-white/95 backdrop-blur-sm',
      tabBorder: 'border-gray-200',
      activeTab: 'text-blue-600 border-blue-600',
      inactiveTab: 'text-gray-500 border-transparent hover:text-blue-600/80',
      completedTab: 'text-emerald-600',
      content: 'prose-base',
      footer: 'border-gray-200 bg-white/95 backdrop-blur-sm',
      checkbox: {
        base: 'border-gray-300 group-hover:border-blue-500',
        checked: 'bg-blue-600 border-blue-600',
        disabled: 'opacity-50 cursor-not-allowed'
      },
      text: {
        enabled: 'text-gray-900',
        disabled: 'text-gray-500'
      }
    }
  };

  return themes[theme];
};

const TabContent: React.FC<{
  content: React.ReactNode;
  onScroll: (isComplete: boolean) => void;
  onAgree: () => void;
  isActive: boolean;
  isScrolled: boolean;
  isAgreed: boolean;
  sectionTitle: string;
  theme: 'dark' | 'light';
}> = ({
  content,
  onScroll,
  onAgree,
  isActive,
  isScrolled,
  isAgreed,
  sectionTitle,
  theme
}) => {
  const contentRef = useRef<HTMLDivElement>(null);
  const themeClasses = getThemeClasses(theme);

  useEffect(() => {
    const checkScroll = () => {
      if (!contentRef.current) return;

      const { scrollHeight, scrollTop, clientHeight } = contentRef.current;
      const isAtBottom = scrollHeight - scrollTop - clientHeight < 20;

      if (isAtBottom && !isScrolled) {
        onScroll(true);
      }
    };

    const contentElement = contentRef.current;
    if (contentElement) {
      contentElement.addEventListener('scroll', checkScroll);
      // Check initial scroll position
      checkScroll();

      return () => contentElement.removeEventListener('scroll', checkScroll);
    }
  }, [onScroll, isScrolled]);

  if (!isActive) return null;

  return (
    <div className="flex flex-col p-4">
      <div
        ref={contentRef}
        className={`
          overflow-y-auto prose max-w-none mb-4 p-4 rounded-lg
          ${themeClasses.content}
          ${theme === 'light'
            ? 'border border-gray-200 bg-white shadow-sm'
            : 'border border-gray-700 bg-gray-800 shadow-sm'
          }
          max-h-[calc(60vh-4rem)]
        `}
      >
        {content}
      </div>

      <label className="flex items-center group cursor-pointer select-none">
        <div className="relative">
          <input
            type="checkbox"
            className="sr-only"
            checked={isAgreed}
            onChange={onAgree}
            disabled={!isScrolled}
          />
          <div
            className={`
              w-5 h-5 border-2 rounded transition-all duration-200
              ${isScrolled ? themeClasses.checkbox.base : themeClasses.checkbox.disabled}
              ${isAgreed ? themeClasses.checkbox.checked : ''}
            `}
          />
          {isAgreed && (
            <Check className="absolute top-0.5 left-0.5 w-4 h-4 text-white" />
          )}
        </div>
        <span className={`ml-3 ${isScrolled ? themeClasses.text.enabled : themeClasses.text.disabled}`}>
          I have read and agree to the {sectionTitle}
        </span>
      </label>
    </div>
  );
};

const renderIcon = (icon: React.ReactNode) => {
  try {
    return icon;
  } catch (error) {
    return <div />;
  }
};

const STORAGE_KEY = 'im-disclaimer-accepted';

const DisclaimerModal: React.FC<DisclaimerModalProps> = ({
  isOpen: propIsOpen,
  onClose,
  title,
  disclaimerContent,
  disclaimerSections: propSections,
  theme = 'dark',
  customTheme,
  setAllAgreed,
  onAllSectionsAgreed,
  accentColor
}) => {
  // Transform JSON content if provided
  const sections = disclaimerContent 
    ? Object.entries(disclaimerContent).map(([key, section]) => ({
        title: section.title,
        required: section.required,
        content: renderDisclaimerContent(section.content, theme)
      }))
    : propSections || [];

  const [activeTab, setActiveTab] = useState(0);
  const [scrolledSections, setScrolledSections] = useState<boolean[]>(
    new Array(sections.length).fill(false)
  );
  const [agreedSections, setAgreedSections] = useState<boolean[]>(
    new Array(sections.length).fill(false)
  );
  const [isOpen, setIsOpen] = useState(propIsOpen);

  const themeConfig = customTheme || getThemeClasses(theme);

  // Check localStorage on mount
  useEffect(() => {
    const acceptedDisclaimers = localStorage.getItem(STORAGE_KEY);
    if (acceptedDisclaimers) {
      const accepted = new Set(JSON.parse(acceptedDisclaimers));
      if (accepted.has(title)) {
        setIsOpen(false);
      }
    }
  }, [title]);

  // Handle disclaimer acceptance
  const handleClose = () => {
    const acceptedDisclaimers = localStorage.getItem(STORAGE_KEY);
    const accepted = acceptedDisclaimers ? new Set(JSON.parse(acceptedDisclaimers)) : new Set();
    accepted.add(title);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(Array.from(accepted)));
    setIsOpen(false);
    onClose?.();
  };

  // Update parent component when all sections are agreed
  useEffect(() => {
    const allRequired = sections
      .filter((section) => section.required)
      .every((_, index) => agreedSections[index]);
    setAllAgreed?.(allRequired);
    onAllSectionsAgreed?.(allRequired);
  }, [sections, agreedSections, onAllSectionsAgreed]);

  if (!isOpen) return null;

  const allAgreed = sections
    .filter((section) => section.required)
    .every((_, index) => agreedSections[index]);

  return (
    <>
      {/* Backdrop with blur effect */}
      <div className="fixed inset-0 z-40">
        <div className="absolute inset-0 bg-black/40 backdrop-blur-md transition-all duration-300" />
      </div>
      
      {/* Modal */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
        <div
          className={`
            w-full max-w-4xl rounded-xl shadow-2xl overflow-hidden
            flex flex-col
            ${themeConfig.modal}
            transform transition-all duration-200 ease-out
            border border-gray-200/10
          `}
        >
          {/* Header */}
          <div className={`sticky top-0 z-10 px-6 py-4 border-b flex items-center ${themeConfig.header}`}>
            <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-4">{title}</h2>
          </div>

          {/* Tabs */}
          <div className={`sticky top-[4.5rem] z-10 flex border-b ${themeConfig.tabBorder} bg-inherit`}>
            {sections.map((section, index) => {
              const status = agreedSections[index] ? 'completed' : scrolledSections[index] ? 'scrolled' : 'pending';
              return (
                <button
                  key={section.title}
                  onClick={() => setActiveTab(index)}
                  className={`
                    flex items-center gap-2 px-6 py-3 text-sm font-medium border-b-2 -mb-[2px]
                    transition-all duration-200
                    ${activeTab === index
                      ? themeConfig.activeTab
                      : status === 'completed'
                      ? themeConfig.completedTab
                      : themeConfig.inactiveTab
                    }
                  `}
                >
                  {status === 'completed' ? (
                    <Check className="w-4 h-4" />
                  ) : (
                    <div className={`w-2 h-2 rounded-full ${status === 'scrolled' ? 'bg-current' : 'bg-current opacity-40'}`} />
                  )}
                  {section.title}
                  {section.required && <span className="text-red-500">*</span>}
                </button>
              );
            })}
          </div>

          {/* Content */}
          <div className={`flex-1 overflow-y-auto ${themeConfig.content}`}>
            {sections.map((section, index) => (
              <TabContent
                key={section.title}
                content={section.content}
                onScroll={() => {
                  const newScrolled = [...scrolledSections];
                  newScrolled[index] = true;
                  setScrolledSections(newScrolled);
                }}
                onAgree={() => {
                  const newAgreed = [...agreedSections];
                  newAgreed[index] = true;
                  setAgreedSections(newAgreed);
                }}
                isActive={activeTab === index}
                isScrolled={scrolledSections[index]}
                isAgreed={agreedSections[index]}
                sectionTitle={section.title}
                theme={theme}
              />
            ))}
          </div>

          {/* Footer */}
          <div className={`sticky bottom-0 flex justify-end gap-4 px-6 py-4 border-t ${themeConfig.footer}`}>
            <button
              onClick={handleClose}
              disabled={!allAgreed}
              style={{ backgroundColor: accentColor }}
              className={`
                px-6 py-2 rounded-lg font-medium
                disabled:opacity-50 disabled:cursor-not-allowed
                transition-all duration-200
              `}
            >
              Accept All
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default DisclaimerModal;
