import { useState } from 'react'
import Badge from '../UI/Badge'
import { formatDate } from '../../utils/dateHelpers'
import ContextMenu from '../UI/ContextMenu'
import { updateDeliverable, deleteDeliverable } from '../../api/deliverables'
import useProjectStore from '../../store/useProjectStore'
import { STATUS_OPTIONS } from '../../utils/statusHelpers'

export default function DeliverableCard({ deliverable, isActive, index, projectColor, onSelect, onEdit }) {
  const { updateDeliverable: storeUpdate, removeDeliverable } = useProjectStore()
  const [ctxMenu, setCtxMenu] = useState(null)

  const handleContextMenu = (e) => {
    e.preventDefault()
    e.stopPropagation()
    setCtxMenu({
      x: e.clientX, y: e.clientY,
      items: [
        { icon: '✎', label: 'Edit Deliverable', highlight: true, action: () => onEdit(deliverable) },
        { separator: true },
        ...STATUS_OPTIONS.map(s => ({
          icon: s.value === deliverable.status ? '●' : '○',
          label: `Mark ${s.label}`,
          action: async () => {
            storeUpdate(await updateDeliverable(deliverable.id, { status: s.value }))
          },
        })),
        { separator: true },
        {
          icon: '✕', label: 'Delete Deliverable', danger: true,
          action: async () => {
            if (window.confirm(`Delete "${deliverable.title}"?`)) {
              await deleteDeliverable(deliverable.id)
              removeDeliverable(deliverable.id)
            }
          },
        },
      ],
    })
  }

  return (
    <>
      <div
        onClick={() => onSelect(deliverable.id)}
        onDoubleClick={(e) => { e.stopPropagation(); onEdit(deliverable) }}
        onContextMenu={handleContextMenu}
        title="Click: Select · Double-click: Edit · Right-click: Menu"
        className={`relative flex flex-col gap-2 rounded-xl border p-4 min-w-[190px] max-w-[230px] flex-shrink-0 cursor-pointer
          transition-all duration-200 select-none mt-4
          ${isActive
            ? 'border-gold bg-surface-elevated shadow-gold scale-105 ring-2 ring-gold/30'
            : 'border-surface-border bg-surface hover:border-gold/40 hover:bg-surface-elevated/60'
          }`}
      >
        {isActive && (
          <div className="absolute -top-5 left-1/2 -translate-x-1/2 bg-gold text-surface text-[9px] font-black px-2.5 py-0.5 rounded-full tracking-widest uppercase whitespace-nowrap">
            Selected
          </div>
        )}
        <div className="flex items-center gap-1.5">
          <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ backgroundColor: projectColor }} />
          <span className={`text-[10px] font-semibold uppercase tracking-widest ${isActive ? 'text-gold' : 'text-text-muted/60'}`}>
            Deliverable {index + 1}
          </span>
        </div>
        <p className={`text-sm font-semibold leading-snug ${isActive ? 'text-text-primary' : 'text-text-muted'}`}>
          {deliverable.title}
        </p>
        <p className={`text-xs font-mono ${isActive ? 'text-gold' : 'text-text-muted/50'}`}>
          {formatDate(deliverable.due_date)}
        </p>
        <Badge status={deliverable.status} />
        {isActive && (
          <button
            onClick={(e) => { e.stopPropagation(); onEdit(deliverable) }}
            className="mt-1 text-[10px] text-gold/70 hover:text-gold border border-gold/20 hover:border-gold/50 rounded px-2 py-0.5 transition-all text-center"
          >
            Edit
          </button>
        )}
      </div>

      {ctxMenu && (
        <ContextMenu x={ctxMenu.x} y={ctxMenu.y} items={ctxMenu.items} onClose={() => setCtxMenu(null)} />
      )}
    </>
  )
}
