import React from 'react'
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClient, useQueryDocument, useIngestDocument } from './lib/queries'
import { Film } from 'lucide-react'
import { QueryInput } from './components/QueryInput'
import { KeywordsDisplay } from './components/KeywordsDisplay'
import { ResponsePanel } from './components/ResponsePanel'
import { IngestPanel } from './components/IngestPanel'
import { ErrorBoundary } from './components/ErrorBoundary'

const VideoPlaceholder: React.FC = () => {
  return (
    <div className="h-full flex items-center justify-center bg-white/50">
      <div className="text-center space-y-2">
        <Film className="mx-auto w-12 h-12 text-gray-600" />
        <div className="text-gray-700 font-semibold">Video upload coming in Phase 2</div>
      </div>
    </div>
  )
}

const AppContent: React.FC = () => {
  const queryMutation = useQueryDocument()
  const ingestMutation = useIngestDocument()

  const handleQuerySubmit = (question: string): void => {
    queryMutation.mutate({ question })
  }

  const handleFileUpload = (file: File): void => {
    ingestMutation.mutate(file)
  }

  return (
    <div className="h-screen grid grid-rows-[30%_1fr] grid-cols-2 bg-gray-50">
      <div className="border-r border-b border-gray-200 p-4 min-h-0 overflow-hidden">
        <VideoPlaceholder />
      </div>
      <div className="border-b border-gray-200 p-6 flex flex-col gap-4 overflow-y-auto min-h-0">
        <QueryInput onSubmit={handleQuerySubmit} isLoading={queryMutation.isPending} />
        <KeywordsDisplay keywords={queryMutation.data?.keywords} isLoading={queryMutation.isPending} />
        <IngestPanel
          onUpload={handleFileUpload}
          isLoading={ingestMutation.isPending}
          success={ingestMutation.isSuccess ? ingestMutation.data?.filename ?? null : null}
          error={ingestMutation.isError ? (ingestMutation.error instanceof Error ? ingestMutation.error.message : 'Upload failed') : null}
        />
      </div>
      <div className="col-span-2 p-6 border-t border-gray-200 overflow-y-auto min-h-0">
        <ResponsePanel
          answer={queryMutation.data?.answer ?? null}
          sources={queryMutation.data?.sources ?? []}
          isLoading={queryMutation.isPending}
          error={queryMutation.isError ? (queryMutation.error instanceof Error ? queryMutation.error.message : 'Query failed') : null}
        />
      </div>
    </div>
  )
}

export default function App(): JSX.Element {
  return (
    <QueryClientProvider client={queryClient}>
      <ErrorBoundary>
        <AppContent />
      </ErrorBoundary>
    </QueryClientProvider>
  )
}
