"use client";

import { useState, useEffect, useCallback } from "react";
import type { Movimento } from "@/src/types/movimento";

export default function MovimentiPage() {
  const [movimenti, setMovimenti] = useState<Movimento[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchMovimenti = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      const res = await fetch("/api/movimenti?limit=200");
      if (!res.ok) throw new Error("Errore nel caricamento");

      const data = await res.json();
      setMovimenti(data.movimenti);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore sconosciuto");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchMovimenti();
  }, [fetchMovimenti]);

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleString("it-IT", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  return (
    <div className="min-h-screen bg-black">
      <div className="max-w-7xl mx-auto px-4 py-6">
        {/* Header */}
        <div className="mb-6">
          <h1 className="text-2xl font-bold text-white">Movimenti</h1>
          <p className="text-sm text-zinc-500">Storico carichi e scarichi</p>
        </div>

        {/* Statistiche rapide */}
        <div className="grid grid-cols-3 gap-4 mb-6">
          <div className="p-4 rounded-xl bg-zinc-900 border border-zinc-800">
            <p className="text-sm text-zinc-500">Totale movimenti</p>
            <p className="text-2xl font-bold text-white">{movimenti.length}</p>
          </div>
          <div className="p-4 rounded-xl bg-zinc-900 border border-green-500/30">
            <p className="text-sm text-zinc-500">Carichi</p>
            <p className="text-2xl font-bold text-green-400">
              {movimenti.filter((m) => m.tipo_movimento === 1).length}
            </p>
          </div>
          <div className="p-4 rounded-xl bg-zinc-900 border border-red-500/30">
            <p className="text-sm text-zinc-500">Scarichi</p>
            <p className="text-2xl font-bold text-red-400">
              {movimenti.filter((m) => m.tipo_movimento === 2).length}
            </p>
          </div>
        </div>

        {/* Lista movimenti */}
        {loading ? (
          <div className="flex items-center justify-center py-20 text-zinc-500">
            <svg className="w-6 h-6 animate-spin mr-3" 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>
            Caricamento movimenti...
          </div>
        ) : error ? (
          <div className="p-6 rounded-xl bg-red-500/10 border border-red-500/30 text-center">
            <p className="text-red-400">{error}</p>
            <button onClick={fetchMovimenti} className="mt-4 px-4 py-2 rounded-lg bg-red-600 text-white hover:bg-red-500">
              Riprova
            </button>
          </div>
        ) : movimenti.length === 0 ? (
          <div className="p-12 rounded-xl bg-zinc-900 border border-zinc-800 text-center">
            <svg className="w-16 h-16 mx-auto text-zinc-700 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            <h3 className="text-lg font-medium text-white mb-2">Nessun movimento</h3>
            <p className="text-zinc-500">I movimenti appariranno qui quando effettuerai carichi o scarichi</p>
          </div>
        ) : (
          <div className="rounded-xl border border-zinc-800 overflow-hidden">
            {/* Header tabella */}
            <div className="grid grid-cols-12 gap-4 px-4 py-3 bg-zinc-800/50 text-xs font-medium text-zinc-400 uppercase tracking-wider">
              <div className="col-span-1">Tipo</div>
              <div className="col-span-3">Articolo</div>
              <div className="col-span-1 text-center">Carico</div>
              <div className="col-span-1 text-center">Scarico</div>
              <div className="col-span-2">Magazzino</div>
              <div className="col-span-2">Data / Utente</div>
              <div className="col-span-2">Causale</div>
            </div>

            {/* Righe */}
            <div className="divide-y divide-zinc-800">
              {movimenti.map((movimento) => {
                const isCarico = movimento.tipo_movimento === 1;
                
                return (
                  <div
                    key={movimento.id}
                    className="grid grid-cols-12 gap-4 px-4 py-3 bg-zinc-900 hover:bg-zinc-800/50 transition-colors items-center"
                  >
                    {/* Tipo */}
                    <div className="col-span-1">
                      <div className={`
                        inline-flex items-center justify-center w-8 h-8 rounded-lg
                        ${isCarico ? "bg-green-500/10 text-green-400" : "bg-red-500/10 text-red-400"}
                      `}>
                        {isCarico ? (
                          <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>
                        ) : (
                          <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>
                        )}
                      </div>
                    </div>

                    {/* Articolo */}
                    <div className="col-span-3 min-w-0">
                      <p className="font-medium text-white truncate text-sm">
                        {movimento.articolo_descrizione}
                      </p>
                      <p className="text-xs text-zinc-500 font-mono">
                        {movimento.articolo_codice}
                      </p>
                    </div>

                    {/* Quantità Carico */}
                    <div className="col-span-1 text-center">
                      {isCarico ? (
                        <span className="text-lg font-bold text-green-400">
                          +{movimento.quantita}
                        </span>
                      ) : (
                        <span className="text-zinc-700">-</span>
                      )}
                    </div>

                    {/* Quantità Scarico */}
                    <div className="col-span-1 text-center">
                      {!isCarico ? (
                        <span className="text-lg font-bold text-red-400">
                          -{movimento.quantita}
                        </span>
                      ) : (
                        <span className="text-zinc-700">-</span>
                      )}
                    </div>

                    {/* Magazzino */}
                    <div className="col-span-2">
                      <p className="text-xs text-zinc-500 mb-0.5">
                        {isCarico ? "Destinazione" : "Origine"}
                      </p>
                      <p className="text-sm text-white">
                        {isCarico 
                          ? movimento.magazzino_destinazione || "-"
                          : movimento.magazzino_origine || "-"}
                      </p>
                    </div>

                    {/* Data / Utente */}
                    <div className="col-span-2">
                      <p className="text-sm text-white">
                        {formatDate(movimento.data_movimento)}
                      </p>
                      <p className="text-xs text-zinc-500">
                        {movimento.utente || "-"}
                      </p>
                    </div>

                    {/* Causale */}
                    <div className="col-span-2">
                      <p className="text-sm text-zinc-400 truncate" title={movimento.causale || ""}>
                        {movimento.causale || "-"}
                      </p>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
