import { useState, useRef, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { Send, Paperclip, Terminal, Loader2, X, RotateCcw, ImagePlus, Globe, Mail, Lock, Printer, Shield } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { cn } from '@/lib/utils'
import { uploadsApi } from '@/api/uploads'
import { toast } from '@/lib/toast'
import type { PendingUpload } from '@/types/upload'

const SUGGESTIONS: { icon: LucideIcon; label: string }[] = [
  { icon: Globe, label: 'VPN not connecting' },
  { icon: Mail, label: 'Outlook not syncing' },
  { icon: Lock, label: 'User locked out' },
  { icon: Globe, label: 'Slow internet' },
  { icon: Printer, label: 'Printer issues' },
  { icon: Shield, label: 'MFA problems' },
]

const ACCEPTED_FILE_TYPES = 'image/png,image/jpeg,image/gif,image/webp,.txt,.log,.csv,.pdf,.docx'

export function StartSessionInput() {
  const [value, setValue] = useState('')
  const [showLogs, setShowLogs] = useState(false)
  const [logContent, setLogContent] = useState('')
  const [pendingUploads, setPendingUploads] = useState<PendingUpload[]>([])
  const [isDragOver, setIsDragOver] = useState(false)
  const navigate = useNavigate()
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const dragCounterRef = useRef(0)

  useEffect(() => { textareaRef.current?.focus() }, [])

  // Auto-grow textarea
  useEffect(() => {
    const el = textareaRef.current
    if (!el) return
    el.style.height = 'auto'
    el.style.height = `${Math.min(el.scrollHeight, 200)}px`
  }, [value])

  const handleSubmit = () => {
    const trimmed = value.trim()
    if (!trimmed) return
    const state: Record<string, unknown> = { prefill: trimmed }
    if (logContent.trim()) {
      state.logs = logContent.trim()
    }
    const completedUploadIds = pendingUploads
      .filter((u) => u.status === 'done' && u.result?.id)
      .map((u) => u.result!.id)
    if (completedUploadIds.length > 0) {
      state.uploadIds = completedUploadIds
    }
    navigate('/pilot', { state })
  }

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSubmit()
    }
  }

  const handleSuggestionClick = (suggestion: string) => {
    navigate('/pilot', { state: { prefill: suggestion } })
  }

  // ── File handling ──────────────────────────────

  const processFiles = useCallback((files: File[]) => {
    if (files.length === 0) return

    const newUploads: PendingUpload[] = files.map((file) => ({
      id: crypto.randomUUID(),
      file,
      preview: file.type.startsWith('image/') ? URL.createObjectURL(file) : '',
      status: 'uploading' as const,
    }))

    setPendingUploads((prev) => [...prev, ...newUploads])

    newUploads.forEach((upload) => {
      uploadsApi
        .upload(upload.file)
        .then((result) => {
          setPendingUploads((prev) =>
            prev.map((u) => u.id === upload.id ? { ...u, status: 'done' as const, result } : u)
          )
        })
        .catch((err) => {
          const is503 = err?.response?.status === 503
          const errorMsg = is503
            ? 'File uploads not available'
            : err?.message || 'Upload failed'
          if (is503) {
            toast.warning('Image attachments are not available yet — describe the issue in text instead')
          } else {
            toast.error(`Upload failed: ${errorMsg}`)
          }
          setPendingUploads((prev) => prev.filter((u) => u.id !== upload.id))
        })
    })
  }, [])

  const handlePaste = useCallback((e: React.ClipboardEvent<HTMLTextAreaElement>) => {
    const items = e.clipboardData?.items
    if (!items) return
    const imageFiles: File[] = []
    for (let i = 0; i < items.length; i++) {
      if (items[i].type.startsWith('image/')) {
        const file = items[i].getAsFile()
        if (file) imageFiles.push(file)
      }
    }
    if (imageFiles.length > 0) {
      e.preventDefault()
      processFiles(imageFiles)
    }
  }, [processFiles])

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    e.dataTransfer.dropEffect = 'copy'
  }, [])

  const handleDragEnter = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    dragCounterRef.current++
    if (dragCounterRef.current === 1) setIsDragOver(true)
  }, [])

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    dragCounterRef.current--
    if (dragCounterRef.current === 0) setIsDragOver(false)
  }, [])

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault()
    dragCounterRef.current = 0
    setIsDragOver(false)
    processFiles(Array.from(e.dataTransfer.files))
  }, [processFiles])

  const handleFileSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      processFiles(Array.from(e.target.files))
      e.target.value = '' // reset so same file can be re-selected
    }
  }, [processFiles])

  const handleRemoveUpload = useCallback((uploadId: string) => {
    setPendingUploads((prev) => {
      const toRemove = prev.find((u) => u.id === uploadId)
      if (toRemove?.preview) URL.revokeObjectURL(toRemove.preview)
      return prev.filter((u) => u.id !== uploadId)
    })
  }, [])

  const retryUpload = useCallback((uploadId: string) => {
    const upload = pendingUploads.find((u) => u.id === uploadId)
    if (!upload) return
    setPendingUploads((prev) =>
      prev.map((u) => u.id === uploadId ? { ...u, status: 'uploading' as const, error: undefined } : u)
    )
    uploadsApi
      .upload(upload.file)
      .then((result) => {
        setPendingUploads((prev) =>
          prev.map((u) => u.id === uploadId ? { ...u, status: 'done' as const, result } : u)
        )
      })
      .catch((err) => {
        setPendingUploads((prev) =>
          prev.map((u) => u.id === uploadId ? { ...u, status: 'error' as const, error: err?.message || 'Upload failed' } : u)
        )
      })
  }, [pendingUploads])

  // Cleanup blob URLs on unmount
  useEffect(() => {
    return () => {
      pendingUploads.forEach((u) => { if (u.preview) URL.revokeObjectURL(u.preview) })
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const hasContent = value.trim().length > 0

  return (
    <div
      className="w-full"
      onDragOver={handleDragOver}
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
    >
      {/* Main input area */}
      <div className={cn(
        'relative rounded-2xl border bg-card transition-all',
        isDragOver ? 'border-primary/50 bg-primary/5' : 'border-border',
        'focus-within:border-[rgba(96,165,250,0.25)] focus-within:ring-1 focus-within:ring-[rgba(96,165,250,0.1)]'
      )}>
        {/* Drag overlay */}
        {isDragOver && (
          <div className="absolute inset-0 z-10 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary/50 bg-primary/5 pointer-events-none">
            <div className="flex items-center gap-2 text-sm text-primary">
              <ImagePlus size={18} />
              Drop files to attach
            </div>
          </div>
        )}

        {/* Textarea */}
        <textarea
          ref={textareaRef}
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={handleKeyDown}
          onPaste={handlePaste}
          placeholder="Describe the issue, paste an error message, or drop a screenshot..."
          rows={3}
          className="w-full resize-none bg-transparent px-5 pt-5 pb-2 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none"
          style={{ minHeight: '80px', maxHeight: '200px' }}
        />

        {/* Thumbnail strip */}
        {pendingUploads.length > 0 && (
          <div className="flex gap-2 flex-wrap px-5 pb-2">
            {pendingUploads.map((upload) => (
              <div key={upload.id} className="relative w-14 h-14 rounded-lg overflow-hidden border border-border bg-background">
                {upload.preview ? (
                  <img src={upload.preview} alt="" className="w-full h-full object-cover" />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-[0.5rem] text-muted-foreground px-1 text-center">
                    {upload.file.name.split('.').pop()?.toUpperCase()}
                  </div>
                )}
                {upload.status === 'uploading' && (
                  <div className="absolute inset-0 bg-background/60 flex items-center justify-center">
                    <Loader2 size={14} className="animate-spin text-primary" />
                  </div>
                )}
                {upload.status === 'done' && (
                  <button
                    type="button"
                    onClick={() => handleRemoveUpload(upload.id)}
                    className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-background border border-border flex items-center justify-center hover:bg-rose-500/20 transition-colors"
                  >
                    <X size={8} className="text-muted-foreground" />
                  </button>
                )}
                {upload.status === 'error' && (
                  <div
                    className="absolute inset-0 bg-rose-500/20 border-2 border-rose-500 flex items-center justify-center cursor-pointer"
                    onClick={() => retryUpload(upload.id)}
                  >
                    <RotateCcw size={12} className="text-rose-500" />
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Logs textarea (expandable) */}
        {showLogs && (
          <div className="px-5 pb-2">
            <div className="flex items-center justify-between mb-1">
              <span className="text-[0.625rem] uppercase tracking-wide text-muted-foreground font-sans">Paste logs or error output</span>
              <button type="button" onClick={() => { setShowLogs(false); setLogContent('') }} className="text-muted-foreground hover:text-foreground">
                <X size={14} />
              </button>
            </div>
            <textarea
              value={logContent}
              onChange={(e) => setLogContent(e.target.value)}
              placeholder="Paste event viewer logs, error messages, PowerShell output..."
              rows={4}
              className="w-full resize-none rounded-lg border border-border bg-background p-3 font-mono text-xs text-foreground placeholder:text-muted-foreground focus:border-[rgba(96,165,250,0.3)] focus:outline-none"
            />
          </div>
        )}

        {/* Bottom toolbar */}
        <div className="flex items-center justify-between px-4 py-2.5 border-t border-border/50">
          <div className="flex items-center gap-1">
            {/* Attach button */}
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept={ACCEPTED_FILE_TYPES}
              onChange={handleFileSelect}
              className="hidden"
            />
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors"
              title="Attach files"
            >
              <Paperclip size={14} />
              <span className="hidden sm:inline">Attach</span>
            </button>

            {/* Paste Logs button */}
            {!showLogs && (
              <button
                type="button"
                onClick={() => setShowLogs(true)}
                className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors"
                title="Paste logs or error output"
              >
                <Terminal size={14} />
                <span className="hidden sm:inline">Paste Logs</span>
              </button>
            )}
          </div>

          {/* Send button */}
          <button
            type="button"
            onClick={handleSubmit}
            disabled={!hasContent}
            className={cn(
              'flex h-8 w-8 items-center justify-center rounded-lg transition-all',
              hasContent
                ? 'bg-primary text-white hover:brightness-110 active:scale-95'
                : 'bg-secondary text-muted-foreground cursor-not-allowed'
            )}
            title="Start session"
          >
            <Send size={15} />
          </button>
        </div>
      </div>

      {/* Suggestion chips */}
      <div className="flex flex-wrap gap-2 mt-4">
        {SUGGESTIONS.map(({ icon: Icon, label }) => (
          <button
            key={label}
            type="button"
            onClick={() => handleSuggestionClick(label)}
            className="group flex items-center gap-1.5 rounded-md border border-border bg-card px-3 py-1.5 text-xs text-muted-foreground transition-all hover:border-[var(--color-border-hover)] hover:bg-[var(--color-bg-elevated)] hover:text-foreground active:scale-[0.97]"
          >
            <Icon size={11} className="text-muted shrink-0 group-hover:text-[#60a5fa] transition-colors" />
            {label}
          </button>
        ))}
      </div>
    </div>
  )
}
