import React, { useEffect, useState } from "react";
import { api } from "./api.js";
import { StatusChip, ProgressBar } from "./ui.jsx";

export default function Chapters({ slug, book, state, busy }) {
  const chapters = book.chapters.filter((c) => c.render);
  const [backend, setBackend] = useState("kokoro");
  const [mono, setMono] = useState(false);
  const [selected, setSelected] = useState(() => new Set());

  // Initialise le moteur sur le backend par defaut des reglages.
  useEffect(() => {
    api.getSettings().then((s) => s?.default_backend && setBackend(s.default_backend)).catch(() => {});
  }, []);

  const toggle = (idx) => {
    const next = new Set(selected);
    next.has(idx) ? next.delete(idx) : next.add(idx);
    setSelected(next);
  };

  const renderChapters = (indexes) => {
    if (!indexes.length) return;
    api.render(slug, indexes, backend, mono);
  };

  return (
    <div className="space-y-4">
      <div className="card flex flex-wrap items-center gap-3 p-3">
        <label className="text-sm text-ink-muted">Moteur</label>
        <select className="input" value={backend} onChange={(e) => setBackend(e.target.value)}>
          <option value="kokoro">Kokoro (rapide)</option>
          <option value="qwen3">Qwen3 (qualité + clonage)</option>
        </select>
        <label className="flex items-center gap-2 text-sm text-ink-muted">
          <input type="checkbox" checked={mono} onChange={(e) => setMono(e.target.checked)} />
          mono-narrateur
        </label>
        <div className="ml-auto flex gap-2">
          <button className="btn-ghost" disabled={busy || !selected.size}
            onClick={() => renderChapters([...selected])}>
            Rendre la sélection ({selected.size})
          </button>
          <button className="btn-primary" disabled={busy}
            onClick={() => renderChapters(chapters.map((c) => c.index))}>
            Rendre tout
          </button>
        </div>
      </div>

      <div className="card divide-y divide-ink-edge">
        {chapters.map((c) => {
          const rs = state.render?.[c.index] || state.render?.[String(c.index)] || {};
          const analyzed = (state.analyzed_chapters || []).includes(c.index);
          return (
            <div key={c.index} className="flex items-center gap-3 px-4 py-2.5">
              <input type="checkbox" checked={selected.has(c.index)}
                onChange={() => toggle(c.index)} />
              <div className="w-9 text-center text-xs text-ink-muted">{c.index}</div>
              <div className="flex-1 min-w-0">
                <p className="truncate font-serif text-sm">{c.title}</p>
                <div className="mt-0.5 flex items-center gap-2 text-xs text-ink-muted">
                  <span>{c.word_count} mots</span>
                  {c.pov && <span className="chip bg-ink-edge text-ink-muted">{c.pov}</span>}
                  {analyzed && <span className="text-emerald-400">analysé</span>}
                </div>
                {rs.status === "running" && (
                  <div className="mt-1.5 max-w-xs"><ProgressBar value={rs.progress} /></div>
                )}
              </div>
              {rs.status && <StatusChip status={rs.status} />}
              {rs.mp3 && (
                <>
                  <audio controls src={api.audioUrl(slug, c.index)} className="h-8" />
                  <a className="btn-ghost" href={api.audioUrl(slug, c.index)} download>↓</a>
                </>
              )}
              {!busy && (
                <>
                  <button className="btn-ghost" title={analyzed ? "Ré-analyser ce chapitre" : "Analyser ce chapitre"}
                    onClick={() => api.analyze(slug, [c.index])}>
                    {analyzed ? "Ré-analyser" : "Analyser"}
                  </button>
                  <button className="btn-ghost" title="Ré-analyser le casting de ce chapitre (sans re-segmenter)"
                    onClick={() => api.castAnalyze(slug, [c.index])}>
                    Casting
                  </button>
                  <button className="btn-ghost" title="Rendre ce chapitre"
                    onClick={() => renderChapters([c.index])}>▶</button>
                </>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
