import React, { useState } from 'react'
import { Search, ChevronDown, MoreHorizontal, FileText } from 'lucide-react'
import { Badge } from './Badge'
import { Button } from './Button'
import { UploadModal } from './UploadModal'
import { useDocuments, useCategories } from '../hooks/useDocuments'
import type { DocumentItem } from '../api/types'

interface DashboardProps {
  onNavigate: (view: string, docId?: string) => void
}

const getStatusForBadge = (status: string): string => {
  const statusMap: Record<string, string> = {
    pending: 'Pending',
    labeled: 'Labeled',
    verified: 'Verified',
    exported: 'Exported',
  }
  return statusMap[status] || status
}

const getAutoLabelProgress = (doc: DocumentItem): number | undefined => {
  if (doc.auto_label_status === 'running') {
    return 45
  }
  if (doc.auto_label_status === 'completed') {
    return 100
  }
  return undefined
}

export const Dashboard: React.FC<DashboardProps> = ({ onNavigate }) => {
  const [isUploadOpen, setIsUploadOpen] = useState(false)
  const [selectedDocs, setSelectedDocs] = useState<Set<string>>(new Set())
  const [statusFilter, setStatusFilter] = useState<string>('')
  const [categoryFilter, setCategoryFilter] = useState<string>('')
  const [limit] = useState(20)
  const [offset] = useState(0)

  const { categories } = useCategories()

  const { documents, total, isLoading, error, refetch } = useDocuments({
    status: statusFilter || undefined,
    category: categoryFilter || undefined,
    limit,
    offset,
  })

  const toggleSelection = (id: string) => {
    const newSet = new Set(selectedDocs)
    if (newSet.has(id)) {
      newSet.delete(id)
    } else {
      newSet.add(id)
    }
    setSelectedDocs(newSet)
  }

  if (error) {
    return (
      <div className="p-8 max-w-7xl mx-auto">
        <div className="bg-red-50 border border-red-200 text-red-800 p-4 rounded-lg">
          Error loading documents. Please check your connection to the backend API.
          <button
            onClick={() => refetch()}
            className="ml-4 underline hover:no-underline"
          >
            Retry
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="p-8 max-w-7xl mx-auto animate-fade-in">
      <div className="flex items-center justify-between mb-8">
        <div>
          <h1 className="text-3xl font-bold text-warm-text-primary tracking-tight">
            Documents
          </h1>
          <p className="text-sm text-warm-text-muted mt-1">
            {isLoading ? 'Loading...' : `${total} documents total`}
          </p>
        </div>
        <div className="flex gap-3">
          <Button variant="secondary" disabled={selectedDocs.size === 0}>
            Export Selection ({selectedDocs.size})
          </Button>
          <Button onClick={() => setIsUploadOpen(true)}>Upload Documents</Button>
        </div>
      </div>

      <div className="bg-warm-card border border-warm-border rounded-lg p-4 mb-6 shadow-sm flex flex-wrap gap-4 items-center">
        <div className="relative flex-1 min-w-[200px]">
          <Search
            className="absolute left-3 top-1/2 -translate-y-1/2 text-warm-text-muted"
            size={16}
          />
          <input
            type="text"
            placeholder="Search documents..."
            className="w-full pl-9 pr-4 h-10 rounded-md border border-warm-border bg-white focus:outline-none focus:ring-1 focus:ring-warm-state-info transition-shadow text-sm"
          />
        </div>

        <div className="flex gap-3">
          <div className="relative">
            <select
              value={categoryFilter}
              onChange={(e) => setCategoryFilter(e.target.value)}
              className="h-10 pl-3 pr-8 rounded-md border border-warm-border bg-white text-sm text-warm-text-secondary focus:outline-none appearance-none cursor-pointer hover:bg-warm-hover"
            >
              <option value="">All Categories</option>
              {categories.map((cat) => (
                <option key={cat} value={cat}>
                  {cat.charAt(0).toUpperCase() + cat.slice(1)}
                </option>
              ))}
            </select>
            <ChevronDown
              className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-warm-text-muted"
              size={14}
            />
          </div>
          <div className="relative">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="h-10 pl-3 pr-8 rounded-md border border-warm-border bg-white text-sm text-warm-text-secondary focus:outline-none appearance-none cursor-pointer hover:bg-warm-hover"
            >
              <option value="">All Statuses</option>
              <option value="pending">Pending</option>
              <option value="labeled">Labeled</option>
              <option value="verified">Verified</option>
              <option value="exported">Exported</option>
            </select>
            <ChevronDown
              className="absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-warm-text-muted"
              size={14}
            />
          </div>
        </div>
      </div>

      <div className="bg-warm-card border border-warm-border rounded-lg shadow-sm overflow-hidden">
        <table className="w-full text-left border-collapse">
          <thead>
            <tr className="border-b border-warm-border bg-white">
              <th className="py-3 pl-6 pr-4 w-12">
                <input
                  type="checkbox"
                  className="rounded border-warm-divider text-warm-text-primary focus:ring-warm-text-secondary"
                />
              </th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase tracking-wider">
                Document Name
              </th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase tracking-wider">
                Date
              </th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase tracking-wider">
                Status
              </th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase tracking-wider">
                Annotations
              </th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase tracking-wider">
                Category
              </th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase tracking-wider">
                Group
              </th>
              <th className="py-3 px-4 text-xs font-semibold text-warm-text-muted uppercase tracking-wider w-64">
                Auto-label
              </th>
              <th className="py-3 px-4 w-12"></th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr>
                <td colSpan={9} className="py-8 text-center text-warm-text-muted">
                  Loading documents...
                </td>
              </tr>
            ) : documents.length === 0 ? (
              <tr>
                <td colSpan={9} className="py-8 text-center text-warm-text-muted">
                  No documents found. Upload your first document to get started.
                </td>
              </tr>
            ) : (
              documents.map((doc) => {
                const isSelected = selectedDocs.has(doc.document_id)
                const progress = getAutoLabelProgress(doc)

                return (
                  <tr
                    key={doc.document_id}
                    onClick={() => onNavigate('detail', doc.document_id)}
                    className={`
                    group transition-colors duration-150 cursor-pointer border-b border-warm-border last:border-0
                    ${isSelected ? 'bg-warm-selected' : 'hover:bg-warm-hover bg-white'}
                  `}
                  >
                    <td
                      className="py-4 pl-6 pr-4 relative"
                      onClick={(e) => {
                        e.stopPropagation()
                        toggleSelection(doc.document_id)
                      }}
                    >
                      {isSelected && (
                        <div className="absolute left-0 top-0 bottom-0 w-[3px] bg-warm-state-info" />
                      )}
                      <input
                        type="checkbox"
                        checked={isSelected}
                        readOnly
                        className="rounded border-warm-divider text-warm-text-primary focus:ring-warm-text-secondary cursor-pointer"
                      />
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center gap-3">
                        <div className="p-2 bg-warm-bg rounded border border-warm-border text-warm-text-muted">
                          <FileText size={16} />
                        </div>
                        <span className="font-medium text-warm-text-secondary">
                          {doc.filename}
                        </span>
                      </div>
                    </td>
                    <td className="py-4 px-4 text-sm text-warm-text-secondary font-mono">
                      {new Date(doc.created_at).toLocaleDateString()}
                    </td>
                    <td className="py-4 px-4">
                      <Badge status={getStatusForBadge(doc.status)} />
                    </td>
                    <td className="py-4 px-4 text-sm text-warm-text-secondary">
                      {doc.annotation_count || 0} annotations
                    </td>
                    <td className="py-4 px-4 text-sm text-warm-text-secondary capitalize">
                      {doc.category || 'invoice'}
                    </td>
                    <td className="py-4 px-4 text-sm text-warm-text-muted">
                      {doc.group_key || '-'}
                    </td>
                    <td className="py-4 px-4">
                      {doc.auto_label_status === 'running' && progress && (
                        <div className="w-full">
                          <div className="flex justify-between text-xs mb-1">
                            <span className="text-warm-text-secondary font-medium">
                              Running
                            </span>
                            <span className="text-warm-text-muted">{progress}%</span>
                          </div>
                          <div className="h-1.5 w-full bg-warm-selected rounded-full overflow-hidden">
                            <div
                              className="h-full bg-warm-state-info transition-all duration-500 ease-out"
                              style={{ width: `${progress}%` }}
                            />
                          </div>
                        </div>
                      )}
                      {doc.auto_label_status === 'completed' && (
                        <span className="text-sm font-medium text-warm-state-success">
                          Completed
                        </span>
                      )}
                      {doc.auto_label_status === 'failed' && (
                        <span className="text-sm font-medium text-warm-state-error">
                          Failed
                        </span>
                      )}
                    </td>
                    <td className="py-4 px-4 text-right">
                      <button className="text-warm-text-muted hover:text-warm-text-secondary p-1 rounded hover:bg-black/5 transition-colors">
                        <MoreHorizontal size={18} />
                      </button>
                    </td>
                  </tr>
                )
              })
            )}
          </tbody>
        </table>
      </div>

      <UploadModal
        isOpen={isUploadOpen}
        onClose={() => {
          setIsUploadOpen(false)
          refetch()
        }}
      />
    </div>
  )
}
