import { useState, useEffect } from 'react';
import { api } from '../../api.js';

export default function CategoriesInvSection() {
  const [categoriesInv, setCategoriesInv] = useState([]);
  const [err, setErr]                     = useState(null);
  const [selectedCatInv, setSelectedCatInv] = useState(null);
  const [editingCatInv,  setEditingCatInv]  = useState(null);
  const [editingNomCatInv, setEditingNomCatInv] = useState('');
  const [newCatInvNom,   setNewCatInvNom]   = useState('');
  const [showNewCatInv,  setShowNewCatInv]  = useState(false);
  const [catGlobalOpen,  setCatGlobalOpen]  = useState(false);
  const [catPrivateOpen, setCatPrivateOpen] = useState(true);

  useEffect(() => {
    api.get('/categories-inv').then(data => {
      setCategoriesInv(data.sort((a, b) => b.is_global - a.is_global || a.nom.localeCompare(b.nom)));
    }).catch(() => {});
  }, []);

  const saveCatInv = async (nom) => {
    if (!nom.trim()) return;
    try {
      const row = await api.post('/categories-inv', { nom: nom.trim() });
      setCategoriesInv(prev => [...prev, row].sort((a, b) =>
        b.is_global - a.is_global || a.nom.localeCompare(b.nom)));
      setShowNewCatInv(false); setNewCatInvNom(''); setErr(null);
    } catch (e) { setErr(e.message || 'Erreur'); }
  };
  const renameCatInv = async (id, nom) => {
    if (!nom.trim()) return;
    try {
      await api.put(`/categories-inv/${id}`, { nom: nom.trim() });
      setCategoriesInv(prev => prev.map(c => c.id === id ? { ...c, nom: nom.trim() } : c));
      setEditingCatInv(null);
    } catch (e) { setErr(e.message || 'Erreur'); }
  };
  const delCatInv = async (id) => {
    try {
      await api.del(`/categories-inv/${id}`);
      setCategoriesInv(prev => prev.filter(c => c.id !== id));
      if (selectedCatInv?.id === id) setSelectedCatInv(null);
    } catch (e) { setErr(e.message || 'Erreur'); }
  };


  const globalCats  = categoriesInv.filter(c => c.is_global);
  const privateCats = categoriesInv.filter(c => !c.is_global);

  return (
<div>
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
    <h3 style={{ margin: 0 }}>Mes catégories d'investissement</h3>
  </div>
  {err && <div className="error" style={{ marginBottom: 12 }}>{err}</div>}

  {/* Accordéon — Catégories globalement définies */}
  <div className="card" style={{ marginBottom: 10 }}>
    <button type="button"
      onClick={() => setCatGlobalOpen(o => !o)}
      style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'none', border: 'none', cursor: 'pointer', padding: 0, color: 'var(--text)' }}>
      <span style={{ fontWeight: 600, fontSize: 'var(--fs-base)' }}>
        Catégories globalement définies
        <span style={{ marginLeft: 8, fontWeight: 400, fontSize: 'var(--fs-sm)', color: 'var(--text-muted)' }}>
          ({globalCats.length})
        </span>
      </span>
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"
        strokeLinecap="round" strokeLinejoin="round"
        style={{ transform: catGlobalOpen ? 'rotate(180deg)' : 'none', transition: 'transform .2s', flexShrink: 0 }}>
        <polyline points="6 9 12 15 18 9"/>
      </svg>
    </button>
    {catGlobalOpen && (
      <div style={{ marginTop: 14 }}>
        <table>
          <thead>
            <tr>
              <th>Nom</th>
              <th className="num">Plateformes</th>
              <th className="num">Investissements</th>
            </tr>
          </thead>
          <tbody>
            {globalCats.length === 0 && (
              <tr><td colSpan={3} className="text-muted" style={{ textAlign: 'center', padding: 24 }}>Aucune catégorie globale</td></tr>
            )}
            {globalCats.map(c => (
              <tr key={c.id}>
                <td><span style={{ fontWeight: 600 }}>{c.nom}</span></td>
                <td className="num">{c.nb_plateformes > 0 ? c.nb_plateformes : <span className="text-muted">—</span>}</td>
                <td className="num">{c.nb_investissements > 0 ? c.nb_investissements : <span className="text-muted">—</span>}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )}
  </div>

  {/* Accordéon — Mes propres catégories */}
  <div className="card">
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <button type="button"
        onClick={() => setCatPrivateOpen(o => !o)}
        style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8,
          background: 'none', border: 'none', cursor: 'pointer', padding: 0, color: 'var(--text)', textAlign: 'left' }}>
        <span style={{ fontWeight: 600, fontSize: 'var(--fs-base)' }}>
          Mes propres catégories
          <span style={{ marginLeft: 8, fontWeight: 400, fontSize: 'var(--fs-sm)', color: 'var(--text-muted)' }}>
            ({privateCats.length})
          </span>
        </span>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"
          strokeLinecap="round" strokeLinejoin="round"
          style={{ transform: catPrivateOpen ? 'rotate(180deg)' : 'none', transition: 'transform .2s', flexShrink: 0 }}>
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>
      {catPrivateOpen && (
        <button className="primary" type="button" style={{ marginLeft: 12, flexShrink: 0 }}
          onClick={() => { setCatPrivateOpen(true); setShowNewCatInv(true); setNewCatInvNom(''); setErr(null); }}>
          + Ajouter
        </button>
      )}
    </div>
    {catPrivateOpen && (
      <div style={{ marginTop: 14 }}>
        {showNewCatInv && (
          <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
            <input autoFocus style={{ flex: 1 }} placeholder="Nom de la catégorie"
              value={newCatInvNom} onChange={e => setNewCatInvNom(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') saveCatInv(newCatInvNom); if (e.key === 'Escape') setShowNewCatInv(false); }} />
            <button className="primary" onClick={() => saveCatInv(newCatInvNom)}>Créer</button>
            <button onClick={() => setShowNewCatInv(false)}>Annuler</button>
          </div>
        )}
        <table>
          <thead>
            <tr>
              <th>Nom</th>
              <th className="num">Plateformes</th>
              <th className="num">Investissements</th>
              <th style={{ width: 80 }}></th>
            </tr>
          </thead>
          <tbody>
            {privateCats.length === 0 && (
              <tr><td colSpan={4} className="text-muted" style={{ textAlign: 'center', padding: 24 }}>Aucune catégorie personnelle</td></tr>
            )}
            {privateCats.map(c => (
              <tr key={c.id}>
                <td>
                  {editingCatInv === c.id ? (
                    <div style={{ display: 'flex', gap: 6 }}>
                      <input autoFocus style={{ flex: 1 }} value={editingNomCatInv}
                        onChange={e => setEditingNomCatInv(e.target.value)}
                        onKeyDown={e => { if (e.key === 'Enter') renameCatInv(c.id, editingNomCatInv); if (e.key === 'Escape') setEditingCatInv(null); }} />
                      <button className="primary" onClick={() => renameCatInv(c.id, editingNomCatInv)}>OK</button>
                      <button onClick={() => setEditingCatInv(null)}>✕</button>
                    </div>
                  ) : (
                    <span style={{ fontWeight: 600 }}>{c.nom}</span>
                  )}
                </td>
                <td className="num">{c.nb_plateformes > 0 ? c.nb_plateformes : <span className="text-muted">—</span>}</td>
                <td className="num">{c.nb_investissements > 0 ? c.nb_investissements : <span className="text-muted">—</span>}</td>
                <td>
                  {editingCatInv !== c.id && (
                    <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                      <button style={{ fontSize: 12, padding: '2px 8px' }}
                        onClick={() => { setEditingCatInv(c.id); setEditingNomCatInv(c.nom); setErr(null); }}>
                        Renommer
                      </button>
                      <button style={{ fontSize: 12, padding: '2px 8px', color: 'var(--danger)', borderColor: 'var(--danger)' }}
                        onClick={() => setConfirmDelete({
                          title: 'Supprimer la catégorie',
                          message: `Supprimer la catégorie "${c.nom}" ? Elle sera retirée de toutes les plateformes et investissements.`,
                          confirmLabel: 'Supprimer',
                          onConfirm: () => { delCatInv(c.id); setConfirmDelete(null); }
                        })}>
                        Supprimer
                      </button>
                    </div>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )}
  </div>
</div>
  );
}
