import { useState, useEffect, useRef } from 'react'
import { FileUp, X, AlertTriangle } from 'lucide-react'
import { flowTransferApi } from '@/api/flowTransfer'
import { parseRFFlowFile, RFFlowParseError } from '@/lib/rfflowParser'
import type { RFFlowFile } from '@/types'
import { toast } from '@/lib/toast'
import { cn } from '@/lib/utils'
import { useNavigate } from 'react-router-dom'
import { getTreeEditorPath } from '@/lib/routing'
import { Button } from '@/components/ui/Button'

interface ImportFlowModalProps {
  onClose: () => void
}

const TYPE_LABELS: Record<string, string> = {
  troubleshooting: 'Troubleshooting',
  procedural: 'Project',
  maintenance: 'Maintenance',
}

export function ImportFlowModal({ onClose }: ImportFlowModalProps) {
  const navigate = useNavigate()
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [step, setStep] = useState<'pick' | 'preview'>('pick')
  const [parsed, setParsed] = useState<RFFlowFile | null>(null)
  const [nameOverride, setNameOverride] = useState('')
  const [parseError, setParseError] = useState<string | null>(null)
  const [isImporting, setIsImporting] = useState(false)
  const [isDragging, setIsDragging] = useState(false)

  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [onClose])

  const handleFile = async (file: File) => {
    setParseError(null)

    if (!file.name.endsWith('.rfflow')) {
      setParseError('File must have .rfflow extension')
      return
    }

    try {
      const text = await file.text()
      const data = parseRFFlowFile(text)
      setParsed(data)
      setNameOverride(data.flow.name)
      setStep('preview')
    } catch (err) {
      if (err instanceof RFFlowParseError) {
        setParseError(err.message)
      } else {
        setParseError('Failed to read file')
      }
    }
  }

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) handleFile(file)
  }

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

  const handleImport = async () => {
    if (!parsed) return
    setIsImporting(true)
    try {
      const overrideName = nameOverride.trim() !== parsed.flow.name ? nameOverride.trim() : undefined
      const result = await flowTransferApi.importFlow(parsed, overrideName)
      toast.success(`Imported "${result.name}" as draft`)
      onClose()
      navigate(getTreeEditorPath(result.tree_id, result.tree_type))
    } catch (err) {
      console.error('Import failed:', err)
      toast.error('Failed to import flow')
    } finally {
      setIsImporting(false)
    }
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md rounded-xl border border-border bg-card shadow-xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-border px-5 py-4">
          <div className="flex items-center gap-2">
            <FileUp className="h-4 w-4 text-muted-foreground" />
            <h2 className="text-sm font-semibold text-foreground">Import Flow</h2>
          </div>
          <button
            onClick={onClose}
            aria-label="Close"
            className="rounded-md p-1 text-muted-foreground hover:bg-accent hover:text-foreground"
          >
            <X className="h-4 w-4" />
          </button>
        </div>

        {/* Body */}
        <div className="px-5 py-4">
          {step === 'pick' && (
            <div className="space-y-3">
              <div
                className={cn(
                  'flex flex-col items-center justify-center rounded-lg border-2 border-dashed px-4 py-8 text-center transition-colors cursor-pointer',
                  isDragging
                    ? 'border-primary/50 bg-primary/5'
                    : 'border-border hover:border-border-hover'
                )}
                onClick={() => fileInputRef.current?.click()}
                onDragOver={(e) => { e.preventDefault(); setIsDragging(true) }}
                onDragLeave={() => setIsDragging(false)}
                onDrop={handleDrop}
              >
                <FileUp className="mb-2 h-8 w-8 text-muted-foreground" />
                <p className="text-sm text-foreground">
                  Drop .rfflow file here or <span className="text-primary cursor-pointer">browse</span>
                </p>
                <p className="mt-1 text-xs text-muted-foreground">JSON format</p>
              </div>
              <input
                ref={fileInputRef}
                type="file"
                accept=".rfflow"
                onChange={handleFileChange}
                className="hidden"
              />
              {parseError && (
                <div className="flex items-start gap-2 rounded-lg border border-rose-500/20 bg-rose-500/5 px-3 py-2">
                  <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-rose-400" />
                  <p className="text-xs text-rose-400">{parseError}</p>
                </div>
              )}
            </div>
          )}

          {step === 'preview' && parsed && (
            <div className="space-y-4">
              {/* Editable name */}
              <div>
                <label htmlFor="import-name" className="mb-1.5 block text-xs font-medium text-muted-foreground">
                  Name
                </label>
                <input
                  id="import-name"
                  type="text"
                  value={nameOverride}
                  onChange={(e) => setNameOverride(e.target.value)}
                  maxLength={255}
                  className={cn(
                    'w-full rounded-lg border border-border bg-card px-3 py-2 text-sm text-foreground',
                    'placeholder:text-muted-foreground focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20'
                  )}
                />
              </div>

              {/* Flow info */}
              <div className="space-y-2 text-xs">
                <div className="flex items-center gap-2">
                  <span className="text-muted-foreground">Type:</span>
                  <span className="rounded bg-accent-dim px-2 py-0.5 font-sans text-xs text-primary">
                    {TYPE_LABELS[parsed.flow.tree_type] || parsed.flow.tree_type}
                  </span>
                </div>

                {parsed.flow.description && (
                  <div>
                    <span className="text-muted-foreground">Description:</span>
                    <p className="mt-0.5 text-foreground line-clamp-2">{parsed.flow.description}</p>
                  </div>
                )}

                {parsed.flow.category && (
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">Category:</span>
                    <span className="text-foreground">{parsed.flow.category.name}</span>
                  </div>
                )}

                {parsed.flow.tags.length > 0 && (
                  <div className="flex flex-wrap items-center gap-1.5">
                    <span className="text-muted-foreground">Tags:</span>
                    {parsed.flow.tags.map((tag) => (
                      <span key={tag} className="rounded bg-card border border-border px-2 py-0.5 font-sans text-xs text-foreground">
                        {tag}
                      </span>
                    ))}
                  </div>
                )}

                {parsed.flow.author_name && (
                  <div className="flex items-center gap-2">
                    <span className="text-muted-foreground">Original author:</span>
                    <span className="text-foreground">{parsed.flow.author_name}</span>
                  </div>
                )}

                <div className="flex items-center gap-2">
                  <span className="text-muted-foreground">Version:</span>
                  <span className="text-foreground">v{parsed.flow.version}</span>
                </div>
              </div>

              <p className="text-xs text-muted-foreground">
                Flow will be imported as a <span className="font-medium text-foreground">draft</span>.
              </p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-2 border-t border-border px-5 py-3">
          {step === 'preview' && (
            <Button
              variant="secondary"
              onClick={() => { setStep('pick'); setParsed(null); setParseError(null) }}
              className="mr-auto"
            >
              Back
            </Button>
          )}
          <Button variant="secondary" onClick={onClose}>
            Cancel
          </Button>
          {step === 'preview' && (
            <Button
              onClick={handleImport}
              disabled={!nameOverride.trim()}
              loading={isImporting}
            >
              <FileUp className="h-4 w-4" />
              Import as Draft
            </Button>
          )}
        </div>
      </div>
    </div>
  )
}
