import React, { useState } from 'react'
import { Database, AlertCircle } from 'lucide-react'
import { useQueryClient } from '@tanstack/react-query'
import { useDocuments, useDocumentChunks, useDeleteDocument, useDeleteChunk, useIngestDocument } from '../lib/queries'
import { DocumentList } from '../components/DocumentList'
import { ChunkList } from '../components/ChunkList'
import { DocumentUpload } from '../components/DocumentUpload'

export const RAGDatabasePage: React.FC = () => {
  const [expandedId, setExpandedId] = useState<string | null>(null)
  const [uploadSuccess, setUploadSuccess] = useState<string | null>(null)
  const [uploadError, setUploadError] = useState<string | null>(null)

  const { data: documentsData, isLoading: isLoadingDocuments, error: documentsError } = useDocuments()
  const { data: chunks, isLoading: isLoadingChunks } = useDocumentChunks(expandedId)
  const deleteDocumentMutation = useDeleteDocument()
  const deleteChunkMutation = useDeleteChunk()
  const ingestDocumentMutation = useIngestDocument()
  const queryClient = useQueryClient()

  const handleToggleExpand = (documentId: string) => {
    setExpandedId(expandedId === documentId ? null : documentId)
  }

  const handleDeleteDocument = (documentId: string, filename: string) => {
    const doc = documentsData?.documents.find((d) => d.document_id === documentId)
    const chunkCount = doc?.chunk_count ?? 0
    if (window.confirm(`Delete "${filename}" and all its ${chunkCount} chunks?`)) {
      deleteDocumentMutation.mutate(documentId)
    }
  }

  const handleDeleteChunk = (chunkId: string) => {
    const chunk = chunks?.find((c) => c.chunk_id === chunkId)
    const chunkIndex = chunk?.chunk_index ?? 0
    if (window.confirm(`Delete chunk ${chunkIndex}?`)) {
      deleteChunkMutation.mutate(chunkId)
    }
  }

  const handleUpload = (file: File) => {
    setUploadSuccess(null)
    setUploadError(null)
    ingestDocumentMutation.mutate(file, {
      onSuccess: (data) => {
        setUploadSuccess(`Uploaded ${data.filename}`)
        queryClient.invalidateQueries({ queryKey: ['documents'] })
        setTimeout(() => setUploadSuccess(null), 3000)
      },
      onError: (error) => {
        setUploadError(error.message)
      },
    })
  }

  if (isLoadingDocuments) {
    return (
      <div className="p-6 space-y-4">
        <div className="h-8 bg-gray-200 rounded animate-pulse w-1/3" />
        <div className="h-4 bg-gray-200 rounded animate-pulse w-1/4" />
        <div className="space-y-3">
          <div className="h-20 bg-gray-200 rounded animate-pulse" />
          <div className="h-20 bg-gray-200 rounded animate-pulse" />
        </div>
      </div>
    )
  }

  if (documentsError) {
    return (
      <div className="p-4">
        <div className="bg-red-50 border border-red-200 text-red-700 rounded p-4">
          <div className="flex items-center space-x-2">
            <AlertCircle className="w-5 h-5" />
            <span>Failed to load documents: {documentsError.message}</span>
          </div>
        </div>
      </div>
    )
  }

  const documents = documentsData?.documents ?? []
  const hasDocuments = documents.length > 0

  return (
    <div className="h-full flex flex-col bg-gray-50">
      <div className="border-b border-gray-200 bg-white px-6 py-4">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-gray-900">RAG Database</h1>
          <DocumentUpload
            onUpload={handleUpload}
            isLoading={ingestDocumentMutation.isPending}
            success={uploadSuccess}
            error={uploadError}
          />
        </div>
      </div>

      {hasDocuments && (
        <div className="px-6 py-3 bg-white border-b border-gray-200">
          <div className="text-sm text-gray-600">
            Total: {documentsData?.total_documents ?? 0} documents,{' '}
            {documentsData?.total_chunks ?? 0} chunks
          </div>
        </div>
      )}

      <div className="flex-1 overflow-auto p-6">
        {!hasDocuments ? (
          <div className="h-full flex items-center justify-center bg-white/50 rounded-lg border border-gray-200">
            <div className="text-center space-y-2">
              <Database className="mx-auto w-12 h-12 text-gray-600" />
              <div className="text-gray-700 font-semibold">No documents uploaded yet</div>
              <div className="text-sm text-gray-500">Upload a document to get started</div>
            </div>
          </div>
        ) : (
          <div className="space-y-3">
            {documents.map((doc) => (
              <div key={doc.document_id} className="space-y-0">
                <DocumentList
                  documents={[doc]}
                  expandedId={expandedId}
                  onToggleExpand={handleToggleExpand}
                  onDelete={handleDeleteDocument}
                  isDeleting={deleteDocumentMutation.isPending}
                />
                {expandedId === doc.document_id && (
                  <div className="ml-6 border-l-2 border-gray-200 pl-4">
                    <ChunkList
                      chunks={chunks ?? []}
                      isLoading={isLoadingChunks}
                      onDeleteChunk={handleDeleteChunk}
                      isDeleting={deleteChunkMutation.isPending}
                    />
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
