import React, { useState, useCallback } from 'react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus, prism } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { useTheme } from '../../../contexts/ThemeContext';
import useRenderTracker from '../../../hooks/useRenderTracker';

interface CodeBlockProps {
    content: string;
    language?: string;
}

// Custom styles for dark mode
const customDarkStyle = {
  ...vscDarkPlus,
  'code[class*="language-"]': {
    ...vscDarkPlus['code[class*="language-"]'],
    background: 'transparent',
    backgroundColor: 'transparent',
  },
  'pre[class*="language-"]': {
    ...vscDarkPlus['pre[class*="language-"]'],
    background: 'transparent',
    backgroundColor: 'transparent',
  },
};

// Custom styles for light mode
const customLightStyle = {
  ...prism,
  'code[class*="language-"]': {
    ...prism['code[class*="language-"]'],
    background: 'transparent',
    backgroundColor: 'transparent',
  },
  'pre[class*="language-"]': {
    ...prism['pre[class*="language-"]'],
    background: 'transparent',
    backgroundColor: 'transparent',
  },
};

// Modern API fails on insecure origins; this helper ensures we only attempt it when allowed.
const copyWithNavigatorClipboard = async (text: string): Promise<boolean> => {
  if (
    typeof navigator === 'undefined' ||
    !navigator.clipboard?.writeText ||
    (typeof window !== 'undefined' && window.isSecureContext === false)
  ) {
    return false;
  }

  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
};

// Legacy fallback using a hidden textarea + execCommand so HTTP dashboards still work.
const copyWithFallback = (text: string): boolean => {
  if (
    typeof document === 'undefined' ||
    !document.body ||
    typeof document.execCommand !== 'function'
  ) {
    return false;
  }

  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.setAttribute('readonly', '');
  textarea.style.position = 'fixed';
  textarea.style.top = '-9999px';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);

  const selection = document.getSelection();
  const originalRange = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;

  textarea.focus();
  textarea.select();
  textarea.setSelectionRange(0, textarea.value.length);

  let copied = false;
  try {
    copied = document.execCommand('copy');
  } catch {
    copied = false;
  }

  document.body.removeChild(textarea);

  if (originalRange && selection) {
    selection.removeAllRanges();
    selection.addRange(originalRange);
  }

  return copied;
};

const CodeBlock: React.FC<CodeBlockProps> = ({ content, language}) => {
  const { effectiveTheme } = useTheme();
  const [isCopied, setIsCopied] = useState(false);

  useRenderTracker('CodeBlock', {
    content,
    language,
    // isComplete,
    // isCopied,
    effectiveTheme,
  });

  // Initialize variables
  language = language || 'text';

    const handleCopyClick = useCallback(async () => {
      const copied =
        (await copyWithNavigatorClipboard(content)) || copyWithFallback(content);

      if (copied) {
        setIsCopied(true);
        setTimeout(() => setIsCopied(false), 3000);
      } else {
        console.error('Failed to copy text: unsupported environment');
      }
    }, [content]);

    return (
      <div className="code-block-container bg-gray-100 dark:bg-black/30 rounded-md border border-gray-200 dark:border-secondary/20 overflow-hidden">
        <div className="flex items-center justify-between px-4 py-2 text-xs dark:text-gray-400 bg-primary/10 dark:bg-primary/10">
          <span>{language}</span>
          <button
            onClick={handleCopyClick}
            className="flex items-center gap-1 py-1 px-2 rounded hover:bg-primary/10 dark:hover:bg-secondary/15 transition-colors min-w-[100px] justify-center duration-0"
          >
            {isCopied ? (
              <>
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M20 6L9 17L4 12"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  />
                </svg>
                Copied!
              </>
            ) : (
              <>
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    fillRule="evenodd"
                    clipRule="evenodd"
                    d="M7 5C7 3.34315 8.34315 2 10 2H19C20.6569 2 22 3.34315 22 5V14C22 15.6569 20.6569 17 19 17H17V19C17 20.6569 15.6569 22 14 22H5C3.34315 22 2 20.6569 2 19V10C2 8.34315 3.34315 7 5 7H7V5ZM9 7H14C15.6569 7 17 8.34315 17 10V15H19C19.5523 15 20 14.5523 20 14V5C20 4.44772 19.5523 4 19 4H10C9.44772 4 9 4.44772 9 5V7ZM5 9C4.44772 9 4 9.44772 4 10V19C4 19.5523 4.44772 20 5 20H14C14.5523 20 15 19.5523 15 19V10C15 9.44772 14.5523 9 14 9H5Z"
                    fill="currentColor"
                  />
                </svg>
                Copy code
              </>
            )}
          </button>
        </div>
        <SyntaxHighlighter
          language={language}
          style={effectiveTheme === 'dark' ? customDarkStyle : customLightStyle}
          customStyle={{
            margin: 0,
            padding: '1rem',
            backgroundColor: 'transparent',
            fontSize: '0.825rem',
            lineHeight: '1.5',
          }}
        >
          {content}
        </SyntaxHighlighter>
      </div>
    );
  }

export default React.memo(CodeBlock);
