import React, { useState } from 'react';
import { ExternalLink, Quote, X, CheckCircle, AlertTriangle, HelpCircle, FileText } from 'lucide-react';
import { SourceAnchor as SourceAnchorType, ConfidenceLevel } from '../types';

interface Props {
  anchor: SourceAnchorType;
  children: React.ReactNode;
}

const confidenceConfig: Record<ConfidenceLevel, {
  label: string;
  color: string;
  bgColor: string;
  borderColor: string;
  icon: React.ReactNode;
  description: string;
}> = {
  'direct-quote': {
    label: 'Direct Quote',
    color: 'text-green-700 dark:text-green-300',
    bgColor: 'bg-green-50 dark:bg-green-900/30',
    borderColor: 'border-green-200 dark:border-green-800',
    icon: <Quote size={12} />,
    description: 'This is a direct quote from the paper'
  },
  'paraphrase': {
    label: 'Paraphrased',
    color: 'text-blue-700 dark:text-blue-300',
    bgColor: 'bg-blue-50 dark:bg-blue-900/30',
    borderColor: 'border-blue-200 dark:border-blue-800',
    icon: <FileText size={12} />,
    description: 'Closely paraphrased from source text'
  },
  'synthesis': {
    label: 'Synthesized',
    color: 'text-purple-700 dark:text-purple-300',
    bgColor: 'bg-purple-50 dark:bg-purple-900/30',
    borderColor: 'border-purple-200 dark:border-purple-800',
    icon: <CheckCircle size={12} />,
    description: 'Combined from multiple parts of the paper'
  },
  'interpretation': {
    label: 'AI Analysis',
    color: 'text-amber-700 dark:text-amber-300',
    bgColor: 'bg-amber-50 dark:bg-amber-900/30',
    borderColor: 'border-amber-200 dark:border-amber-800',
    icon: <AlertTriangle size={12} />,
    description: 'AI interpretation - verify with source'
  }
};

const SourceAnchorComponent: React.FC<Props> = ({ anchor, children }) => {
  const [isOpen, setIsOpen] = useState(false);
  const config = confidenceConfig[anchor.confidence];

  return (
    <span className="relative inline">
      {/* Anchor trigger - the highlighted claim text */}
      <span
        onClick={() => setIsOpen(!isOpen)}
        className={`
          inline cursor-pointer border-b-2 border-dashed transition-all
          hover:border-solid
          ${config.borderColor}
        `}
        style={{
          borderBottomColor: anchor.highlightColor || undefined,
          backgroundColor: isOpen ? `${anchor.highlightColor}15` : undefined
        }}
      >
        {children}
        <sup 
          className={`
            ml-0.5 text-[10px] font-bold px-1 py-0.5 rounded 
            ${config.bgColor} ${config.color}
          `}
        >
          {anchor.pageNumber ? `p.${anchor.pageNumber}` : '↗'}
        </sup>
      </span>

      {/* Popup with source text */}
      {isOpen && (
        <>
          {/* Backdrop */}
          <div 
            className="fixed inset-0 z-40"
            onClick={() => setIsOpen(false)}
          />
          
          {/* Popup */}
          <div className={`
            absolute z-50 left-0 top-full mt-2 
            w-80 sm:w-96 
            rounded-xl shadow-2xl border-2
            ${config.bgColor} ${config.borderColor}
            animate-in fade-in zoom-in-95 slide-in-from-top-2 duration-200
          `}>
            {/* Header */}
            <div className={`
              flex items-center justify-between px-4 py-3 border-b ${config.borderColor}
            `}>
              <div className="flex items-center gap-2">
                <span className={config.color}>{config.icon}</span>
                <span className={`text-sm font-bold ${config.color}`}>
                  {config.label}
                </span>
                {anchor.pageNumber && (
                  <span className="text-xs text-gray-500 dark:text-gray-400">
                    Page {anchor.pageNumber}
                  </span>
                )}
              </div>
              <button
                onClick={() => setIsOpen(false)}
                className="p-1 rounded-lg hover:bg-white/50 dark:hover:bg-black/20 transition-colors"
              >
                <X size={14} className="text-gray-500" />
              </button>
            </div>

            {/* Content */}
            <div className="p-4 space-y-3">
              {/* Original source text */}
              <div>
                <label className="text-[10px] font-bold uppercase tracking-wider text-gray-500 dark:text-gray-400 mb-1 block">
                  Original Text
                </label>
                <blockquote className="text-sm text-gray-700 dark:text-gray-300 bg-white/50 dark:bg-black/20 p-3 rounded-lg border-l-4 border-gray-300 dark:border-gray-600 italic">
                  "{anchor.sourceText}"
                </blockquote>
              </div>

              {/* Confidence explanation */}
              <div className={`
                flex items-start gap-2 p-2 rounded-lg 
                ${anchor.confidence === 'interpretation' 
                  ? 'bg-amber-100/50 dark:bg-amber-900/20' 
                  : 'bg-white/30 dark:bg-black/10'
                }
              `}>
                <HelpCircle size={14} className="flex-shrink-0 mt-0.5 text-gray-400" />
                <p className="text-xs text-gray-600 dark:text-gray-400">
                  {config.description}
                </p>
              </div>
            </div>

            {/* Footer */}
            <div className="px-4 py-3 border-t border-gray-200/50 dark:border-gray-700/50 flex items-center justify-between">
              <span className="text-[10px] text-gray-400">
                Click outside to close
              </span>
              <button
                onClick={() => {
                  // In a real implementation, this would scroll to the PDF location
                  console.log('Navigate to source:', anchor);
                }}
                className="flex items-center gap-1 text-xs font-medium text-brand-600 dark:text-brand-400 hover:underline"
              >
                <ExternalLink size={12} />
                View in PDF
              </button>
            </div>
          </div>
        </>
      )}
    </span>
  );
};

// Inline confidence badge (for use in content)
export const ConfidenceBadge: React.FC<{ level: ConfidenceLevel; compact?: boolean }> = ({ 
  level, 
  compact = false 
}) => {
  const config = confidenceConfig[level];
  
  if (compact) {
    return (
      <span 
        className={`inline-flex items-center justify-center w-4 h-4 rounded-full ${config.bgColor} ${config.color}`}
        title={config.label}
      >
        {config.icon}
      </span>
    );
  }

  return (
    <span className={`
      inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium
      ${config.bgColor} ${config.color}
    `}>
      {config.icon}
      <span>{config.label}</span>
    </span>
  );
};

export default SourceAnchorComponent;
