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

const ICONS_BASE = '/api/icons-files/';

function IconPlus() {
  return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>;
}
function IconUpload() {
  return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>;
}
function IconDownload() {
  return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>;
}
function IconHistory() {
  return <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-4.95"/></svg>;
}

export default function IconsSection() {
  const [icons, setIcons]           = useState([]);
  const [loading, setLoading]       = useState(true);
  const [err, setErr]               = useState(null);
  const [uploading, setUploading]   = useState(null);
  const [history, setHistory]       = useState(null); // { name, rows } | null
  const [creating, setCreating]     = useState(false);
  const [newName, setNewName]       = useState('');
  const [newDesc, setNewDesc]       = useState('');
  const [newFile, setNewFile]       = useState(null);
  const [createErr, setCreateErr]   = useState(null);
  const [createOk, setCreateOk]     = useState(null);

  const load = useCallback(async () => {
    setLoading(true);
    try { setIcons(await api.get('/icons')); }
    catch { setErr('Erreur de chargement'); }
    finally { setLoading(false); }
  }, []);

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

  async function handleReplace(name) {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.svg,.png,.jpg,.jpeg,.webp';
    input.onchange = async () => {
      const file = input.files[0];
      if (!file) return;
      setUploading(name);
      try {
        const fd = new FormData();
        fd.append('file', file);
        const token = localStorage.getItem('cl_token');
        const res = await fetch(`/api/icons/${name}`, {
          method: 'PUT',
          headers: { Authorization: `Bearer ${token}` },
          body: fd,
        });
        if (!res.ok) { const j = await res.json(); throw new Error(j.error); }
        await load();
      } catch (e) { setErr(e.message); }
      finally { setUploading(null); }
    };
    input.click();
  }

  async function loadHistory(name) {
    try {
      const rows = await api.get(`/icons/${name}/history`);
      setHistory({ name, rows });
    } catch { setErr('Erreur historique'); }
  }

  async function handleCreate(e) {
    e.preventDefault();
    setCreateErr(null); setCreateOk(null);
    if (!newName.trim()) return setCreateErr('Nom requis');
    if (!newFile) return setCreateErr('Fichier requis');
    try {
      const fd = new FormData();
      fd.append('name', newName.trim().toLowerCase());
      fd.append('description', newDesc.trim());
      fd.append('file', newFile);
      const token = localStorage.getItem('cl_token');
      const res = await fetch('/api/icons', {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` },
        body: fd,
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error);
      setCreateOk(`Icône "${json.name}" créée.`);
      setNewName(''); setNewDesc(''); setNewFile(null);
      setCreating(false);
      await load();
    } catch (e) { setCreateErr(e.message); }
  }

  if (loading) return <p className="text-muted" style={{ padding: 24 }}>Chargement…</p>;

  return (
    <div>
      <div className="topbar" style={{ marginBottom: 20 }}>
        <div>
          <h2 style={{ margin: 0 }}>Bibliothèque d'icônes</h2>
          <p className="text-muted" style={{ margin: '4px 0 0', fontSize: 'var(--fs-sm)' }}>
            {icons.length} icône{icons.length !== 1 ? 's' : ''} — les noms sont les clés utilisées par l'application.
          </p>
        </div>
        <button className="btn btn-primary" onClick={() => { setCreating(v => !v); setCreateErr(null); setCreateOk(null); }}>
          <IconPlus /> Nouvelle icône
        </button>
      </div>

      {err && <div className="error" style={{ marginBottom: 12 }}>{err}</div>}

      {creating && (
        <div className="card" style={{ marginBottom: 20 }}>
          <h3 style={{ margin: '0 0 14px' }}>Nouvelle association nom / image</h3>
          <form onSubmit={handleCreate}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 12 }}>
              <div>
                <label style={{ display: 'block', fontSize: 'var(--fs-sm)', fontWeight: 600, marginBottom: 4 }}>
                  Nom (slug) *
                </label>
                <input
                  className="form-input"
                  placeholder="ex: taux-defaut"
                  value={newName}
                  onChange={e => setNewName(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))}
                />
                <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>lettres minuscules, chiffres, tirets</span>
              </div>
              <div>
                <label style={{ display: 'block', fontSize: 'var(--fs-sm)', fontWeight: 600, marginBottom: 4 }}>
                  Description
                </label>
                <input
                  className="form-input"
                  placeholder="ex: Taux de défaut"
                  value={newDesc}
                  onChange={e => setNewDesc(e.target.value)}
                />
              </div>
            </div>
            <div style={{ marginBottom: 14 }}>
              <label style={{ display: 'block', fontSize: 'var(--fs-sm)', fontWeight: 600, marginBottom: 4 }}>
                Fichier image * (SVG, PNG, JPG, WebP — 2 Mo max)
              </label>
              <input
                type="file"
                accept=".svg,.png,.jpg,.jpeg,.webp"
                onChange={e => setNewFile(e.target.files[0] || null)}
              />
              {newFile && <span style={{ marginLeft: 8, fontSize: 12, color: 'var(--text-muted)' }}>{newFile.name}</span>}
            </div>
            {createErr && <div className="error" style={{ marginBottom: 8 }}>{createErr}</div>}
            {createOk  && <div className="success" style={{ marginBottom: 8 }}>{createOk}</div>}
            <div style={{ display: 'flex', gap: 8 }}>
              <button type="submit" className="btn btn-primary">Créer</button>
              <button type="button" className="btn btn-secondary" onClick={() => setCreating(false)}>Annuler</button>
            </div>
          </form>
        </div>
      )}

      <div className="icons-grid">
        {icons.map(icon => (
          <div key={icon.name} className="icon-card">
            <div className="icon-card-preview">
              <img
                src={`${ICONS_BASE}${icon.filename}`}
                alt={icon.name}
                style={{ width: 48, height: 48, objectFit: 'contain' }}
              />
            </div>
            <div className="icon-card-body">
              <span className="icon-card-name">{icon.name}</span>
              {icon.description && (
                <span className="icon-card-desc">{icon.description}</span>
              )}
              <span className="icon-card-file">{icon.filename}</span>
            </div>
            <div className="icon-card-actions">
              <button
                className="btn btn-sm btn-secondary"
                onClick={() => handleReplace(icon.name)}
                disabled={uploading === icon.name}
                title="Remplacer l'image"
              >
                {uploading === icon.name ? '…' : <><IconUpload /> Remplacer</>}
              </button>
              <a
                className="btn btn-sm btn-ghost"
                href={`${ICONS_BASE}${icon.filename}`}
                download={icon.filename}
                title="Télécharger le fichier nettoyé"
              >
                <IconDownload />
              </a>
              <button
                className="btn btn-sm btn-ghost"
                onClick={() => history?.name === icon.name ? setHistory(null) : loadHistory(icon.name)}
                title="Historique des versions"
              >
                <IconHistory />
              </button>
            </div>

            {history?.name === icon.name && (
              <div className="icon-history">
                <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--text-muted)' }}>
                  Historique ({history.rows.length} version{history.rows.length !== 1 ? 's' : ''})
                </span>
                {history.rows.length === 0 ? (
                  <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Aucune version précédente</span>
                ) : (
                  <div className="icon-history-list">
                    {history.rows.map(h => (
                      <div key={h.id} className="icon-history-row">
                        <img
                          src={`${ICONS_BASE}${h.filename}`}
                          alt="prev"
                          style={{ width: 28, height: 28, objectFit: 'contain', opacity: .7 }}
                        />
                        <span style={{ fontSize: 11, color: 'var(--text-muted)', flex: 1 }}>{h.filename}</span>
                        <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                          {new Date(h.replaced_at).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
