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: '\u270e', label: 'Edit Deliverable', highlight: true, action: () => onEdit(deliverable) },
        { separator: true },
        ...STATUS_OPTIONS.map(s => ({
          icon: s.value === deliverable.status ? '\u25cf' : '\u25cb',
          label: `Mark ${s.label}`,
          action: async () => {
            storeUpdate(await updateDeliverable(deliverable.id, { status: s.value }))
          },
        })),
        { separator: true },
        {
          icon: '\u2715',
          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 text-[9px] font-bold tracking-widest uppercase text-gold/80 whitespace-nowrap">
            Selected
          </div>
        )}

        <div className="text-[10px] text-text-muted/50 font-mono">Deliverable {index + 1}</div>
        <div className="text-sm font-semibold text-text-primary leading-snug line-clamp-3">{deliverable.title}</div>
        <div className="text-xs text-text-muted/70 mt-auto pt-1">{formatDate(deliverable.due_date)}</div>
        <Badge status={deliverable.status} />
      </div>

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