"use client";

import { useState, useEffect } from 'react';
import { Check, Copy } from 'lucide-react';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';

interface SqlViewerProps {
  sql: string;
}

// Custom theme for light mode - Warm tones to match the design system
const lightTheme: { [key: string]: React.CSSProperties } = {
  'pre[class*="language-"]': {
    background: '#FAF7F2',
    color: '#373028',
    border: 'none',
    margin: 0,
    padding: '1.25rem',
    fontSize: '0.8125rem',
    lineHeight: '1.6',
    fontFamily: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
    overflow: 'auto',
  },
  'code[class*="language-"]': {
    fontFamily: 'inherit',
    background: 'transparent',
  },
  'comment': { color: '#7A6E5E', fontStyle: 'italic' },
  'punctuation': { color: '#A89A88' },
  'string': { color: '#059669' },
  'number': { color: '#D25A38' },
  'keyword': { color: '#A94429', fontWeight: '600' },
  'function': { color: '#7c3aed' },
  'operator': { color: '#7A6E5E' },
  'class-name': { color: '#A94429' },
  'constant': { color: '#D25A38' },
};

// Custom theme for dark mode - Warm dark tones
const darkTheme: { [key: string]: React.CSSProperties } = {
  'pre[class*="language-"]': {
    background: '#1C1916',
    color: '#F5F0E8',
    border: 'none',
    margin: 0,
    padding: '1.25rem',
    fontSize: '0.8125rem',
    lineHeight: '1.6',
    fontFamily: '"JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',
    overflow: 'auto',
  },
  'code[class*="language-"]': {
    fontFamily: 'inherit',
    background: 'transparent',
  },
  'comment': { color: '#7A6E5E', fontStyle: 'italic' },
  'punctuation': { color: '#5A5048' },
  'string': { color: '#34d399' },
  'number': { color: '#F5A492' },
  'keyword': { color: '#F5A492', fontWeight: '600' },
  'function': { color: '#a78bfa' },
  'operator': { color: '#A89A88' },
  'class-name': { color: '#F5A492' },
  'constant': { color: '#F5A492' },
};

export function SqlViewer({ sql }: SqlViewerProps) {
  const [copied, setCopied] = useState(false);
  const [isDark, setIsDark] = useState(false);

  // Check for dark mode on mount and listen for changes
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const checkDark = () => {
        setIsDark(document.documentElement.classList.contains('dark'));
      };
      checkDark();
      
      const observer = new MutationObserver(checkDark);
      observer.observe(document.documentElement, { 
        attributes: true, 
        attributeFilter: ['class'] 
      });
      
      return () => observer.disconnect();
    }
  }, []);

  const handleCopy = async () => {
    await navigator.clipboard.writeText(sql);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  const currentTheme = isDark ? darkTheme : lightTheme;
  const lineNumberColor = isDark ? '#4A4238' : '#C9BBAA';
  const lineNumberBorder = isDark ? '#373028' : '#EBE4D8';

  return (
    <div className="relative group rounded-xl border border-cream-300 dark:border-warm-700 shadow-warm-sm bg-cream-50 dark:bg-warm-900 overflow-hidden">
      {/* Copy Button */}
      <div className="absolute top-3 right-3 z-10 opacity-0 group-hover:opacity-100 transition-all duration-200">
        <button
          onClick={handleCopy}
          className="flex items-center gap-1.5 px-2.5 py-1.5 
                   bg-white/90 dark:bg-warm-800/90 backdrop-blur-sm border border-cream-300 dark:border-warm-600 
                   shadow-sm rounded-lg text-[11px] font-bold 
                   text-warm-600 dark:text-warm-300 
                   hover:text-accent dark:hover:text-accent-300 
                   hover:border-accent/30 dark:hover:border-accent/50 
                   active:scale-95 transition-all"
        >
          {copied ? (
            <>
              <Check className="w-3.5 h-3.5 text-green-600 dark:text-green-400" />
              <span>COPIED</span>
            </>
          ) : (
            <>
              <Copy className="w-3.5 h-3.5 text-warm-400" />
              <span>COPY SQL</span>
            </>
          )}
        </button>
      </div>

      {/* Code Block */}
      <div className="overflow-auto max-h-[600px] scrollbar-thin"> 
        <SyntaxHighlighter 
          language="sql" 
          style={currentTheme}
          showLineNumbers={true}
          wrapLines={true}
          lineNumberStyle={{ 
            minWidth: '2.8em', 
            paddingRight: '1.25rem', 
            color: lineNumberColor, 
            textAlign: 'right', 
            borderRight: `1px solid ${lineNumberBorder}`, 
            marginRight: '1.25rem',
            userSelect: 'none',
            fontSize: '0.75rem'
          }}
          customStyle={{ 
            margin: 0, 
            background: 'transparent' 
          }}
        >
          {sql}
        </SyntaxHighlighter>
      </div>
    </div>
  );
}
