"use client";

import { useState } from "react";
import { Download, Archive, AlertTriangle, Check, RefreshCw } from "lucide-react";
import { API_BASE_URL } from "@/lib/api";
import { useRouter } from "next/navigation";

export default function DatasetToolbar() {
  const router = useRouter();
  const [isExporting, setIsExporting] = useState(false);
  const [isArchiving, setIsArchiving] = useState(false);
  const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);

  const handleExport = async () => {
    setIsExporting(true);
    try {
      // On ouvre simplement l'URL dans un nouvel onglet pour déclencher le téléchargement
      window.open(`${API_BASE_URL}/api/export/zip`, '_blank');
    } catch (error) {
      console.error("Export error:", error);
    } finally {
      setIsExporting(false);
    }
  };

  const handleArchive = async () => {
    setIsArchiving(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/export/archive`, {
        method: "POST"
      });
      if (response.ok) {
        setShowArchiveConfirm(false);
        router.refresh(); // Rafraîchir la galerie
      } else {
        alert("Erreur lors de l'archivage");
      }
    } catch (error) {
      console.error("Archive error:", error);
      alert("Erreur réseau");
    } finally {
      setIsArchiving(false);
    }
  };

  return (
    <div className="bg-slate-900 border border-slate-800 rounded-2xl p-6 flex flex-col md:flex-row items-center justify-between gap-6 shadow-xl shadow-indigo-500/5">
      <div className="space-y-1">
        <h3 className="font-bold text-lg flex items-center gap-2">
          <RefreshCw size={20} className="text-indigo-400" />
          Gestion du Dataset
        </h3>
        <p className="text-xs text-slate-500">Exportez vos sessions étiquetées en ZIP et archivez-les pour nettoyer la galerie.</p>
      </div>

      <div className="flex gap-3">
        <button 
          onClick={handleExport}
          disabled={isExporting}
          className="flex items-center gap-2 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 px-5 py-2.5 rounded-xl text-sm font-bold transition-all hover:scale-105 active:scale-95 shadow-lg shadow-indigo-600/20"
        >
          <Download size={18} />
          {isExporting ? "Préparation..." : "Télécharger ZIP"}
        </button>

        {!showArchiveConfirm ? (
          <button 
            onClick={() => setShowArchiveConfirm(true)}
            className="flex items-center gap-2 bg-slate-800 hover:bg-slate-700 px-5 py-2.5 rounded-xl text-sm font-bold transition-all border border-slate-700"
          >
            <Archive size={18} />
            Archiver les sessions
          </button>
        ) : (
          <div className="flex items-center gap-2 animate-in fade-in slide-in-from-right-4 duration-300">
            <div className="flex items-center gap-2 px-4 py-2 bg-rose-500/10 border border-rose-500/20 rounded-xl text-rose-400 text-xs font-bold">
              <AlertTriangle size={14} />
              Vider la galerie ?
            </div>
            <button 
              onClick={handleArchive}
              disabled={isArchiving}
              className="bg-rose-600 hover:bg-rose-500 p-2.5 rounded-xl transition-colors disabled:opacity-50"
            >
              <Check size={18} className="text-white" />
            </button>
            <button 
              onClick={() => setShowArchiveConfirm(false)}
              className="bg-slate-800 hover:bg-slate-700 p-2.5 rounded-xl transition-colors"
            >
              <Archive size={18} className="text-slate-400" />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
