"use client";

import { useState, type DragEvent } from "react";
import type { Article } from "@/src/types/article";
import type { TipoMovimento } from "@/src/types/movimento";

interface ArticleCardProps {
  article: Article;
  giacenzaMagazzino?: number;
  magazzinoNome?: string;
  onEdit: (article: Article) => void;
  onDelete: (article: Article) => void;
  onMovimento?: (article: Article, tipo: TipoMovimento) => void;
  draggable?: boolean;
}

export default function ArticleCard({ 
  article, 
  giacenzaMagazzino,
  magazzinoNome,
  onEdit, 
  onDelete,
  onMovimento,
  draggable = true,
}: ArticleCardProps) {
  const [deleting, setDeleting] = useState(false);
  const [isDragging, setIsDragging] = useState(false);

  const isSottoScorta = article.quantita < article.quantita_minima;
  const disponibile = article.quantita - article.assegnata_macchine;
  const hasGiacenzaMagazzino = giacenzaMagazzino !== undefined;
  const canDrag = draggable && disponibile > 0;

  const handleDelete = async () => {
    if (!confirm(`Eliminare "${article.descrizione}"?`)) return;
    
    setDeleting(true);
    try {
      const res = await fetch(`/api/articoli/${article.id}`, { method: "DELETE" });
      if (!res.ok) throw new Error("Errore durante l'eliminazione");
      onDelete(article);
    } catch (error) {
      alert(error instanceof Error ? error.message : "Errore");
    } finally {
      setDeleting(false);
    }
  };

  const handleDragStart = (e: DragEvent<HTMLDivElement>) => {
    if (!canDrag) {
      e.preventDefault();
      return;
    }
    setIsDragging(true);
    e.dataTransfer.setData("application/json", JSON.stringify({
      id: article.id,
      descrizione: article.descrizione,
      codice: article.codice,
      barcode: article.barcode,
      quantita_residua: disponibile,
      famiglia: article.famiglia,
    }));
    e.dataTransfer.effectAllowed = "move";
  };

  const handleDragEnd = () => {
    setIsDragging(false);
  };

  return (
    <div
      draggable={canDrag}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      className={`
        flex items-center gap-3 p-3 rounded-lg border bg-zinc-900 transition-colors hover:bg-zinc-800
        ${isSottoScorta ? "border-red-500/50" : "border-zinc-800"}
        ${canDrag ? "cursor-grab active:cursor-grabbing" : ""}
        ${isDragging ? "opacity-50 ring-2 ring-blue-500" : ""}
      `}
    >
      {/* Indicatore draggable */}
      {canDrag && (
        <div 
          className="w-4 h-8 flex flex-col items-center justify-center gap-0.5 text-zinc-600 hover:text-zinc-400 flex-shrink-0" 
          title="Trascina per assegnare a macchina"
        >
          <div className="w-1 h-1 rounded-full bg-current"></div>
          <div className="w-1 h-1 rounded-full bg-current"></div>
          <div className="w-1 h-1 rounded-full bg-current"></div>
        </div>
      )}
      
      {/* Indicatore sotto scorta */}
      {isSottoScorta && (
        <div className="w-2 h-2 rounded-full bg-red-500 flex-shrink-0" title="Sotto scorta" />
      )}

      {/* Info articolo */}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="font-medium text-white truncate text-sm" title={article.descrizione}>
            {article.descrizione}
          </span>
          {article.famiglia && (
            <span className="px-1.5 py-0.5 text-[10px] rounded bg-zinc-800 text-zinc-500 flex-shrink-0">
              {article.famiglia}
            </span>
          )}
        </div>
        <div className="flex items-center gap-3 text-xs text-zinc-500 mt-0.5">
          <span className="font-mono">{article.codice}</span>
        </div>
      </div>

      {/* Quantità */}
      <div className="flex items-center gap-4 flex-shrink-0">
        {/* Quantità totale */}
        <div className="text-right">
          <div className="text-[10px] text-zinc-600 uppercase">Totale</div>
          <div className={`text-sm font-semibold ${isSottoScorta ? "text-red-400" : "text-white"}`}>
            {article.quantita}
            {isSottoScorta && (
              <span className="text-[10px] text-red-400 ml-1">(min {article.quantita_minima})</span>
            )}
          </div>
        </div>

        {/* Quantità magazzino (se disponibile) */}
        {hasGiacenzaMagazzino && (
          <div className="text-right border-l border-zinc-800 pl-4">
            <div className="text-[10px] text-zinc-600 uppercase truncate max-w-[80px]" title={magazzinoNome}>
              {magazzinoNome || "Mag."}
            </div>
            <div className={`text-sm font-semibold ${
              giacenzaMagazzino === 0 ? "text-zinc-600" : 
              giacenzaMagazzino! > 0 ? "text-green-400" : "text-white"
            }`}>
              {giacenzaMagazzino}
            </div>
          </div>
        )}

        {/* Disponibile */}
        <div className="text-right border-l border-zinc-800 pl-4">
          <div className="text-[10px] text-zinc-600 uppercase">Disp.</div>
          <div className={`text-sm font-semibold ${
            disponibile <= 0 ? "text-yellow-400" : "text-green-400"
          }`}>
            {disponibile}
          </div>
        </div>
      </div>

      {/* Azioni movimenti */}
      {onMovimento && (
        <div className="flex items-center gap-1 flex-shrink-0 border-l border-zinc-800 pl-3">
          <button
            onClick={() => onMovimento(article, "carico")}
            className="p-1.5 rounded text-zinc-500 hover:text-green-400 hover:bg-green-500/10 transition-colors"
            title="Carico"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
          </button>
          <button
            onClick={() => onMovimento(article, "scarico")}
            className="p-1.5 rounded text-zinc-500 hover:text-red-400 hover:bg-red-500/10 transition-colors"
            title="Scarico"
          >
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 12H4" />
            </svg>
          </button>
        </div>
      )}

      {/* Azioni CRUD */}
      <div className="flex items-center gap-1 flex-shrink-0 border-l border-zinc-800 pl-3">
        <button
          onClick={() => onEdit(article)}
          className="p-1.5 rounded text-zinc-500 hover:text-blue-400 hover:bg-zinc-700 transition-colors"
          title="Modifica"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
          </svg>
        </button>
        <button
          onClick={handleDelete}
          disabled={deleting}
          className="p-1.5 rounded text-zinc-500 hover:text-red-400 hover:bg-zinc-700 transition-colors disabled:opacity-50"
          title="Elimina"
        >
          {deleting ? (
            <svg className="w-4 h-4 animate-spin" viewBox="0 0 24 24">
              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
            </svg>
          ) : (
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
            </svg>
          )}
        </button>
      </div>
    </div>
  );
}
