// src/components/Dashboard.jsx

const QUIZZES = [
  {
    id: "q1",
    imageKey: "Q1.jpeg",
    title: { it: "Harmonised compliance", en: "Harmonised compliance" },
    description: {
      it: "Valuta il livello di maturità dei sistemi di governance e l'integrazione multidisciplinare dei processi aziendali.",
      en: "Assess the maturity level of governance systems and the multidisciplinary integration of business processes."
    },
    duration: "5 min"
  },
  {
    id: "q2",
    imageKey: "Q2.png",
    title: { it: "OT Resilience & Integrity", en: "OT Resilience & Integrity" },
    description: {
      it: "Analisi approfondita della sicurezza, segregazione e integrità dei dati nei sistemi industriali e di produzione (PLC/SCADA).",
      en: "Deep dive analysis of security, segregation, and data integrity in industrial and production systems (PLC/SCADA)."
    },
    duration: "5 min"
  },
  {
    id: "q3",
    imageKey: "Q3.png",
    title: { it: "ESG & CSR", en: "ESG & CSR" },
    description: {
      it: "Misura la sostenibilità aziendale, l'impatto ambientale e la responsabilità sociale d'impresa secondo i framework vigenti.",
      en: "Measure corporate sustainability, environmental impact, and corporate social responsibility according to current frameworks."
    },
    duration: "5 min"
  },
  {
    id: "q4",
    imageKey: "Q4.png",
    title: { it: "Digital Validation", en: "Digital Validation" },
    description: {
      it: "Verifica l'efficacia dei protocolli di convalida software, infrastrutture cloud e approcci basati sul rischio (CSA/GxP).",
      en: "Verify the effectiveness of software validation protocols, cloud infrastructures, and risk-based approaches (CSA/GxP)."
    },
    duration: "5 min"
  },
  {
    id: "q5",
    imageKey: "Q5.png",
    title: { it: "Intelligenza Artificiale", en: "Artificial Intelligence" },
    description: {
      it: "Valutazione dei sistemi di Intelligenza Artificiale e Machine Learning, tracciabilità ALCOA+ e protocolli di supervisione umana.",
      en: "Evaluation of Artificial Intelligence and Machine Learning systems, ALCOA+ traceability, and human oversight protocols."
    },
    duration: "5 min"
  }
];

function Dashboard({ onSelectQuiz }) {
  const urlParams = new URLSearchParams(window.location.search);
  const isCollegaView = urlParams.get('view') === 'lead';
  
  // Legge la lingua dalla configurazione globale
  const lang = typeof APP_CONFIG !== 'undefined' && APP_CONFIG.enableItalian ? 'it' : 'en';

  const [leads, setLeads] = React.useState([]);
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);
  const [password, setPassword] = React.useState("");

  // STATI PER I FILTRI
  const [searchTerm, setSearchTerm] = React.useState("");
  const [selectedQuiz, setSelectedQuiz] = React.useState("ALL");
  const [selectedDate, setSelectedDate] = React.useState("ALL");
  const [sortOrder, setSortOrder] = React.useState("DESC"); // DESC = Più bravi prima, ASC = Più scarsi prima

  React.useEffect(() => {
    if (!isCollegaView || !isAuthenticated) return;

    if (!window.firebase || !window.firebase.firestore) {
      console.error("Firebase SDK non disponibile.");
      return;
    }

    const db = window.firebase.firestore();
    const unsubscribe = db.collection("lead_fiera_2026")
      .orderBy("createdAt", "desc")
      .onSnapshot((snapshot) => {
        const docs = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() }));
        setLeads(docs);
      }, (err) => console.error("Errore Firestore:", err));

    return () => unsubscribe();
  }, [isAuthenticated, isCollegaView]);

  const texts = {
    it: {
      welcome: "Mettiti alla prova!",
      subtitle: "Seleziona uno dei seguenti assessment per iniziare la tua valutazione specialistica.",
      startBtn: "Inizia Questionario"
    },
    en: {
      welcome: "Challenge yourself!",
      subtitle: "Select one of the following assessments to start your specialized evaluation.",
      startBtn: "Start Quiz"
    }
  };

  const handleLogin = (e) => {
    e.preventDefault();
    if (password === "Maasi_admin!") {
      setIsAuthenticated(true);
    } else {
      alert("Password errata!");
    }
  };

  const scaricaPDFCertificato = (lead) => {
    const finestraStampa = window.open('', '_blank');
    const htmlFinale = window.generaHtmlCertificato(lead);
    finestraStampa.document.write(htmlFinale);
    finestraStampa.document.write(`
      <script>
        window.onload = function() { 
          setTimeout(function() { window.print(); window.close(); }, 450);
        }
      </script>
    `);
    finestraStampa.document.close();
  };

  // ESTRAZIONE DELLE DATE UNICHE PER IL FILTRO DATE
  const uniqueDates = React.useMemo(() => {
    const dates = new Set();
    leads.forEach(l => {
      if (l.createdAt?.toDate) {
        dates.add(l.createdAt.toDate().toLocaleDateString('it-IT'));
      }
    });
    return Array.from(dates);
  }, [leads]);

  // APPLICAZIONE DEI FILTRI E ORDINAMENTO SUI LEADS
  const filteredAndSortedLeads = React.useMemo(() => {
    let result = [...leads];

    // 1. Filtro testuale (Nome, Cognome, Email, Azienda)
    if (searchTerm.trim() !== "") {
      const lowerSearch = searchTerm.toLowerCase();
      result = result.filter(l => 
        (l.name && l.name.toLowerCase().includes(lowerSearch)) ||
        (l.surname && l.surname.toLowerCase().includes(lowerSearch)) ||
        (l.email && l.email.toLowerCase().includes(lowerSearch)) ||
        (l.company && l.company.toLowerCase().includes(lowerSearch))
      );
    }

    // 2. Filtro per Questionario
    if (selectedQuiz !== "ALL") {
      result = result.filter(l => l.quizId === selectedQuiz);
    }

    // 3. Filtro per Data
    if (selectedDate !== "ALL") {
      result = result.filter(l => {
        if (!l.createdAt?.toDate) return false;
        return l.createdAt.toDate().toLocaleDateString('it-IT') === selectedDate;
      });
    }

    // 4. Ordinamento per Punteggio
    result.sort((a, b) => {
      const scoreA = Number(a.score) || 0;
      const scoreB = Number(b.score) || 0;
      if (sortOrder === "ASC") {
        return scoreA - scoreB; // Dal più scarso al più bravo
      } else {
        return scoreB - scoreA; // Dal più bravo al più scarso
      }
    });

    return result;
  }, [leads, searchTerm, selectedQuiz, selectedDate, sortOrder]);

  // ==========================================
  // VISTA LIVE LEADS CON DETTAGLIO RISPOSTE E FILTRI
  // ==========================================
  if (isCollegaView) {
    if (!isAuthenticated) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-slate-50 text-slate-900 p-4">
          <form onSubmit={handleLogin} className="max-w-sm w-full bg-white p-8 rounded-2xl border border-slate-200 space-y-4 shadow-xl">
            <h2 className="text-2xl font-bold text-indigo-600 tracking-tight text-center">Dashboard Live Lead</h2>
            <p className="text-xs text-slate-500 text-center !mt-1">Inserisci le credenziali del padiglione</p>
            <input 
              type="password" 
              placeholder="Password Stand" 
              value={password} 
              onChange={(e) => setPassword(e.target.value)}
              className="w-full p-3 bg-slate-50 border border-slate-200 rounded-xl text-slate-900 focus:outline-none focus:border-indigo-500 focus:bg-white text-sm transition-all"
            />
            <button type="submit" className="w-full p-3 bg-indigo-600 hover:bg-indigo-700 rounded-xl font-bold text-sm text-white shadow-md shadow-indigo-600/10 cursor-pointer transition-all">Accedi</button>
          </form>
        </div>
      );
    }

    return (
      <div className="min-h-screen bg-slate-50 text-slate-900 p-6 lg:p-10">
        <div className="max-w-7xl mx-auto space-y-6">
          <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
              <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight">Anagrafiche Assessment</h1>
              <p className="text-sm text-slate-500 mt-1">Lead totali registrati: <span className="text-indigo-600 font-bold font-mono text-base">{leads.length}</span></p>
            </div>
            <span className="text-xs bg-emerald-500/10 text-emerald-600 border border-emerald-500/20 px-3 py-1.5 rounded-full font-mono font-bold flex items-center gap-1.5 shadow-sm">
              <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span> COLLEGATO LIVE
            </span>
          </div>

          {/* BARRA DEI FILTRI */}
          <div className="bg-white border border-slate-200 rounded-2xl p-4 shadow-sm flex flex-col md:flex-row gap-4">
            <input 
              type="text" 
              placeholder="Cerca utente o email..." 
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="flex-1 p-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:border-indigo-500"
            />
            <select 
              value={selectedQuiz} 
              onChange={(e) => setSelectedQuiz(e.target.value)}
              className="flex-1 p-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:border-indigo-500"
            >
              <option value="ALL">Tutti i Questionari</option>
              {QUIZZES.map(q => <option key={q.id} value={q.id}>{q.title.it}</option>)}
            </select>
            <select 
              value={selectedDate} 
              onChange={(e) => setSelectedDate(e.target.value)}
              className="flex-1 p-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:border-indigo-500"
            >
              <option value="ALL">Tutte le Date</option>
              {uniqueDates.map((d, idx) => <option key={idx} value={d}>{d}</option>)}
            </select>
            <select 
              value={sortOrder} 
              onChange={(e) => setSortOrder(e.target.value)}
              className="flex-1 p-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:border-indigo-500 font-medium"
            >
              <option value="DESC">Punteggio: dal più bravo</option>
              <option value="ASC">Punteggio: dal più scarso</option>
            </select>
          </div>
          
          {/* TABELLA DATI */}
          <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-md">
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-slate-50 border-b border-slate-200 text-slate-600 text-xs font-bold uppercase tracking-wider">
                    <th className="p-4 w-20">Orario</th>
                    <th className="p-4 w-1/4">Anagrafica</th>
                    <th className="p-4 w-1/4">Contatti</th>
                    <th className="p-4 w-1/3">Dettaglio Domande & Risposte Scelte</th>
                    <th className="p-4 text-center">Score</th>
                    <th className="p-4 text-center w-24">Certificato</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100 text-sm">
                  {filteredAndSortedLeads.map((l) => (
                    <tr key={l.id} className="hover:bg-slate-50/60 transition-colors align-top">
                      <td className="p-4 font-mono text-slate-400 whitespace-nowrap pt-5">
                        {l.createdAt?.toDate 
                          ? l.createdAt.toDate().toLocaleString('it-IT', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) 
                          : "Ora"}
                      </td>                      
                      <td className="p-4 pt-5">
                        <div className="font-bold text-slate-900 text-base">{l.name} {l.surname}</div>
                        <div className="text-xs text-slate-500 mt-0.5">{l.role} @ <span className="text-indigo-600 font-semibold">{l.company}</span></div>
                      </td>
                      <td className="p-4 pt-5">
                        <div className="font-medium text-slate-700 break-all">{l.email}</div>
                        <div className="text-xs text-slate-400 mt-0.5 font-mono">{l.phone || "-"}</div>
                      </td>
                      <td className="p-4 pt-5">
                        <div className="mb-2 text-indigo-600 font-bold uppercase tracking-wider text-xs">
                          {l.quizTitle} <span className="text-slate-400 font-normal">({l.profileTitle || "N/A"})</span>
                        </div>
                        {l.answers && Array.isArray(l.answers) ? (
                          <div className="space-y-3 bg-slate-50 p-4 rounded-xl border border-slate-100 max-h-64 overflow-y-auto shadow-inner">
                            {l.answers.map((ans, idx) => (
                              <div key={idx} className="text-xs space-y-0.5 border-b border-slate-200/60 pb-2 last:border-none last:pb-0">
                                <div className="text-slate-500 font-medium">Q: {ans.domanda}</div>
                                <div className="text-emerald-600 font-bold">A: {ans.risposta_scelta}</div>
                              </div>
                            ))}
                          </div>
                        ) : (
                          <span className="text-slate-400 italic text-xs">Nessun dettaglio risposte salvato o formato vecchio.</span>
                        )}
                      </td>
                      <td className="p-4 text-center font-mono font-bold text-base text-emerald-600 bg-emerald-50/30 pt-5">
                        {l.score} pt
                      </td>
                      <td className="p-4 text-center pt-5">
                        <button onClick={() => scaricaPDFCertificato(l)} className="inline-flex items-center justify-center gap-1.5 bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold py-1.5 px-3 rounded-xl shadow-sm hover:shadow transition-all cursor-pointer">
                          <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/>
                          </svg>
                          PDF
                        </button>
                      </td>
                    </tr>
                  ))}
                  {filteredAndSortedLeads.length === 0 && (
                    <tr>
                      <td colSpan="6" className="p-12 text-center text-slate-400 italic text-base">
                        Nessun risultato trovato per i filtri selezionati.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ==========================================
  // VISTA UTENTE (SELEZIONE QUIZ)
  // ==========================================
  return (
    <div className="min-h-screen bg-slate-50 text-slate-900 px-6 py-12 lg:px-16 flex flex-col items-center justify-center">
      <div className="max-w-7xl mx-auto mb-12 animate-fadeIn text-center">
        <h1 className="text-4xl lg:text-6xl font-extrabold tracking-tight mt-4 text-slate-900">
          {texts[lang].welcome}
        </h1>
        <p className="text-slate-500 text-base lg:text-lg mt-4 max-w-2xl mx-auto">
          {texts[lang].subtitle}
        </p>
      </div>

      <div className="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 animate-slideUp">
        {QUIZZES.map((quiz) => (
          <div key={quiz.id} className="group relative bg-white border border-slate-200 rounded-2xl overflow-hidden hover:border-indigo-300 hover:shadow-[0_15px_30px_rgba(99,102,241,0.08)] transition-all duration-300 flex flex-col cursor-pointer" onClick={() => onSelectQuiz(quiz.id)}>
            <div className="relative h-48 w-full bg-slate-100 overflow-hidden flex items-center justify-center border-b border-slate-100">
              <span className="absolute top-4 right-4 z-20 text-[11px] font-bold bg-white/90 border border-slate-200 text-slate-700 px-2.5 py-1 rounded-md shadow-sm">⏱️ {quiz.duration}</span>
              <img src={`/assets/quiz-cards/${quiz.imageKey}`} alt={quiz.title[lang]} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500 opacity-90 group-hover:opacity-100" onError={(e) => { e.target.style.display = 'none'; }} />
            </div>
            <div className="p-6 flex-1 flex flex-col justify-between">
              <div>
                <h3 className="text-xl font-bold tracking-tight text-slate-900 group-hover:text-indigo-600 transition-colors duration-200">{quiz.title[lang]}</h3>
                <p className="text-slate-500 text-sm mt-2 line-clamp-3 leading-relaxed">{quiz.description[lang]}</p>
              </div>
              <div className="mt-6">
                <button className="w-full bg-slate-50 hover:bg-indigo-600 border border-slate-200 hover:border-transparent text-slate-800 hover:text-white font-bold py-3 px-4 rounded-xl transition-all duration-300 flex items-center justify-center gap-2">
                  {texts[lang].startBtn}
                  <span className="transform group-hover:translate-x-1 transition-transform">→</span>
                </button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;