import { useState } from 'react'
import type { Section, Product, Drone } from '../types'
import { ItemCard } from './ItemCard'
import { AddItemDialog } from './AddItemDialog'
import { cacheItemImages } from '../utils/imageCache'

interface Props {
  section: Section
  onRemoveItem: (itemId: string) => void
  onAddItem: (item: Product | Drone) => void
  onEditItem: (item: Product | Drone) => void
  onRemoveSection: () => void
  onRenameSection: (label: string) => void
  onDragStart: () => void
  onDragOver: (e: React.DragEvent) => void
  onDrop: () => void
  onDragEnd: () => void
  isDragging: boolean
  isDragOver: boolean
}

export function SectionBlock({ section, onRemoveItem, onAddItem, onEditItem, onRemoveSection, onRenameSection, onDragStart, onDragOver, onDrop, onDragEnd, isDragging, isDragOver }: Props) {
  const [showAdd, setShowAdd] = useState(false)
  const [editingItem, setEditingItem] = useState<Product | Drone | null>(null)
  const [editing, setEditing] = useState(false)
  const [labelInput, setLabelInput] = useState(section.label)
  const [pasteError, setPasteError] = useState<string | null>(null)

  function submitRename(e: React.FormEvent) {
    e.preventDefault()
    if (labelInput.trim()) onRenameSection(labelInput.trim())
    setEditing(false)
  }

  function copySection() {
    const json = JSON.stringify(section.items, null, 2)
    navigator.clipboard.writeText(json)
  }

  async function pasteItems() {
    setPasteError(null)
    try {
      const text = await navigator.clipboard.readText()
      const parsed = JSON.parse(text)
      const items: (Product | Drone)[] = Array.isArray(parsed) ? parsed : [parsed]
      for (const item of items) {
        if (!item.name) continue
        const cached = await cacheItemImages({ ...structuredClone(item), id: crypto.randomUUID() })
        onAddItem(cached)
      }
    } catch {
      setPasteError('Clipboard does not contain valid item JSON.')
      setTimeout(() => setPasteError(null), 3000)
    }
  }

  return (
    <div
      onDragOver={onDragOver}
      onDrop={onDrop}
      className="flex flex-col gap-3 rounded-lg border p-4 transition-opacity"
      style={{
        background: 'var(--color-bg1)',
        borderColor: isDragOver ? 'var(--color-cyan)' : 'var(--color-bg3)',
        opacity: isDragging ? 0.4 : 1,
      }}
    >
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span
            draggable
            onDragStart={onDragStart}
            onDragEnd={onDragEnd}
            className="cursor-grab select-none text-base leading-none"
            style={{ color: 'var(--color-bg3)' }}
            title="Drag to reorder"
          >⠿</span>
          {editing ? (
            <form onSubmit={submitRename} className="flex items-center gap-1">
              <input
                autoFocus
                value={labelInput}
                onChange={e => setLabelInput(e.target.value)}
                onBlur={submitRename}
                className="rounded border px-2 py-0.5 text-sm outline-none"
                style={{ background: 'var(--color-bg2)', color: 'var(--color-fg)', borderColor: 'var(--color-bg3)' }}
              />
            </form>
          ) : (
            <button
              className="font-medium"
              style={{ color: 'var(--color-fg)' }}
              onClick={() => { setLabelInput(section.label); setEditing(true) }}
              title="Click to rename"
            >
              {section.label}
            </button>
          )}
          {section.required && (
            <span className="rounded px-1.5 py-0.5 text-xs" style={{ background: 'var(--color-bg-red)', color: 'var(--color-red)' }}>
              required
            </span>
          )}
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={copySection}
            className="rounded px-2 py-1 text-xs"
            style={{ background: 'var(--color-bg2)', color: 'var(--color-grey)' }}
            title="Copy section items to clipboard"
          >
            Copy
          </button>
          <button
            onClick={pasteItems}
            className="rounded px-2 py-1 text-xs"
            style={{ background: 'var(--color-bg2)', color: 'var(--color-grey)' }}
            title="Paste items from clipboard"
          >
            Paste
          </button>
          <button
            onClick={() => setShowAdd(true)}
            className="rounded px-2 py-1 text-xs"
            style={{ background: 'var(--color-bg2)', color: 'var(--color-cyan)' }}
          >
            + Add item
          </button>
          <button
            onClick={onRemoveSection}
            className="text-xs"
            style={{ color: 'var(--color-grey)' }}
            title="Remove section"
          >
            ✕
          </button>
        </div>
      </div>

      {pasteError && (
        <p className="text-xs" style={{ color: 'var(--color-red)' }}>{pasteError}</p>
      )}

      {/* Items */}
      {section.items.length > 0 ? (
        <div className="flex flex-col gap-2">
          {section.items.map(item => (
            <ItemCard
              key={item.id}
              item={item}
              onEdit={() => setEditingItem(item)}
              onRemove={() => onRemoveItem(item.id)}
            />
          ))}
        </div>
      ) : (
        <p className="py-4 text-center text-sm" style={{ color: 'var(--color-grey)' }}>
          No items yet — add one above
        </p>
      )}

      {showAdd && (
        <AddItemDialog
          isDroneSection={section.id === 'drone'}
          onSubmit={onAddItem}
          onClose={() => setShowAdd(false)}
        />
      )}

      {editingItem && (
        <AddItemDialog
          isDroneSection={section.id === 'drone'}
          initialItem={editingItem}
          onSubmit={item => { onEditItem(item); setEditingItem(null) }}
          onClose={() => setEditingItem(null)}
        />
      )}
    </div>
  )
}
