import React, { useState, useRef, useEffect } from 'react'
import { ChevronLeft, ZoomIn, ZoomOut, Plus, Edit2, Trash2, Tag, CheckCircle, Check, X } from 'lucide-react'
import { Button } from './Button'
import { useDocumentDetail } from '../hooks/useDocumentDetail'
import { useAnnotations } from '../hooks/useAnnotations'
import { useDocuments } from '../hooks/useDocuments'
import { documentsApi } from '../api/endpoints/documents'
import type { AnnotationItem } from '../api/types'

interface DocumentDetailProps {
  docId: string
  onBack: () => void
}

// Field class mapping from backend
const FIELD_CLASSES: Record<number, string> = {
  0: 'invoice_number',
  1: 'invoice_date',
  2: 'invoice_due_date',
  3: 'ocr_number',
  4: 'bankgiro',
  5: 'plusgiro',
  6: 'amount',
  7: 'supplier_organisation_number',
  8: 'payment_line',
  9: 'customer_number',
}

export const DocumentDetail: React.FC<DocumentDetailProps> = ({ docId, onBack }) => {
  const { document, annotations, isLoading, refetch } = useDocumentDetail(docId)
  const {
    createAnnotation,
    updateAnnotation,
    deleteAnnotation,
    isCreating,
    isDeleting,
  } = useAnnotations(docId)
  const { updateGroupKey, isUpdatingGroupKey } = useDocuments({})

  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [zoom, setZoom] = useState(100)
  const [isDrawing, setIsDrawing] = useState(false)
  const [isEditingGroupKey, setIsEditingGroupKey] = useState(false)
  const [editGroupKeyValue, setEditGroupKeyValue] = useState('')
  const [drawStart, setDrawStart] = useState<{ x: number; y: number } | null>(null)
  const [drawEnd, setDrawEnd] = useState<{ x: number; y: number } | null>(null)
  const [selectedClassId, setSelectedClassId] = useState<number>(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [imageSize, setImageSize] = useState<{ width: number; height: number } | null>(null)
  const [imageBlobUrl, setImageBlobUrl] = useState<string | null>(null)

  const canvasRef = useRef<HTMLDivElement>(null)
  const imageRef = useRef<HTMLImageElement>(null)

  const [isMarkingComplete, setIsMarkingComplete] = useState(false)

  const selectedAnnotation = annotations?.find((a) => a.annotation_id === selectedId)

  // Handle mark as complete
  const handleMarkComplete = async () => {
    if (!annotations || annotations.length === 0) {
      alert('Please add at least one annotation before marking as complete.')
      return
    }

    if (!confirm('Mark this document as labeled? This will save annotations to the database.')) {
      return
    }

    setIsMarkingComplete(true)
    try {
      const result = await documentsApi.updateStatus(docId, 'labeled')
      alert(`Document marked as labeled. ${(result as any).fields_saved || annotations.length} annotations saved.`)
      onBack() // Return to document list
    } catch (error) {
      console.error('Failed to mark document as complete:', error)
      alert('Failed to mark document as complete. Please try again.')
    } finally {
      setIsMarkingComplete(false)
    }
  }

  // Load image via fetch with authentication header
  useEffect(() => {
    let objectUrl: string | null = null

    const loadImage = async () => {
      if (!docId) return

      const token = localStorage.getItem('admin_token')
      const imageUrl = `${import.meta.env.VITE_API_URL || 'http://localhost:8000'}/api/v1/admin/documents/${docId}/images/${currentPage}`

      try {
        const response = await fetch(imageUrl, {
          headers: {
            'X-Admin-Token': token || '',
          },
        })

        if (!response.ok) {
          throw new Error(`Failed to load image: ${response.status}`)
        }

        const blob = await response.blob()
        objectUrl = URL.createObjectURL(blob)
        setImageBlobUrl(objectUrl)
      } catch (error) {
        console.error('Failed to load image:', error)
      }
    }

    loadImage()

    // Cleanup: revoke object URL when component unmounts or page changes
    return () => {
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl)
      }
    }
  }, [currentPage, docId])

  // Load image size
  useEffect(() => {
    if (imageRef.current && imageRef.current.complete) {
      setImageSize({
        width: imageRef.current.naturalWidth,
        height: imageRef.current.naturalHeight,
      })
    }
  }, [imageBlobUrl])

  const handleImageLoad = () => {
    if (imageRef.current) {
      setImageSize({
        width: imageRef.current.naturalWidth,
        height: imageRef.current.naturalHeight,
      })
    }
  }

  const handleMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!canvasRef.current || !imageSize) return
    const rect = canvasRef.current.getBoundingClientRect()
    const x = (e.clientX - rect.left) / (zoom / 100)
    const y = (e.clientY - rect.top) / (zoom / 100)
    setIsDrawing(true)
    setDrawStart({ x, y })
    setDrawEnd({ x, y })
  }

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!isDrawing || !canvasRef.current || !imageSize) return
    const rect = canvasRef.current.getBoundingClientRect()
    const x = (e.clientX - rect.left) / (zoom / 100)
    const y = (e.clientY - rect.top) / (zoom / 100)
    setDrawEnd({ x, y })
  }

  const handleMouseUp = () => {
    if (!isDrawing || !drawStart || !drawEnd || !imageSize) {
      setIsDrawing(false)
      return
    }

    const bbox_x = Math.min(drawStart.x, drawEnd.x)
    const bbox_y = Math.min(drawStart.y, drawEnd.y)
    const bbox_width = Math.abs(drawEnd.x - drawStart.x)
    const bbox_height = Math.abs(drawEnd.y - drawStart.y)

    // Only create if box is large enough (min 10x10 pixels)
    if (bbox_width > 10 && bbox_height > 10) {
      createAnnotation({
        page_number: currentPage,
        class_id: selectedClassId,
        bbox: {
          x: Math.round(bbox_x),
          y: Math.round(bbox_y),
          width: Math.round(bbox_width),
          height: Math.round(bbox_height),
        },
      })
    }

    setIsDrawing(false)
    setDrawStart(null)
    setDrawEnd(null)
  }

  const handleDeleteAnnotation = (annotationId: string) => {
    if (confirm('Are you sure you want to delete this annotation?')) {
      deleteAnnotation(annotationId)
      setSelectedId(null)
    }
  }

  if (isLoading || !document) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="text-warm-text-muted">Loading...</div>
      </div>
    )
  }

  // Get current page annotations
  const pageAnnotations = annotations?.filter((a) => a.page_number === currentPage) || []

  return (
    <div className="flex h-[calc(100vh-56px)] overflow-hidden">
      {/* Main Canvas Area */}
      <div className="flex-1 bg-warm-bg flex flex-col relative">
        {/* Toolbar */}
        <div className="h-14 border-b border-warm-border bg-white flex items-center justify-between px-4 z-10">
          <div className="flex items-center gap-4">
            <button
              onClick={onBack}
              className="p-2 hover:bg-warm-hover rounded-md text-warm-text-secondary transition-colors"
            >
              <ChevronLeft size={20} />
            </button>
            <div>
              <h2 className="text-sm font-semibold text-warm-text-primary">{document.filename}</h2>
              <p className="text-xs text-warm-text-muted">
                Page {currentPage} of {document.page_count}
              </p>
            </div>
            <div className="h-6 w-px bg-warm-divider mx-2" />
            <div className="flex items-center gap-2">
              <button
                className="p-1.5 hover:bg-warm-hover rounded text-warm-text-secondary"
                onClick={() => setZoom((z) => Math.max(50, z - 10))}
              >
                <ZoomOut size={16} />
              </button>
              <span className="text-xs font-mono w-12 text-center text-warm-text-secondary">
                {zoom}%
              </span>
              <button
                className="p-1.5 hover:bg-warm-hover rounded text-warm-text-secondary"
                onClick={() => setZoom((z) => Math.min(200, z + 10))}
              >
                <ZoomIn size={16} />
              </button>
            </div>
          </div>
          <div className="flex gap-2">
            <Button variant="secondary" size="sm">
              Auto-label
            </Button>
            <Button
              variant="primary"
              size="sm"
              onClick={handleMarkComplete}
              disabled={isMarkingComplete || document.status === 'labeled'}
            >
              <CheckCircle size={16} className="mr-1" />
              {isMarkingComplete ? 'Saving...' : document.status === 'labeled' ? 'Labeled' : 'Mark Complete'}
            </Button>
            {document.page_count > 1 && (
              <div className="flex gap-1">
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                >
                  Prev
                </Button>
                <Button
                  variant="secondary"
                  size="sm"
                  onClick={() => setCurrentPage((p) => Math.min(document.page_count, p + 1))}
                  disabled={currentPage === document.page_count}
                >
                  Next
                </Button>
              </div>
            )}
          </div>
        </div>

        {/* Canvas Scroll Area */}
        <div className="flex-1 overflow-auto p-8 flex justify-center bg-warm-bg">
          <div
            ref={canvasRef}
            className="bg-white shadow-lg relative transition-transform duration-200 ease-out origin-top"
            style={{
              width: imageSize?.width || 800,
              height: imageSize?.height || 1132,
              transform: `scale(${zoom / 100})`,
              marginBottom: '100px',
              cursor: isDrawing ? 'crosshair' : 'default',
            }}
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
            onClick={() => setSelectedId(null)}
          >
            {/* Document Image */}
            {imageBlobUrl ? (
              <img
                ref={imageRef}
                src={imageBlobUrl}
                alt={`Page ${currentPage}`}
                className="w-full h-full object-contain select-none pointer-events-none"
                onLoad={handleImageLoad}
              />
            ) : (
              <div className="flex items-center justify-center h-full">
                <div className="text-warm-text-muted">Loading image...</div>
              </div>
            )}

            {/* Annotation Overlays */}
            {pageAnnotations.map((ann) => {
              const isSelected = selectedId === ann.annotation_id
              return (
                <div
                  key={ann.annotation_id}
                  onClick={(e) => {
                    e.stopPropagation()
                    setSelectedId(ann.annotation_id)
                  }}
                  className={`
                    absolute group cursor-pointer transition-all duration-100
                    ${
                      ann.source === 'auto'
                        ? 'border border-dashed border-warm-text-muted bg-transparent'
                        : 'border-2 border-warm-text-secondary bg-warm-text-secondary/5'
                    }
                    ${
                      isSelected
                        ? 'border-2 border-warm-state-info ring-4 ring-warm-state-info/10 z-20'
                        : 'hover:bg-warm-state-info/5 z-10'
                    }
                  `}
                  style={{
                    left: ann.bbox.x,
                    top: ann.bbox.y,
                    width: ann.bbox.width,
                    height: ann.bbox.height,
                  }}
                >
                  {/* Label Tag */}
                  <div
                    className={`
                    absolute -top-6 left-0 text-[10px] uppercase font-bold px-1.5 py-0.5 rounded-sm tracking-wide shadow-sm whitespace-nowrap
                    ${
                      isSelected
                        ? 'bg-warm-state-info text-white'
                        : 'bg-white text-warm-text-secondary border border-warm-border'
                    }
                  `}
                  >
                    {ann.class_name}
                  </div>

                  {/* Resize Handles (Visual only) */}
                  {isSelected && (
                    <>
                      <div className="absolute -top-1 -left-1 w-2 h-2 bg-white border border-warm-state-info rounded-full" />
                      <div className="absolute -top-1 -right-1 w-2 h-2 bg-white border border-warm-state-info rounded-full" />
                      <div className="absolute -bottom-1 -left-1 w-2 h-2 bg-white border border-warm-state-info rounded-full" />
                      <div className="absolute -bottom-1 -right-1 w-2 h-2 bg-white border border-warm-state-info rounded-full" />
                    </>
                  )}
                </div>
              )
            })}

            {/* Drawing Box Preview */}
            {isDrawing && drawStart && drawEnd && (
              <div
                className="absolute border-2 border-warm-state-info bg-warm-state-info/10 z-30 pointer-events-none"
                style={{
                  left: Math.min(drawStart.x, drawEnd.x),
                  top: Math.min(drawStart.y, drawEnd.y),
                  width: Math.abs(drawEnd.x - drawStart.x),
                  height: Math.abs(drawEnd.y - drawStart.y),
                }}
              />
            )}
          </div>
        </div>
      </div>

      {/* Right Sidebar */}
      <div className="w-80 bg-white border-l border-warm-border flex flex-col shadow-[-4px_0_15px_-3px_rgba(0,0,0,0.03)] z-20">
        {/* Field Selector */}
        <div className="p-4 border-b border-warm-border">
          <h3 className="text-sm font-semibold text-warm-text-primary mb-3">Draw Annotation</h3>
          <div className="space-y-2">
            <label className="block text-xs text-warm-text-muted mb-1">Select Field Type</label>
            <select
              value={selectedClassId}
              onChange={(e) => setSelectedClassId(Number(e.target.value))}
              className="w-full px-3 py-2 border border-warm-border rounded-md text-sm focus:outline-none focus:ring-1 focus:ring-warm-state-info"
            >
              {Object.entries(FIELD_CLASSES).map(([id, name]) => (
                <option key={id} value={id}>
                  {name.replace(/_/g, ' ')}
                </option>
              ))}
            </select>
            <p className="text-xs text-warm-text-muted mt-2">
              Click and drag on the document to create a bounding box
            </p>
          </div>
        </div>

        {/* Document Info Card */}
        <div className="p-4 border-b border-warm-border">
          <div className="bg-white rounded-lg border border-warm-border p-4 shadow-sm">
            <h3 className="text-sm font-semibold text-warm-text-primary mb-3">Document Info</h3>
            <div className="space-y-2">
              <div className="flex justify-between text-xs">
                <span className="text-warm-text-muted">Status</span>
                <span className="text-warm-text-secondary font-medium capitalize">
                  {document.status}
                </span>
              </div>
              <div className="flex justify-between text-xs">
                <span className="text-warm-text-muted">Size</span>
                <span className="text-warm-text-secondary font-medium">
                  {(document.file_size / 1024 / 1024).toFixed(2)} MB
                </span>
              </div>
              <div className="flex justify-between text-xs">
                <span className="text-warm-text-muted">Uploaded</span>
                <span className="text-warm-text-secondary font-medium">
                  {new Date(document.created_at).toLocaleDateString()}
                </span>
              </div>
              <div className="flex justify-between items-center text-xs">
                <span className="text-warm-text-muted">Group</span>
                {isEditingGroupKey ? (
                  <div className="flex items-center gap-1">
                    <input
                      type="text"
                      value={editGroupKeyValue}
                      onChange={(e) => setEditGroupKeyValue(e.target.value)}
                      className="w-24 px-1.5 py-0.5 text-xs border border-warm-border rounded focus:outline-none focus:ring-1 focus:ring-warm-state-info"
                      placeholder="group key"
                      autoFocus
                    />
                    <button
                      onClick={() => {
                        updateGroupKey(
                          { documentId: docId, groupKey: editGroupKeyValue.trim() || null },
                          {
                            onSuccess: () => {
                              setIsEditingGroupKey(false)
                              refetch()
                            },
                            onError: () => {
                              alert('Failed to update group key. Please try again.')
                            },
                          }
                        )
                      }}
                      disabled={isUpdatingGroupKey}
                      className="p-0.5 text-warm-state-success hover:bg-warm-hover rounded"
                    >
                      <Check size={14} />
                    </button>
                    <button
                      onClick={() => {
                        setIsEditingGroupKey(false)
                        setEditGroupKeyValue(document.group_key || '')
                      }}
                      className="p-0.5 text-warm-state-error hover:bg-warm-hover rounded"
                    >
                      <X size={14} />
                    </button>
                  </div>
                ) : (
                  <div className="flex items-center gap-1">
                    <span className="text-warm-text-secondary font-medium">
                      {document.group_key || '-'}
                    </span>
                    <button
                      onClick={() => {
                        setEditGroupKeyValue(document.group_key || '')
                        setIsEditingGroupKey(true)
                      }}
                      className="p-0.5 text-warm-text-muted hover:text-warm-text-secondary hover:bg-warm-hover rounded"
                    >
                      <Edit2 size={12} />
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Annotations List */}
        <div className="flex-1 overflow-y-auto p-4">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-warm-text-primary">Annotations</h3>
            <span className="text-xs text-warm-text-muted">{pageAnnotations.length} items</span>
          </div>

          {pageAnnotations.length === 0 ? (
            <div className="text-center py-8 text-warm-text-muted">
              <Tag size={48} className="mx-auto mb-3 opacity-20" />
              <p className="text-sm">No annotations yet</p>
              <p className="text-xs mt-1">Draw on the document to add annotations</p>
            </div>
          ) : (
            <div className="space-y-3">
              {pageAnnotations.map((ann) => (
                <div
                  key={ann.annotation_id}
                  onClick={() => setSelectedId(ann.annotation_id)}
                  className={`
                   group p-3 rounded-md border transition-all duration-150 cursor-pointer
                   ${
                     selectedId === ann.annotation_id
                       ? 'bg-warm-bg border-warm-state-info shadow-sm'
                       : 'bg-white border-warm-border hover:border-warm-text-muted'
                   }
                 `}
                >
                  <div className="flex justify-between items-start mb-1">
                    <span className="text-xs font-bold text-warm-text-secondary uppercase tracking-wider">
                      {ann.class_name.replace(/_/g, ' ')}
                    </span>
                    {selectedId === ann.annotation_id && (
                      <div className="flex gap-1">
                        <button
                          onClick={() => handleDeleteAnnotation(ann.annotation_id)}
                          className="text-warm-text-muted hover:text-warm-state-error"
                          disabled={isDeleting}
                        >
                          <Trash2 size={12} />
                        </button>
                      </div>
                    )}
                  </div>
                  <p className="text-sm text-warm-text-muted font-mono truncate">
                    {ann.text_value || '(no text)'}
                  </p>
                  <div className="flex items-center gap-2 mt-2">
                    <span
                      className={`text-[10px] px-1.5 py-0.5 rounded ${
                        ann.source === 'auto'
                          ? 'bg-blue-50 text-blue-700'
                          : 'bg-green-50 text-green-700'
                      }`}
                    >
                      {ann.source}
                    </span>
                    {ann.confidence && (
                      <span className="text-[10px] text-warm-text-muted">
                        {(ann.confidence * 100).toFixed(0)}%
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}