'use client'
import React, { useRef, useState, useCallback } from 'react'
import { Button } from '@/components/ui/Button'
import { ProgressBar } from '@/components/ui/ProgressBar'
import { useIngestionStatus } from '@/lib/hooks/useIngestionStatus'
import { pb } from '@/lib/pocketbase'
import { postIngest } from '@/lib/services'

interface DocumentUploadProps {
  onSuccess: () => void
}

export function DocumentUpload({ onSuccess }: DocumentUploadProps) {
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [uploading, setUploading] = useState(false)
  const [jobId, setJobId] = useState<string | null>(null)
  const [uploadError, setUploadError] = useState<string | null>(null)
  const [dragOver, setDragOver] = useState(false)

  const { status, progress } = useIngestionStatus(jobId)

  const handleFiles = useCallback(
    async (files: FileList | null) => {
      if (!files || files.length === 0) return
      const file = files[0]
      if (!file) return

      const allowed = ['.pdf', '.md', '.txt']
      const ext = file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
      if (!allowed.includes(ext)) {
        setUploadError(`Unsupported file type: ${ext}. Use PDF, MD, or TXT.`)
        return
      }

      setUploadError(null)
      setUploading(true)
      setJobId(null)

      try {
        // Create record in PocketBase
        const format = ext.slice(1) as 'pdf' | 'md' | 'txt'

        // Force explicit MIME type — Windows doesn't register .md and sends
        // application/octet-stream which PocketBase rejects.
        const mimeMap: Record<string, string> = {
          pdf: 'application/pdf',
          md: 'text/markdown',
          txt: 'text/plain',
        }
        const blob = new Blob([file], { type: mimeMap[format] ?? file.type })

        const fd = new FormData()
        fd.append('file', blob, file.name)
        fd.append('filename', file.name)
        fd.append('format', format)
        fd.append('status', 'processing')

        const doc = await pb.collection('source_documents').create<{ id: string; file: string }>(fd)

        // Build PocketBase file download URL
        const pbUrl = process.env.NEXT_PUBLIC_POCKETBASE_URL ?? 'http://localhost:8090'
        const fileUrl = `${pbUrl}/api/files/source_documents/${doc.id}/${doc.file}`

        // Kick off ingestion
        const { jobId: jId } = await postIngest({
          documentId: doc.id,
          filename: file.name,
          format,
          fileUrl,
        })
        setJobId(jId)
      } catch (err) {
        // PocketBase ClientResponseError has a `response` with field details
        const pbErr = err as { response?: { message?: string; data?: Record<string, { message?: string }> } }
        const detail = pbErr.response?.data
          ? Object.entries(pbErr.response.data)
              .map(([f, v]) => `${f}: ${v?.message ?? ''}`)
              .join(', ')
          : null
        setUploadError(detail ?? (err instanceof Error ? err.message : 'Upload failed'))
      } finally {
        setUploading(false)
      }
    },
    [],
  )

  function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    void handleFiles(e.target.files)
    e.target.value = ''
  }

  function handleDrop(e: React.DragEvent<HTMLDivElement>) {
    e.preventDefault()
    setDragOver(false)
    void handleFiles(e.dataTransfer.files)
  }

  function handleDragOver(e: React.DragEvent<HTMLDivElement>) {
    e.preventDefault()
    setDragOver(true)
  }

  function handleDragLeave() {
    setDragOver(false)
  }

  const isDone = status?.status === 'done'
  const isFailed = status?.status === 'failed'

  if (isDone && jobId) {
    return (
      <div
        style={{
          background: 'var(--success)',
          borderRadius: 'var(--r-md)',
          padding: 'var(--s-5)',
          textAlign: 'center',
          display: 'flex',
          flexDirection: 'column',
          gap: 'var(--s-3)',
        }}
      >
        <p style={{ margin: 0, fontWeight: 600, color: 'var(--teal-900)' }}>
          Ingestion complete! {status.themesFound} themes, {status.topicsFound} topics found.
        </p>
        <Button
          variant="secondary"
          size="sm"
          onClick={() => {
            setJobId(null)
            onSuccess()
          }}
        >
          Upload another
        </Button>
      </div>
    )
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
      <div
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onClick={() => fileInputRef.current?.click()}
        style={{
          border: `2px dashed ${dragOver ? 'var(--accent)' : 'var(--cream)'}`,
          borderRadius: 'var(--r-lg)',
          padding: 'var(--s-8, 64px) var(--s-5)',
          textAlign: 'center',
          cursor: 'pointer',
          background: dragOver ? 'var(--accent-soft)' : 'var(--bg-warm)',
          transition: 'background 150ms, border-color 150ms',
        }}
      >
        <input
          ref={fileInputRef}
          type="file"
          accept=".pdf,.md,.txt"
          style={{ display: 'none' }}
          onChange={handleChange}
        />
        <p
          style={{
            margin: '0 0 var(--s-2)',
            fontSize: 'var(--t-lead)',
            fontWeight: 600,
            color: 'var(--fg)',
          }}
        >
          Drop a document here
        </p>
        <p style={{ margin: 0, fontSize: 'var(--t-small)', color: 'var(--fg-muted)' }}>
          or tap to browse — PDF, Markdown, TXT
        </p>
      </div>

      {uploadError && (
        <div
          style={{
            background: '#f8d7da',
            color: '#c0392b',
            borderRadius: 'var(--r-sm)',
            padding: 'var(--s-3) var(--s-4)',
            fontSize: 'var(--t-small)',
          }}
        >
          {uploadError}
        </div>
      )}

      {(uploading || jobId) && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
          <ProgressBar
            value={uploading ? 5 : progress}
            label={
              uploading
                ? 'Uploading…'
                : isFailed
                ? `Failed: ${status?.reason ?? 'unknown error'}`
                : status?.status
                ? `${status.status.charAt(0).toUpperCase()}${status.status.slice(1)}…`
                : 'Processing…'
            }
            color={isFailed ? '#c0392b' : 'var(--accent)'}
          />
          {status && (
            <div
              style={{
                fontSize: 'var(--t-small)',
                color: 'var(--fg-muted)',
                display: 'flex',
                gap: 'var(--s-4)',
                flexWrap: 'wrap',
              }}
            >
              <span>Chunks: {status.chunksEmbedded}/{status.chunksTotal}</span>
              <span>Themes: {status.themesFound}</span>
              <span>Topics: {status.topicsFound}</span>
            </div>
          )}
        </div>
      )}
    </div>
  )
}
