import React, { useState } from 'react'
import { MessageSquare, AlertCircle, Copy, ChevronDown, ChevronRight } from 'lucide-react'
import type { SourceMetadata } from '../types'

interface ResponsePanelProps {
  answer: string | null
  sources: SourceMetadata[]
  isLoading: boolean
  error: string | null
}

export const ResponsePanel: React.FC<ResponsePanelProps> = ({
  answer,
  sources,
  isLoading,
  error,
}) => {
  const [sourcesExpanded, setSourcesExpanded] = useState<boolean>(true)
  const [copied, setCopied] = useState<boolean>(false)

  const handleCopyAnswer = async (): Promise<void> => {
    if (answer) {
      await navigator.clipboard.writeText(answer)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    }
  }

  if (answer === null && !isLoading && !error) {
    return (
      <div className="h-full flex items-center justify-center bg-white/50">
        <div className="text-center space-y-2">
          <MessageSquare className="mx-auto w-12 h-12 text-gray-600" />
          <div className="text-gray-700 font-semibold">Ask a question to see the answer here.</div>
        </div>
      </div>
    )
  }

  if (isLoading) {
    return (
      <div className="space-y-3 p-4">
        <div
          data-testid="skeleton-line"
          className="h-4 bg-gray-200 rounded animate-pulse w-full"
        />
        <div
          data-testid="skeleton-line"
          className="h-4 bg-gray-200 rounded animate-pulse w-11/12"
        />
        <div
          data-testid="skeleton-line"
          className="h-4 bg-gray-200 rounded animate-pulse w-4/5"
        />
        <div
          data-testid="skeleton-line"
          className="h-4 bg-gray-200 rounded animate-pulse w-3/5"
        />
        <div
          data-testid="skeleton-line"
          className="h-4 bg-gray-200 rounded animate-pulse w-2/5"
        />
        <div className="mt-4 space-y-2">
          <div
            data-testid="source-skeleton"
            className="border border-gray-200 rounded p-3 bg-gray-50"
          >
            <div className="h-3 bg-gray-200 rounded w-3/4 mb-2 animate-pulse" />
            <div className="h-2 bg-gray-200 rounded w-1/2 animate-pulse" />
          </div>
          <div
            data-testid="source-skeleton"
            className="border border-gray-200 rounded p-3 bg-gray-50"
          >
            <div className="h-3 bg-gray-200 rounded w-2/3 mb-2 animate-pulse" />
            <div className="h-2 bg-gray-200 rounded w-1/3 animate-pulse" />
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 text-red-700 rounded p-4 m-4">
        <div className="flex items-center space-x-2">
          <AlertCircle className="w-5 h-5" />
          <span>{error}</span>
        </div>
      </div>
    )
  }

  return (
    <div className="p-4 space-y-4">
      <div className="space-y-2">
        <div className="flex items-start justify-between">
          <div className="flex-1" />
          <button
            data-testid="copy-answer-btn"
            onClick={handleCopyAnswer}
            className="flex items-center space-x-1 text-gray-500 hover:text-gray-700 transition-colors duration-200"
            title="Copy answer to clipboard"
          >
            <Copy className="w-4 h-4" />
            <span className="text-sm">{copied ? 'Copied!' : 'Copy'}</span>
          </button>
        </div>
        <div className="space-y-2 transition-all duration-300">
          {answer
            ?.split('\n')
            .map((line, index) => {
              const trimmedLine = line.trim()
              if (trimmedLine.startsWith('-') || trimmedLine.startsWith('•')) {
                const content = trimmedLine.replace(/^[-•]\s*/, '')
                return (
                  <li key={index} className="ml-4">
                    {content}
                  </li>
                )
              }
              return <p key={index}>{trimmedLine}</p>
            })}
        </div>
      </div>

      {sources.length > 0 && (
        <div className="mt-6">
          <button
            data-testid="sources-toggle"
            onClick={() => setSourcesExpanded(!sourcesExpanded)}
            className="flex items-center space-x-2 text-xs uppercase text-gray-500 tracking-wide mb-3 hover:text-gray-700 transition-colors duration-200"
          >
            {sourcesExpanded ? (
              <ChevronDown className="w-4 h-4" />
            ) : (
              <ChevronRight className="w-4 h-4" />
            )}
            <span>Sources ({sources.length})</span>
          </button>
          {sourcesExpanded && (
            <div data-testid="sources-container" className="grid grid-cols-2 gap-2">
              {sources.map((source, index) => (
                <div
                  key={index}
                  className="border border-gray-200 rounded p-3 bg-gray-50"
                >
                  <div className="font-medium text-sm">{source.filename}</div>
                  <div className="text-sm text-gray-500">{source.upload_date}</div>
                  <div className="text-sm text-gray-600 mt-1">{source.content_summary}</div>
                  <div className="text-xs text-gray-400 mt-1">Chunk {source.chunk_index}</div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
