import { useState, useRef, useCallback, useEffect } from 'react'
import { Send, Paperclip, Terminal, Loader2, X, RotateCcw, ImagePlus } from 'lucide-react'
import { cn } from '@/lib/utils'
import { uploadsApi } from '@/api/uploads'
import { toast } from '@/lib/toast'
import type { StepResponseRequest } from '@/types/ai-session'
import type { PendingUpload } from '@/types/upload'

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

interface FlowPilotMessageBarProps {
  onRespond: (response: StepResponseRequest) => void
  disabled?: boolean
  isProcessing?: boolean
}

export function FlowPilotMessageBar({ onRespond, disabled = false, isProcessing = false }: FlowPilotMessageBarProps) {
  const [message, setMessage] = useState('')
  const [showLogs, setShowLogs] = useState(false)
  const [logContent, setLogContent] = useState('')
  const [pendingUploads, setPendingUploads] = useState<PendingUpload[]>([])
  const [isDragOver, setIsDragOver] = useState(false)
  const textareaRef = useRef<HTMLTextAreaElement>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const dragCounterRef = useRef(0)

  const isDisabled = disabled || isProcessing

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

  const handleSubmit = useCallback(() => {
    const trimmed = message.trim()
    if (!trimmed || isDisabled) return

    let fullMessage = trimmed
    if (logContent.trim()) {
      fullMessage += `\n\n--- Logs ---\n${logContent.trim()}`
    }

    onRespond({ free_text_input: fullMessage })
    setMessage('')
    setLogContent('')
    setShowLogs(false)
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto'
    }
  }, [message, logContent, isDisabled, onRespond])

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

  // ── 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
          if (is503) {
            toast.warning('Image attachments are not available yet — describe the issue in text instead')
          } else {
            toast.error(`Upload failed: ${err?.message || 'Unknown error'}`)
          }
          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 = ''
    }
  }, [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 = message.trim().length > 0

  return (
    <div
      className="fixed bottom-0 right-0 lg:right-72 z-40 px-3 sm:px-6 lg:px-8 pb-3"
      style={{ left: 'var(--sidebar-w, 0px)' }}
      onDragOver={handleDragOver}
      onDragEnter={handleDragEnter}
      onDragLeave={handleDragLeave}
      onDrop={handleDrop}
    >
      <div
        className={cn(
          'relative rounded-xl border transition-all',
          isDisabled
            ? 'border-border/50 opacity-50'
            : isDragOver
              ? 'border-primary/50 bg-primary/5'
              : 'border-border focus-within:border-[rgba(96,165,250,0.3)] focus-within:ring-1 focus-within:ring-primary/20'
        )}
        style={{ background: 'var(--color-bg-card)' }}
      >
        {/* Drag overlay */}
        {isDragOver && (
          <div className="absolute inset-0 z-10 flex items-center justify-center rounded-xl 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={message}
          onChange={(e) => setMessage(e.target.value)}
          onKeyDown={handleKeyDown}
          onPaste={handlePaste}
          placeholder={isProcessing ? 'FlowPilot is thinking...' : 'Type a message, paste a screenshot, or drag a file...'}
          disabled={isDisabled}
          rows={1}
          className="w-full resize-none bg-transparent px-4 pt-3 pb-1 text-sm text-foreground placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed"
          style={{ minHeight: '40px', maxHeight: '150px' }}
        />

        {/* Thumbnail strip */}
        {pendingUploads.length > 0 && (
          <div className="flex gap-2 flex-wrap px-4 pb-1">
            {pendingUploads.map((upload) => (
              <div key={upload.id} className="relative w-12 h-12 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={12} 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={10} className="text-rose-500" />
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        {/* Logs textarea (expandable) */}
        {showLogs && (
          <div className="px-4 pb-1">
            <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={3}
              className="w-full resize-none rounded-lg border border-border bg-background p-2 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-3 py-1.5 border-t border-border/50">
          <div className="flex items-center gap-0.5">
            {/* Attach button */}
            <input
              ref={fileInputRef}
              type="file"
              multiple
              accept={ACCEPTED_FILE_TYPES}
              onChange={handleFileSelect}
              className="hidden"
            />
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              disabled={isDisabled}
              className="flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-xs text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors disabled:opacity-40"
              title="Attach files (images, logs, docs)"
            >
              <Paperclip size={14} />
              <span className="hidden sm:inline">Attach</span>
            </button>

            {/* Paste Logs button */}
            {!showLogs && (
              <button
                type="button"
                onClick={() => setShowLogs(true)}
                disabled={isDisabled}
                className="flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-xs text-muted-foreground hover:text-foreground hover:bg-secondary transition-colors disabled:opacity-40"
                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={isDisabled || !hasContent}
            aria-label="Send message"
            className={cn(
              'flex h-8 w-8 items-center justify-center rounded-lg transition-all',
              hasContent && !isDisabled
                ? 'bg-primary text-white hover:brightness-110 active:scale-95'
                : 'bg-secondary text-muted-foreground cursor-not-allowed'
            )}
          >
            <Send size={15} />
          </button>
        </div>
      </div>
    </div>
  )
}
