import React, { useEffect, useState, useRef } from "react";
import * as api from "../api/client";
import useConfigStore from "../stores/useConfigStore";

const formatDate = (dateStr) => {
  if (!dateStr) return "-";
  return new Date(dateStr).toLocaleString("fr-FR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const formatSize = (bytes) => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
};

const SettingsPage = () => {
  const [frontendConfig, setFrontendConfig] = useState(null);
  const [backendConfig, setBackendConfig] = useState(null);
  const [dbInfo, setDbInfo] = useState(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [restoring, setRestoring] = useState(false);
  const [error, setError] = useState(null);
  const [success, setSuccess] = useState(null);
  const fileInputRef = useRef(null);

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

  const loadConfigs = async () => {
    setLoading(true);
    setError(null);
    try {
      const [fe, be, db] = await Promise.all([
        api.fetchFrontendConfig(),
        api.fetchBackendConfig(),
        api.fetchDatabaseInfo().catch(() => null),
      ]);
      setFrontendConfig(fe);
      setBackendConfig(be);
      setDbInfo(db);
    } catch (err) {
      setError("Erreur lors du chargement des configurations: " + err.message);
    } finally {
      setLoading(false);
    }
  };

  const saveFrontendConfig = async () => {
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      const updated = await api.updateFrontendConfig(frontendConfig);
      setFrontendConfig(updated);
      setSuccess("Configuration frontend sauvegardée");
      setTimeout(() => setSuccess(null), 3000);
    } catch (err) {
      setError("Erreur sauvegarde frontend: " + err.message);
    } finally {
      setSaving(false);
    }
  };

  const saveBackendConfig = async () => {
    setSaving(true);
    setError(null);
    setSuccess(null);
    try {
      const updated = await api.updateBackendConfig(backendConfig);
      setBackendConfig(updated);
      setSuccess("Configuration backend sauvegardée");
      setTimeout(() => setSuccess(null), 3000);
    } catch (err) {
      setError("Erreur sauvegarde backend: " + err.message);
    } finally {
      setSaving(false);
    }
  };

  const handleDownloadBackup = () => {
    api.downloadDatabaseBackup();
  };

  const handleRestoreClick = () => {
    fileInputRef.current?.click();
  };

  const handleFileSelect = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.name.endsWith(".db")) {
      setError("Le fichier doit être un fichier .db");
      return;
    }

    if (!confirm("Êtes-vous sûr de vouloir restaurer cette base de données ? Cette action remplacera toutes les données actuelles.")) {
      return;
    }

    setRestoring(true);
    setError(null);
    setSuccess(null);

    try {
      const result = await api.restoreDatabase(file);
      setSuccess(`Base de données restaurée (${formatSize(result.size_bytes)})`);
      // Recharger les infos
      const db = await api.fetchDatabaseInfo();
      setDbInfo(db);
      setTimeout(() => setSuccess(null), 5000);
    } catch (err) {
      setError("Erreur restauration: " + err.message);
    } finally {
      setRestoring(false);
      // Reset l'input file
      e.target.value = "";
    }
  };

  if (loading) {
    return (
      <main className="settings-page">
        <div className="loading-state">
          <i className="fa-solid fa-spinner fa-spin"></i>
          <p>Chargement des configurations...</p>
        </div>
      </main>
    );
  }

  return (
    <main className="settings-page">
      <h2>
        <i className="fa-solid fa-cog"></i> Paramètres
      </h2>

      {error && (
        <div className="error-banner">
          <span>{error}</span>
          <button onClick={() => setError(null)} className="btn-close">
            <i className="fa-solid fa-times"></i>
          </button>
        </div>
      )}

      {success && (
        <div className="success-banner">
          <i className="fa-solid fa-check"></i> {success}
        </div>
      )}

      <div className="settings-grid">
        {/* Section Frontend */}
        <section className="settings-section">
          <div className="section-header">
            <h3>
              <i className="fa-solid fa-desktop"></i> Configuration Frontend
            </h3>
            <span className="version-badge">v{frontendConfig?.versions?.frontend}</span>
          </div>

          {frontendConfig && (
            <div className="settings-form">
              <div className="form-group">
                <label>Thème</label>
                <select
                  value={frontendConfig.ui?.theme || "gruvbox_vintage_dark"}
                  onChange={(e) =>
                    setFrontendConfig({
                      ...frontendConfig,
                      ui: { ...frontendConfig.ui, theme: e.target.value },
                    })
                  }
                >
                  <option value="gruvbox_vintage_dark">Gruvbox Dark</option>
                </select>
              </div>

              <div className="form-group">
                <label>Colonnes (desktop)</label>
                <div className="slider-group">
                  <input
                    type="range"
                    min="1"
                    max="5"
                    value={frontendConfig.ui?.columns_desktop || 3}
                    onChange={(e) =>
                      setFrontendConfig({
                        ...frontendConfig,
                        ui: { ...frontendConfig.ui, columns_desktop: parseInt(e.target.value) },
                      })
                    }
                  />
                  <span className="slider-value">{frontendConfig.ui?.columns_desktop || 3}</span>
                </div>
              </div>

              <div className="form-group">
                <label>Densité des cartes</label>
                <select
                  value={frontendConfig.ui?.card_density || "comfortable"}
                  onChange={(e) =>
                    setFrontendConfig({
                      ...frontendConfig,
                      ui: { ...frontendConfig.ui, card_density: e.target.value },
                    })
                  }
                >
                  <option value="comfortable">Confortable</option>
                  <option value="compact">Compact</option>
                </select>
              </div>

              <div className="form-group">
                <label>Ratio image / infos</label>
                <div className="slider-group">
                  <span className="slider-label-side">Info</span>
                  <input
                    type="range"
                    min="20"
                    max="60"
                    value={frontendConfig.ui?.image_ratio || 40}
                    onChange={(e) => {
                      const ratio = parseInt(e.target.value);
                      setFrontendConfig({
                        ...frontendConfig,
                        ui: { ...frontendConfig.ui, image_ratio: ratio },
                      });
                      // Mise à jour temps réel sans sauvegarde
                      useConfigStore.getState().setImageRatioLocal(ratio);
                    }}
                  />
                  <span className="slider-label-side">Image</span>
                  <span className="slider-value">{frontendConfig.ui?.image_ratio || 40}%</span>
                </div>
                <span className="form-hint">Proportion de l'image dans la vignette produit</span>
              </div>

              <div className="form-group">
                <label>Rafraîchissement auto (secondes)</label>
                <input
                  type="number"
                  min="0"
                  max="3600"
                  value={frontendConfig.ui?.refresh_auto_seconds || 300}
                  onChange={(e) =>
                    setFrontendConfig({
                      ...frontendConfig,
                      ui: { ...frontendConfig.ui, refresh_auto_seconds: parseInt(e.target.value) },
                    })
                  }
                />
                <span className="form-hint">0 = désactivé</span>
              </div>

              <div className="form-group">
                <label>Champs à afficher</label>
                <div className="checkbox-group">
                  {["price", "stock", "ratings", "badges"].map((field) => (
                    <label key={field} className="checkbox-label">
                      <input
                        type="checkbox"
                        checked={frontendConfig.ui?.show_fields?.[field] ?? true}
                        onChange={(e) =>
                          setFrontendConfig({
                            ...frontendConfig,
                            ui: {
                              ...frontendConfig.ui,
                              show_fields: {
                                ...frontendConfig.ui?.show_fields,
                                [field]: e.target.checked,
                              },
                            },
                          })
                        }
                      />
                      {field === "price" && "Prix"}
                      {field === "stock" && "Stock"}
                      {field === "ratings" && "Notes"}
                      {field === "badges" && "Badges"}
                    </label>
                  ))}
                </div>
              </div>

              <button
                className="btn btn-primary"
                onClick={saveFrontendConfig}
                disabled={saving}
              >
                {saving ? (
                  <><i className="fa-solid fa-spinner fa-spin"></i> Sauvegarde...</>
                ) : (
                  <><i className="fa-solid fa-save"></i> Sauvegarder Frontend</>
                )}
              </button>
            </div>
          )}
        </section>

        {/* Section Backend */}
        <section className="settings-section">
          <div className="section-header">
            <h3>
              <i className="fa-solid fa-server"></i> Configuration Backend
            </h3>
            <span className="version-badge">v{backendConfig?.app?.version}</span>
          </div>

          {backendConfig && (
            <div className="settings-form">
              <div className="form-group">
                <label>Environnement</label>
                <select
                  value={backendConfig.app?.env || "dev"}
                  onChange={(e) =>
                    setBackendConfig({
                      ...backendConfig,
                      app: { ...backendConfig.app, env: e.target.value },
                    })
                  }
                >
                  <option value="dev">Développement</option>
                  <option value="prod">Production</option>
                </select>
              </div>

              <div className="form-group">
                <label>Niveau de log</label>
                <select
                  value={backendConfig.app?.log_level || "INFO"}
                  onChange={(e) =>
                    setBackendConfig({
                      ...backendConfig,
                      app: { ...backendConfig.app, log_level: e.target.value },
                    })
                  }
                >
                  <option value="DEBUG">DEBUG</option>
                  <option value="INFO">INFO</option>
                  <option value="WARNING">WARNING</option>
                  <option value="ERROR">ERROR</option>
                </select>
              </div>

              <h4>Scraping</h4>

              <div className="form-group">
                <label>Intervalle scraping (minutes)</label>
                <input
                  type="number"
                  min="5"
                  max="1440"
                  value={backendConfig.scrape?.interval_minutes || 60}
                  onChange={(e) =>
                    setBackendConfig({
                      ...backendConfig,
                      scrape: { ...backendConfig.scrape, interval_minutes: parseInt(e.target.value) },
                    })
                  }
                />
              </div>

              <div className="form-group">
                <label>Mode headless</label>
                <label className="checkbox-label">
                  <input
                    type="checkbox"
                    checked={backendConfig.scrape?.headless ?? true}
                    onChange={(e) =>
                      setBackendConfig({
                        ...backendConfig,
                        scrape: { ...backendConfig.scrape, headless: e.target.checked },
                      })
                    }
                  />
                  Navigateur invisible
                </label>
                <span className="form-hint">Désactiver pour debug manuel</span>
              </div>

              <div className="form-group">
                <label>Timeout (ms)</label>
                <input
                  type="number"
                  min="5000"
                  max="120000"
                  step="1000"
                  value={backendConfig.scrape?.timeout_ms || 30000}
                  onChange={(e) =>
                    setBackendConfig({
                      ...backendConfig,
                      scrape: { ...backendConfig.scrape, timeout_ms: parseInt(e.target.value) },
                    })
                  }
                />
              </div>

              <div className="form-group">
                <label>Délai entre pages (min-max ms)</label>
                <div className="range-inputs">
                  <input
                    type="number"
                    min="500"
                    max="10000"
                    value={backendConfig.scrape?.delay_range_ms?.[0] || 1000}
                    onChange={(e) =>
                      setBackendConfig({
                        ...backendConfig,
                        scrape: {
                          ...backendConfig.scrape,
                          delay_range_ms: [parseInt(e.target.value), backendConfig.scrape?.delay_range_ms?.[1] || 3000],
                        },
                      })
                    }
                  />
                  <span>-</span>
                  <input
                    type="number"
                    min="1000"
                    max="30000"
                    value={backendConfig.scrape?.delay_range_ms?.[1] || 3000}
                    onChange={(e) =>
                      setBackendConfig({
                        ...backendConfig,
                        scrape: {
                          ...backendConfig.scrape,
                          delay_range_ms: [backendConfig.scrape?.delay_range_ms?.[0] || 1000, parseInt(e.target.value)],
                        },
                      })
                    }
                  />
                </div>
              </div>

              <div className="form-group">
                <label>User Agent</label>
                <input
                  type="text"
                  value={backendConfig.scrape?.user_agent || ""}
                  onChange={(e) =>
                    setBackendConfig({
                      ...backendConfig,
                      scrape: { ...backendConfig.scrape, user_agent: e.target.value },
                    })
                  }
                />
              </div>

              <h4>Taxonomie</h4>

              <div className="form-group">
                <label>Catégories disponibles</label>
                <input
                  type="text"
                  value={backendConfig.taxonomy?.categories?.join(", ") || ""}
                  onChange={(e) =>
                    setBackendConfig({
                      ...backendConfig,
                      taxonomy: {
                        ...backendConfig.taxonomy,
                        categories: e.target.value.split(",").map((s) => s.trim()).filter(Boolean),
                      },
                    })
                  }
                />
                <span className="form-hint">Séparées par des virgules</span>
              </div>

              <button
                className="btn btn-primary"
                onClick={saveBackendConfig}
                disabled={saving}
              >
                {saving ? (
                  <><i className="fa-solid fa-spinner fa-spin"></i> Sauvegarde...</>
                ) : (
                  <><i className="fa-solid fa-save"></i> Sauvegarder Backend</>
                )}
              </button>
            </div>
          )}
        </section>

        {/* Section Database Backup */}
        <section className="settings-section">
          <div className="section-header">
            <h3>
              <i className="fa-solid fa-database"></i> Base de données
            </h3>
          </div>

          <div className="settings-form">
            {dbInfo && (
              <div className="db-info">
                <div className="db-info-row">
                  <span className="label">Fichier</span>
                  <span className="value mono">{dbInfo.filename}</span>
                </div>
                <div className="db-info-row">
                  <span className="label">Taille</span>
                  <span className="value">{formatSize(dbInfo.size_bytes)}</span>
                </div>
                <div className="db-info-row">
                  <span className="label">Dernière modification</span>
                  <span className="value">{formatDate(dbInfo.modified_at)}</span>
                </div>
              </div>
            )}

            <div className="db-actions">
              <button
                className="btn btn-primary"
                onClick={handleDownloadBackup}
              >
                <i className="fa-solid fa-download"></i> Télécharger backup
              </button>

              <button
                className="btn btn-secondary"
                onClick={handleRestoreClick}
                disabled={restoring}
              >
                {restoring ? (
                  <><i className="fa-solid fa-spinner fa-spin"></i> Restauration...</>
                ) : (
                  <><i className="fa-solid fa-upload"></i> Restaurer</>
                )}
              </button>

              <input
                ref={fileInputRef}
                type="file"
                accept=".db"
                style={{ display: "none" }}
                onChange={handleFileSelect}
              />
            </div>

            <span className="form-hint">
              La restauration créera automatiquement une sauvegarde de la base actuelle avant de la remplacer.
            </span>
          </div>
        </section>
      </div>
    </main>
  );
};

export default SettingsPage;
