// src/ModelOverview.jsx

import React, { useEffect, useState } from "react";

export default function ModelOverview({ onBackToChat }) {
  const [defaultModel, setDefaultModel] = useState("");
  const [modelInfo, setModelInfo] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [loading, setLoading] = useState(false);

  const fetchModelData = async () => {
    setLoading(true);
    try {
      const [defaultRes, infoRes] = await Promise.all([
        fetch("/v1/default-model"),
        fetch("/v1/models-info")
      ]);
      const defaultText = await defaultRes.text();
      const infoJson = await infoRes.json();
      setDefaultModel(defaultText);
      setModelInfo(Array.isArray(infoJson) ? infoJson : []);
    } catch (err) {
      console.error("Errore nel caricamento modelli", err);
    } finally {
      setLoading(false);
    }
  };

  const updateModelData = async () => {
    setLoading(true);
    try {
      const res = await fetch("/v1/models-info/update", { method: "POST" });
      if (res.ok) {
        const updated = await res.json();
        setModelInfo(Array.isArray(updated) ? updated : []);
      }
    } catch (err) {
      console.error("Errore nell'aggiornamento modelli", err);
    } finally {
      setLoading(false);
    }
  };

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

  const filteredModels = modelInfo.filter((model) =>
    model.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="container py-4">
      <div className="bg-light p-4 rounded shadow-sm mb-4">
        <h3 className="mb-0">📌 Modello di default</h3>
        <p className="lead text-muted mb-0">
          {defaultModel || "Non disponibile"}
        </p>
      </div>

      <div className="d-flex justify-content-between mb-3">
        <button className="btn btn-outline-primary" onClick={onBackToChat}>
          ⬅ Torna alla chat
        </button>
        <button className="btn btn-outline-success" onClick={updateModelData}>
          🔄 Aggiorna dati modelli
        </button>
      </div>

      <div className="mb-3">
        <input
          type="text"
          className="form-control"
          placeholder="🔍 Cerca modello per nome..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
        />
      </div>

      <div className="table-responsive">
        <table className="table table-bordered table-hover align-middle">
          <thead className="table-light">
            <tr>
              <th>Nome</th>
              <th>Descrizione</th>
	      {/*<th>Anno</th>*/}
              <th>Caratteristiche</th>
            </tr>
          </thead>
          <tbody>
            {loading && (
              <tr>
                <td colSpan="4" className="text-center">Caricamento…</td>
              </tr>
            )}
            {!loading && filteredModels.length === 0 && (
              <tr>
                <td colSpan="4" className="text-center">Nessun modello trovato</td>
              </tr>
            )}
            {!loading && filteredModels.map((model) => (
              <tr key={model.name}>
                <td>{model.name}</td>
                <td>{model.description || "—"}</td>
		{/*<td>{model.year || "—"}</td>*/}
                <td>
                  <ul className="mb-0 small">
                    {Array.isArray(model.features) && model.features.length > 0
                      ? model.features.map((f, i) => <li key={i}>{f}</li>)
                      : <li>—</li>}
                  </ul>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

