'use client'

import { useState } from 'react'
import { ChevronDown, ChevronRight, Plus, Trash2, GripVertical } from 'lucide-react'

interface CardListProps {
  items: Record<string, unknown>[]
  onChange: (items: Record<string, unknown>[]) => void
  titleKey: string
  subtitleKey?: string
  renderCard: (item: Record<string, unknown>, update: (key: string, value: unknown) => void) => React.ReactNode
  newItemTemplate?: Record<string, unknown>
  addLabel?: string
}

export default function CardList({
  items, onChange, titleKey, subtitleKey, renderCard, newItemTemplate, addLabel,
}: CardListProps) {
  const [expandedIdx, setExpandedIdx] = useState<number | null>(null)

  function updateItem(idx: number, key: string, value: unknown) {
    onChange(items.map((item, i) => i === idx ? { ...item, [key]: value } : item))
  }

  function addItem() {
    const newItem = newItemTemplate || (() => {
      const template: Record<string, unknown> = {}
      if (items.length > 0) {
        Object.keys(items[0]).forEach(k => {
          const sample = items[0][k]
          template[k] = Array.isArray(sample) ? [] : typeof sample === 'number' ? 0 : typeof sample === 'boolean' ? false : ''
        })
      }
      if ('sort_order' in template) template.sort_order = items.length
      return template
    })()
    onChange([...items, newItem])
    setExpandedIdx(items.length)
  }

  function removeItem(idx: number) {
    if (!confirm('Remove this item?')) return
    onChange(items.filter((_, i) => i !== idx))
    if (expandedIdx === idx) setExpandedIdx(null)
  }

  function moveUp(idx: number) {
    if (idx === 0) return
    const copy = [...items]
    ;[copy[idx - 1], copy[idx]] = [copy[idx], copy[idx - 1]]
    onChange(copy)
    setExpandedIdx(idx - 1)
  }

  function moveDown(idx: number) {
    if (idx >= items.length - 1) return
    const copy = [...items]
    ;[copy[idx], copy[idx + 1]] = [copy[idx + 1], copy[idx]]
    onChange(copy)
    setExpandedIdx(idx + 1)
  }

  return (
    <div className="space-y-2">
      {items.map((item, idx) => {
        const isExpanded = expandedIdx === idx
        const title = String(item[titleKey] || `Item ${idx + 1}`)
        const subtitle = subtitleKey ? String(item[subtitleKey] || '') : ''

        return (
          <div key={idx} className="border border-white/[0.06] rounded-xl overflow-hidden">
            <button
              onClick={() => setExpandedIdx(isExpanded ? null : idx)}
              className="w-full flex items-center gap-3 px-4 py-3 hover:bg-white/[0.02] text-left"
            >
              <div className="flex items-center gap-1 text-white/30">
                <button
                  onClick={e => { e.stopPropagation(); moveUp(idx) }}
                  className="hover:text-white/60 p-0.5"
                  title="Move up"
                >
                  <GripVertical className="w-3 h-3" />
                </button>
              </div>
              {isExpanded ? <ChevronDown className="w-4 h-4 text-white/40" /> : <ChevronRight className="w-4 h-4 text-white/40" />}
              <div className="flex-1 min-w-0">
                <span className="text-sm text-white/90 font-medium truncate block">{title}</span>
                {subtitle && <span className="text-xs text-white/40 truncate block">{subtitle}</span>}
              </div>
              <span className="text-[9px] text-white/30 font-mono">#{idx + 1}</span>
              <button
                onClick={e => { e.stopPropagation(); removeItem(idx) }}
                className="text-white/30 hover:text-rose-400 p-1"
                title="Remove"
              >
                <Trash2 className="w-3.5 h-3.5" />
              </button>
            </button>
            {isExpanded && (
              <div className="px-4 pb-4 pt-1 border-t border-white/[0.04] space-y-4">
                {renderCard(item, (key, value) => updateItem(idx, key, value))}
              </div>
            )}
          </div>
        )
      })}
      <button
        onClick={addItem}
        className="w-full flex items-center justify-center gap-2 py-2.5 text-xs text-white/50 hover:text-white border border-dashed border-white/[0.1] hover:border-white/[0.2] rounded-xl transition-colors"
      >
        <Plus className="w-3.5 h-3.5" /> {addLabel || 'Add item'}
      </button>
    </div>
  )
}
