"use client";

import { useState, useEffect, useCallback } from "react";
import type { Article, ArticleFamily } from "@/src/types/article";
import type { Stabilimento } from "@/src/types/stabilimento";
import ArticleCard from "./ArticleCard";
import ArticleModal from "./ArticleModal";

interface ArticlesGridProps {
  stabilimento: Stabilimento;
}

export default function ArticlesGrid({ stabilimento }: ArticlesGridProps) {
  const [articles, setArticles] = useState<Article[]>([]);
  const [families, setFamilies] = useState<ArticleFamily[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [search, setSearch] = useState("");
  const [selectedFamily, setSelectedFamily] = useState<number | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [editingArticle, setEditingArticle] = useState<Article | null>(null);

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

    try {
      const params = new URLSearchParams();
      params.set("stabilimentoId", stabilimento.id.toString());
      
      if (search) params.set("search", search);
      if (selectedFamily) params.set("famigliaId", selectedFamily.toString());

      const res = await fetch(`/api/articoli?${params}`);
      if (!res.ok) throw new Error("Errore nel caricamento");

      const data = await res.json();
      setArticles(data.articles);
      setFamilies(data.families);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Errore sconosciuto");
    } finally {
      setLoading(false);
    }
  }, [stabilimento.id, search, selectedFamily]);

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

  const handleEdit = (article: Article) => {
    setEditingArticle(article);
    setShowModal(true);
  };

  const handleDelete = (deleted: Article) => {
    setArticles((prev) => prev.filter((a) => a.id !== deleted.id));
  };

  const handleSave = (saved: Article) => {
    if (editingArticle) {
      setArticles((prev) =>
        prev.map((a) => (a.id === saved.id ? saved : a))
      );
    } else {
      setArticles((prev) => [saved, ...prev]);
    }
    setShowModal(false);
    setEditingArticle(null);
  };

  const handleNewArticle = () => {
    setEditingArticle(null);
    setShowModal(true);
  };

  const sottoScorta = articles.filter((a) => a.quantita < a.quantita_minima);
  const totaleValore = articles.reduce((sum, a) => sum + a.prezzo * a.quantita, 0);

  return (
    <div className="space-y-6">
      {/* Header con statistiche */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="p-4 rounded-xl bg-zinc-900 border border-zinc-800">
          <p className="text-sm text-zinc-500">Totale Articoli</p>
          <p className="text-2xl font-bold text-white">{articles.length}</p>
        </div>
        <div className="p-4 rounded-xl bg-zinc-900 border border-zinc-800">
          <p className="text-sm text-zinc-500">Famiglie</p>
          <p className="text-2xl font-bold text-white">{families.length}</p>
        </div>
        <div className="p-4 rounded-xl bg-zinc-900 border border-red-500/30">
          <p className="text-sm text-zinc-500">Sotto Scorta</p>
          <p className="text-2xl font-bold text-red-400">{sottoScorta.length}</p>
        </div>
        <div className="p-4 rounded-xl bg-zinc-900 border border-zinc-800">
          <p className="text-sm text-zinc-500">Valore Totale</p>
          <p className="text-2xl font-bold text-green-400">€{totaleValore.toFixed(2)}</p>
        </div>
      </div>

      {/* Toolbar: ricerca, filtri, azioni */}
      <div className="flex flex-col md:flex-row gap-4 items-start md:items-center justify-between">
        <div className="flex flex-1 gap-4 w-full md:w-auto">
          {/* Ricerca */}
          <div className="relative flex-1 max-w-md">
            <svg
              className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-zinc-500"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
              />
            </svg>
            <input
              type="text"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Cerca articoli..."
              className="w-full pl-10 pr-4 py-2 rounded-lg bg-zinc-900 border border-zinc-800 text-white placeholder-zinc-500 focus:outline-none focus:border-blue-500 transition-colors"
            />
          </div>

          {/* Filtro famiglia */}
          <select
            value={selectedFamily ?? ""}
            onChange={(e) =>
              setSelectedFamily(e.target.value ? parseInt(e.target.value, 10) : null)
            }
            className="px-4 py-2 rounded-lg bg-zinc-900 border border-zinc-800 text-white focus:outline-none focus:border-blue-500 transition-colors"
          >
            <option value="">Tutte le famiglie</option>
            {families.map((fam) => (
              <option key={fam.id} value={fam.id}>
                {fam.nome}
              </option>
            ))}
          </select>
        </div>

        {/* Pulsante nuovo articolo */}
        <button
          onClick={handleNewArticle}
          className="px-4 py-2 rounded-lg bg-blue-600 text-white font-medium hover:bg-blue-500 transition-colors flex items-center gap-2"
        >
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
          </svg>
          Nuovo Articolo
        </button>
      </div>

      {/* Contenuto principale */}
      {loading ? (
        <div className="flex items-center justify-center py-20">
          <div className="flex items-center gap-3 text-zinc-400">
            <svg className="w-6 h-6 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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              />
            </svg>
            <span>Caricamento articoli...</span>
          </div>
        </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={fetchArticles}
            className="mt-4 px-4 py-2 rounded-lg bg-red-600 text-white hover:bg-red-500 transition-colors"
          >
            Riprova
          </button>
        </div>
      ) : articles.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="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"
            />
          </svg>
          <h3 className="text-lg font-medium text-white mb-2">Nessun articolo trovato</h3>
          <p className="text-zinc-500 mb-6">
            {search || selectedFamily
              ? "Prova a modificare i filtri di ricerca"
              : "Inizia aggiungendo il primo articolo"}
          </p>
          {!search && !selectedFamily && (
            <button
              onClick={handleNewArticle}
              className="px-4 py-2 rounded-lg bg-blue-600 text-white font-medium hover:bg-blue-500 transition-colors"
            >
              Aggiungi articolo
            </button>
          )}
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {articles.map((article) => (
            <ArticleCard
              key={article.id}
              article={article}
              onEdit={handleEdit}
              onDelete={handleDelete}
            />
          ))}
        </div>
      )}

      {/* Modal */}
      {showModal && (
        <ArticleModal
          article={editingArticle}
          families={families}
          onClose={() => {
            setShowModal(false);
            setEditingArticle(null);
          }}
          onSave={handleSave}
        />
      )}
    </div>
  );
}
