import React, { useState, MouseEvent } from 'react';
import CodeBlock from '@theme/CodeBlock';

// Simple markdown parser for basic markdown support in descriptions
const parseMarkdown = (text: string): string => {
  return text
    // Convert [text](url) to <a href="url">text</a>
    .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
    // Convert **text** to <strong>text</strong>
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    // Convert *text* to <em>text</em>
    .replace(/\*([^*]+)\*/g, '<em>$1</em>')
    // Convert `code` to <code>code</code>
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    // Convert line breaks to <br>
    .replace(/\n/g, '<br>');
};

// Type definitions
export interface Tab {
  id: string;
  title: string;
  icon: string;
  language?: string;
  content: string;
  description?: string;
  custom?: React.ReactNode;
}

export interface InteractiveCodePanelProps {
  title: string;
  description: string;
  tabs: Tab[];
  defaultTab?: string;
  defaultExpanded?: boolean;
  showCopyButton?: boolean;
}

// Reusable Interactive Code Demo Component
const InteractiveCodePanel: React.FC<InteractiveCodePanelProps> = ({
  title,
  description,
  tabs,
  defaultTab,
  defaultExpanded = false,
  showCopyButton = true
}) => {
  const [activeTab, setActiveTab] = useState<string>(defaultTab || tabs[0]?.id || '');
  const [isExpanded, setIsExpanded] = useState<boolean>(defaultExpanded);
  const [copyStatus, setCopyStatus] = useState<string>('');

  const getCurrentTab = (): Tab => tabs.find(tab => tab.id === activeTab) || tabs[0];
  const currentTab = getCurrentTab();

  const copyToClipboard = async (text: string): Promise<void> => {
    try {
      await navigator.clipboard.writeText(text);
      setCopyStatus('✅ Copied!');
      setTimeout(() => setCopyStatus(''), 2000);
    } catch (err) {
      setCopyStatus('❌ Failed to copy');
      setTimeout(() => setCopyStatus(''), 2000);
    }
  };

  const handleMouseEnter = (e: MouseEvent<HTMLButtonElement>, tabId: string): void => {
    if (activeTab !== tabId) {
      (e.target as HTMLButtonElement).style.background = 'var(--ifm-color-emphasis-100)';
    }
  };

  const handleMouseLeave = (e: MouseEvent<HTMLButtonElement>, tabId: string): void => {
    if (activeTab !== tabId) {
      (e.target as HTMLButtonElement).style.background = 'transparent';
    }
  };

  const handleCopyButtonMouseEnter = (e: MouseEvent<HTMLButtonElement>): void => {
    (e.target as HTMLButtonElement).style.background = 'var(--ifm-color-primary-dark)';
  };

  const handleCopyButtonMouseLeave = (e: MouseEvent<HTMLButtonElement>): void => {
    (e.target as HTMLButtonElement).style.background = 'var(--ifm-color-primary)';
  };

  return (
    <div
      style={{
        background: 'var(--ifm-background-surface-color)',
        border: '1px solid var(--ifm-color-emphasis-300)',
        borderRadius: '12px',
        margin: '24px 0',
        overflow: 'hidden',
        boxShadow: 'var(--ifm-global-shadow-lw)',
      }}
    >
      {/* Header */}
      <div
        style={{
          padding: '20px 24px',
          background: 'var(--ifm-color-primary-contrast-background)',
          borderBottom: '1px solid var(--ifm-color-emphasis-300)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <div>
          <h3 style={{ margin: '0 0 4px 0', fontSize: '18px', fontWeight: '600', color: 'var(--ifm-heading-color)' }}>
            {title}
          </h3>
          <p style={{ margin: 0, fontSize: '14px', color: 'var(--ifm-color-content-secondary)' }}>
            {description}
          </p>
        </div>
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          style={{
            padding: '8px 16px',
            background: 'var(--ifm-color-primary)',
            color: 'white',
            border: 'none',
            borderRadius: '6px',
            fontSize: '14px',
            fontWeight: '500',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
          }}
        >
          {isExpanded ? 'Hide Guide' : 'Show Guide'}
        </button>
      </div>

      {/* Content */}
      {isExpanded && (
        <div style={{ padding: '0' }}>
          {/* Tab Navigation */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              borderBottom: '1px solid var(--ifm-color-emphasis-300)',
              background: 'var(--ifm-background-color)',
            }}
            className="tab-navigation"
          >
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                style={{
                  flex: 1,
                  padding: '16px 20px',
                  background: activeTab === tab.id ? 'var(--ifm-background-surface-color)' : 'transparent',
                  border: 'none',
                  borderBottom: activeTab === tab.id ? '2px solid var(--ifm-color-primary)' : '2px solid transparent',
                  color: activeTab === tab.id ? 'var(--ifm-color-primary)' : 'var(--ifm-color-content-secondary)',
                  fontSize: '14px',
                  fontWeight: activeTab === tab.id ? '600' : '500',
                  cursor: 'pointer',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '8px',
                  transition: 'all 0.2s ease',
                }}
                onMouseEnter={(e) => handleMouseEnter(e, tab.id)}
                onMouseLeave={(e) => handleMouseLeave(e, tab.id)}
              >
                <span>{tab.icon}</span>
                {tab.title}
              </button>
            ))}
          </div>

          {/* Code Content */}
          <div style={{ padding: '24px' }}>

            {/* Tab Description */}
            {currentTab.description && (
              <div
                style={{
                  marginBottom: '16px',
                  padding: '16px',
                  background: 'var(--ifm-color-info-contrast-background)',
                  borderRadius: '8px',
                  border: '1px solid var(--ifm-color-info-dark)',
                }}
              >
                <div>
                  <h4 style={{ margin: '0 0 8px 0', fontSize: '16px', color: 'var(--ifm-heading-color)' }}>
                    {currentTab.icon} {currentTab.title}
                  </h4>
                  <div
                    style={{
                      margin: 0,
                      fontSize: '14px',
                      color: 'var(--ifm-color-content)',
                      lineHeight: '1.5'
                    }}
                    dangerouslySetInnerHTML={{ __html: parseMarkdown(currentTab.description) }}
                  />
                </div>
              </div>
            )}

            <div style={{ position: 'relative' }}>
              {/* Copy Button - only show for code content */}
              {showCopyButton && currentTab.content && !currentTab.custom && (
                <button
                  onClick={() => copyToClipboard(currentTab.content)}
                  style={{
                    position: 'absolute',
                    top: '12px',
                    right: '12px',
                    zIndex: 10,
                    padding: '6px 12px',
                    background: 'var(--ifm-color-primary)',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4px',
                    fontSize: '12px',
                    fontWeight: '500',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '4px',
                    transition: 'all 0.2s ease',
                  }}
                  onMouseEnter={handleCopyButtonMouseEnter}
                  onMouseLeave={handleCopyButtonMouseLeave}
                >
                  📋 {copyStatus || 'Copy'}
                </button>
              )}

              {/* Custom Content or Code Block */}
              {currentTab.custom ? (
                <div>{currentTab.custom}</div>
              ) : (
                currentTab.content && <CodeBlock language={currentTab.language || 'text'}>
                  {currentTab.content}
                </CodeBlock>
              )}
            </div>


          </div>
        </div>
      )}
    </div>
  );
};

// Export both the reusable component and the specific demo
export { InteractiveCodePanel };
