import React, { useState, useRef } from 'react'
import { UploadCloud, FileText, Loader2, CheckCircle2, AlertCircle, Clock, Table2 } from 'lucide-react'
import { Button } from './Button'
import { inferenceApi } from '../api/endpoints'
import { LineItemsTable } from './LineItemsTable'
import { VATSummaryCard } from './VATSummaryCard'
import type { InferenceResult } from '../api/types'

export const InferenceDemo: React.FC = () => {
  const [isDragging, setIsDragging] = useState(false)
  const [selectedFile, setSelectedFile] = useState<File | null>(null)
  const [isProcessing, setIsProcessing] = useState(false)
  const [result, setResult] = useState<InferenceResult | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [extractLineItems, setExtractLineItems] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  const handleFileSelect = (file: File | null) => {
    if (!file) return

    const validTypes = ['application/pdf', 'image/png', 'image/jpeg', 'image/jpg']
    if (!validTypes.includes(file.type)) {
      setError('Please upload a PDF, PNG, or JPG file')
      return
    }

    if (file.size > 50 * 1024 * 1024) {
      setError('File size must be less than 50MB')
      return
    }

    setSelectedFile(file)
    setResult(null)
    setError(null)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    if (e.dataTransfer.files.length > 0) {
      handleFileSelect(e.dataTransfer.files[0])
    }
  }

  const handleBrowseClick = () => {
    fileInputRef.current?.click()
  }

  const handleProcess = async () => {
    if (!selectedFile) return

    setIsProcessing(true)
    setError(null)

    try {
      const response = await inferenceApi.processDocument(selectedFile, {
        extractLineItems,
      })
      setResult(response.result)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Processing failed')
    } finally {
      setIsProcessing(false)
    }
  }

  const handleReset = () => {
    setSelectedFile(null)
    setResult(null)
    setError(null)
    setExtractLineItems(false)
  }

  const formatFieldName = (field: string): string => {
    const fieldNames: Record<string, string> = {
      InvoiceNumber: 'Invoice Number',
      InvoiceDate: 'Invoice Date',
      InvoiceDueDate: 'Due Date',
      OCR: 'OCR Number',
      Amount: 'Amount',
      Bankgiro: 'Bankgiro',
      Plusgiro: 'Plusgiro',
      supplier_org_number: 'Supplier Org Number',
      customer_number: 'Customer Number',
      payment_line: 'Payment Line',
    }
    return fieldNames[field] || field
  }

  return (
    <div className="max-w-7xl mx-auto px-4 py-6 space-y-6">
      {/* Header */}
      <div className="text-center">
        <h2 className="text-3xl font-bold text-warm-text-primary mb-2">
          Invoice Extraction Demo
        </h2>
        <p className="text-warm-text-muted">
          Upload a Swedish invoice to see our AI-powered field extraction in action
        </p>
      </div>

      {/* Upload Area */}
      {!result && (
        <div className="max-w-2xl mx-auto">
          <div className="bg-warm-card rounded-xl border border-warm-border p-8 shadow-sm">
            <div
              className={`
                relative h-72 rounded-xl border-2 border-dashed transition-all duration-200
                ${isDragging
                  ? 'border-warm-text-secondary bg-warm-selected scale-[1.02]'
                  : 'border-warm-divider bg-warm-bg hover:bg-warm-hover hover:border-warm-text-secondary/50'
                }
                ${isProcessing ? 'opacity-60 pointer-events-none' : 'cursor-pointer'}
              `}
              onDragOver={(e) => {
                e.preventDefault()
                setIsDragging(true)
              }}
              onDragLeave={() => setIsDragging(false)}
              onDrop={handleDrop}
              onClick={handleBrowseClick}
            >
              <div className="absolute inset-0 flex flex-col items-center justify-center gap-6">
                {isProcessing ? (
                  <>
                    <Loader2 size={56} className="text-warm-text-secondary animate-spin" />
                    <div className="text-center">
                      <p className="text-lg font-semibold text-warm-text-primary mb-1">
                        Processing invoice...
                      </p>
                      <p className="text-sm text-warm-text-muted">
                        This may take a few moments
                      </p>
                    </div>
                  </>
                ) : selectedFile ? (
                  <>
                    <div className="p-5 bg-warm-text-secondary/10 rounded-full">
                      <FileText size={40} className="text-warm-text-secondary" />
                    </div>
                    <div className="text-center px-4">
                      <p className="text-lg font-semibold text-warm-text-primary mb-1">
                        {selectedFile.name}
                      </p>
                      <p className="text-sm text-warm-text-muted">
                        {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                      </p>
                    </div>
                  </>
                ) : (
                  <>
                    <div className="p-5 bg-warm-text-secondary/10 rounded-full">
                      <UploadCloud size={40} className="text-warm-text-secondary" />
                    </div>
                    <div className="text-center px-4">
                      <p className="text-lg font-semibold text-warm-text-primary mb-2">
                        Drag & drop invoice here
                      </p>
                      <p className="text-sm text-warm-text-muted mb-3">
                        or{' '}
                        <span className="text-warm-text-secondary font-medium">
                          browse files
                        </span>
                      </p>
                      <p className="text-xs text-warm-text-muted">
                        Supports PDF, PNG, JPG (up to 50MB)
                      </p>
                    </div>
                  </>
                )}
              </div>
            </div>

            <input
              ref={fileInputRef}
              type="file"
              accept=".pdf,image/*"
              className="hidden"
              onChange={(e) => handleFileSelect(e.target.files?.[0] || null)}
            />

            {error && (
              <div className="mt-5 p-4 bg-red-50 border border-red-200 rounded-lg flex items-start gap-3">
                <AlertCircle size={18} className="text-red-600 flex-shrink-0 mt-0.5" />
                <span className="text-sm text-red-800 font-medium">{error}</span>
              </div>
            )}

            {selectedFile && !isProcessing && (
              <div className="mt-6 space-y-4">
                {/* Business Features Checkbox */}
                <label className="flex items-center gap-3 p-4 bg-warm-bg/50 rounded-lg border border-warm-divider cursor-pointer hover:bg-warm-hover/50 transition-colors">
                  <input
                    type="checkbox"
                    checked={extractLineItems}
                    onChange={(e) => setExtractLineItems(e.target.checked)}
                    className="w-5 h-5 rounded border-warm-border text-warm-text-secondary focus:ring-warm-text-secondary"
                  />
                  <div className="flex items-center gap-2">
                    <Table2 size={18} className="text-warm-text-secondary" />
                    <div>
                      <span className="font-medium text-warm-text-primary">
                        Extract Line Items & VAT
                      </span>
                      <p className="text-xs text-warm-text-muted mt-0.5">
                        Extract product/service rows, VAT breakdown, and cross-validation
                      </p>
                    </div>
                  </div>
                </label>

                <div className="flex gap-3 justify-end">
                  <Button variant="secondary" onClick={handleReset}>
                    Cancel
                  </Button>
                  <Button onClick={handleProcess}>Process Invoice</Button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Results */}
      {result && (
        <div className="space-y-6">
          {/* Status Header */}
          <div className="bg-warm-card rounded-xl border border-warm-border shadow-sm overflow-hidden">
            <div className="p-6 flex items-center justify-between border-b border-warm-divider">
              <div className="flex items-center gap-4">
                {result.success ? (
                  <div className="p-3 bg-green-100 rounded-xl">
                    <CheckCircle2 size={28} className="text-green-600" />
                  </div>
                ) : (
                  <div className="p-3 bg-yellow-100 rounded-xl">
                    <AlertCircle size={28} className="text-yellow-600" />
                  </div>
                )}
                <div>
                  <h3 className="text-xl font-bold text-warm-text-primary">
                    {result.success ? 'Extraction Complete' : 'Partial Results'}
                  </h3>
                  <p className="text-sm text-warm-text-muted mt-0.5">
                    Document ID: <span className="font-mono">{result.document_id}</span>
                  </p>
                </div>
              </div>
              <Button variant="secondary" onClick={handleReset}>
                Process Another
              </Button>
            </div>

            <div className="px-6 py-4 bg-warm-bg/50 flex items-center gap-6 text-sm">
              <div className="flex items-center gap-2 text-warm-text-secondary">
                <Clock size={16} />
                <span className="font-medium">
                  {result.processing_time_ms.toFixed(0)}ms
                </span>
              </div>
              {result.fallback_used && (
                <span className="px-3 py-1.5 bg-warm-selected rounded-md text-warm-text-secondary font-medium text-xs">
                  Fallback OCR Used
                </span>
              )}
            </div>
          </div>

          {/* Main Content Grid */}
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Left Column: Extracted Fields */}
            <div className="lg:col-span-2 space-y-6">
              <div className="bg-warm-card rounded-xl border border-warm-border p-6 shadow-sm">
                <h3 className="text-lg font-bold text-warm-text-primary mb-5 flex items-center gap-2">
                  <span className="w-1 h-5 bg-warm-text-secondary rounded-full"></span>
                  Extracted Fields
                </h3>
                <div className="flex flex-wrap gap-4">
                  {Object.entries(result.fields).map(([field, value]) => {
                    const confidence = result.confidence[field]
                    return (
                      <div
                        key={field}
                        className="p-4 bg-warm-bg/70 rounded-lg border border-warm-divider hover:border-warm-text-secondary/30 transition-colors w-[calc(50%-0.5rem)]"
                      >
                        <div className="text-xs font-semibold text-warm-text-muted uppercase tracking-wide mb-2">
                          {formatFieldName(field)}
                        </div>
                        <div className="text-sm font-bold text-warm-text-primary mb-2 min-h-[1.5rem]">
                          {value || <span className="text-warm-text-muted italic">N/A</span>}
                        </div>
                        {confidence && (
                          <div className="flex items-center gap-1.5 text-xs font-medium text-warm-text-secondary">
                            <CheckCircle2 size={13} />
                            <span>{(confidence * 100).toFixed(1)}%</span>
                          </div>
                        )}
                      </div>
                    )
                  })}
                </div>
              </div>

              {/* Line Items */}
              {result.line_items && (
                <div className="bg-warm-card rounded-xl border border-warm-border p-6 shadow-sm">
                  <h3 className="text-lg font-bold text-warm-text-primary mb-5 flex items-center gap-2">
                    <span className="w-1 h-5 bg-warm-text-secondary rounded-full"></span>
                    <Table2 size={20} className="text-warm-text-secondary" />
                    Line Items
                    <span className="ml-auto text-sm font-normal text-warm-text-muted">
                      {result.line_items.items.length} item(s)
                    </span>
                  </h3>
                  <LineItemsTable lineItems={result.line_items} />
                </div>
              )}

              {/* Visualization */}
              {result.visualization_url && (
                <div className="bg-warm-card rounded-xl border border-warm-border p-6 shadow-sm">
                  <h3 className="text-lg font-bold text-warm-text-primary mb-5 flex items-center gap-2">
                    <span className="w-1 h-5 bg-warm-text-secondary rounded-full"></span>
                    Detection Visualization
                  </h3>
                  <div className="bg-warm-bg rounded-lg overflow-hidden border border-warm-divider">
                    <img
                      src={`${import.meta.env.VITE_API_URL || 'http://localhost:8000'}${result.visualization_url}`}
                      alt="Detection visualization"
                      className="w-full h-auto"
                    />
                  </div>
                </div>
              )}
            </div>

            {/* Right Column: Cross-Validation & Errors */}
            <div className="space-y-6">
              {/* Cross-Validation */}
              {result.cross_validation && (
                <div className="bg-warm-card rounded-xl border border-warm-border p-6 shadow-sm">
                  <h3 className="text-lg font-bold text-warm-text-primary mb-4 flex items-center gap-2">
                    <span className="w-1 h-5 bg-warm-text-secondary rounded-full"></span>
                    Payment Line Validation
                  </h3>

                  <div
                    className={`
                      p-4 rounded-lg mb-4 flex items-center gap-3
                      ${result.cross_validation.is_valid
                        ? 'bg-green-50 border border-green-200'
                        : 'bg-yellow-50 border border-yellow-200'
                      }
                    `}
                  >
                    {result.cross_validation.is_valid ? (
                      <>
                        <CheckCircle2 size={22} className="text-green-600 flex-shrink-0" />
                        <span className="font-bold text-green-800">All Fields Match</span>
                      </>
                    ) : (
                      <>
                        <AlertCircle size={22} className="text-yellow-600 flex-shrink-0" />
                        <span className="font-bold text-yellow-800">Mismatch Detected</span>
                      </>
                    )}
                  </div>

                  <div className="space-y-2.5">
                    {result.cross_validation.payment_line_ocr && (
                      <div
                        className={`
                          p-3 rounded-lg border transition-colors
                          ${result.cross_validation.ocr_match === true
                            ? 'bg-green-50 border-green-200'
                            : result.cross_validation.ocr_match === false
                            ? 'bg-red-50 border-red-200'
                            : 'bg-warm-bg border-warm-divider'
                          }
                        `}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex-1">
                            <div className="text-xs font-semibold text-warm-text-muted mb-1">
                              OCR NUMBER
                            </div>
                            <div className="text-sm font-bold text-warm-text-primary font-mono">
                              {result.cross_validation.payment_line_ocr}
                            </div>
                          </div>
                          {result.cross_validation.ocr_match === true && (
                            <CheckCircle2 size={16} className="text-green-600" />
                          )}
                          {result.cross_validation.ocr_match === false && (
                            <AlertCircle size={16} className="text-red-600" />
                          )}
                        </div>
                      </div>
                    )}

                    {result.cross_validation.payment_line_amount && (
                      <div
                        className={`
                          p-3 rounded-lg border transition-colors
                          ${result.cross_validation.amount_match === true
                            ? 'bg-green-50 border-green-200'
                            : result.cross_validation.amount_match === false
                            ? 'bg-red-50 border-red-200'
                            : 'bg-warm-bg border-warm-divider'
                          }
                        `}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex-1">
                            <div className="text-xs font-semibold text-warm-text-muted mb-1">
                              AMOUNT
                            </div>
                            <div className="text-sm font-bold text-warm-text-primary font-mono">
                              {result.cross_validation.payment_line_amount}
                            </div>
                          </div>
                          {result.cross_validation.amount_match === true && (
                            <CheckCircle2 size={16} className="text-green-600" />
                          )}
                          {result.cross_validation.amount_match === false && (
                            <AlertCircle size={16} className="text-red-600" />
                          )}
                        </div>
                      </div>
                    )}

                    {result.cross_validation.payment_line_account && (
                      <div
                        className={`
                          p-3 rounded-lg border transition-colors
                          ${(result.cross_validation.payment_line_account_type === 'bankgiro'
                              ? result.cross_validation.bankgiro_match
                              : result.cross_validation.plusgiro_match) === true
                            ? 'bg-green-50 border-green-200'
                            : (result.cross_validation.payment_line_account_type === 'bankgiro'
                                ? result.cross_validation.bankgiro_match
                                : result.cross_validation.plusgiro_match) === false
                            ? 'bg-red-50 border-red-200'
                            : 'bg-warm-bg border-warm-divider'
                          }
                        `}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex-1">
                            <div className="text-xs font-semibold text-warm-text-muted mb-1">
                              {result.cross_validation.payment_line_account_type === 'bankgiro'
                                ? 'BANKGIRO'
                                : 'PLUSGIRO'}
                            </div>
                            <div className="text-sm font-bold text-warm-text-primary font-mono">
                              {result.cross_validation.payment_line_account}
                            </div>
                          </div>
                          {(result.cross_validation.payment_line_account_type === 'bankgiro'
                            ? result.cross_validation.bankgiro_match
                            : result.cross_validation.plusgiro_match) === true && (
                            <CheckCircle2 size={16} className="text-green-600" />
                          )}
                          {(result.cross_validation.payment_line_account_type === 'bankgiro'
                            ? result.cross_validation.bankgiro_match
                            : result.cross_validation.plusgiro_match) === false && (
                            <AlertCircle size={16} className="text-red-600" />
                          )}
                        </div>
                      </div>
                    )}
                  </div>

                  {result.cross_validation.details.length > 0 && (
                    <div className="mt-4 p-3 bg-warm-bg/70 rounded-lg text-xs text-warm-text-secondary leading-relaxed border border-warm-divider">
                      {result.cross_validation.details[result.cross_validation.details.length - 1]}
                    </div>
                  )}
                </div>
              )}

              {/* VAT Summary */}
              {result.vat_summary && (
                <div className="bg-warm-card rounded-xl border border-warm-border p-6 shadow-sm">
                  <h3 className="text-lg font-bold text-warm-text-primary mb-4 flex items-center gap-2">
                    <span className="w-1 h-5 bg-warm-text-secondary rounded-full"></span>
                    VAT Summary
                  </h3>
                  <VATSummaryCard
                    vatSummary={result.vat_summary}
                    vatValidation={result.vat_validation}
                  />
                </div>
              )}

              {/* Errors */}
              {result.errors.length > 0 && (
                <div className="bg-warm-card rounded-xl border border-warm-border p-6 shadow-sm">
                  <h3 className="text-lg font-bold text-warm-text-primary mb-4 flex items-center gap-2">
                    <span className="w-1 h-5 bg-red-500 rounded-full"></span>
                    Issues
                  </h3>
                  <div className="space-y-2.5">
                    {result.errors.map((err, idx) => (
                      <div
                        key={idx}
                        className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg flex items-start gap-3"
                      >
                        <AlertCircle size={16} className="text-yellow-600 flex-shrink-0 mt-0.5" />
                        <span className="text-xs text-yellow-800 leading-relaxed">{err}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
