import React, { useState } from 'react';
import { Activity, Database, FolderTree, Link, Shield, Sliders, Wifi } from 'lucide-react';
import { testConnection } from '../utils/api';
import { AppSettings, MQTTProfile, TopicFilter } from '../types';
import { ThemeName, setTheme } from '../utils/theme';

interface SettingsPanelProps {
  settings: AppSettings;
  onSettingsChange: (next: AppSettings) => void;
}

const makeProfile = (): MQTTProfile => ({
  id: `profile-${Date.now()}`,
  name: 'Nouveau profil',
  host: '10.0.0.3',
  port: 1883,
  username: '',
  password: '',
  isDefault: false
});

const makeFilter = (topic: string): TopicFilter => ({
  topic,
  save: false,
  view: false
});

export const SettingsPanel: React.FC<SettingsPanelProps> = ({ settings, onSettingsChange }) => {
  const [testStatus, setTestStatus] = useState<string | null>(null);
  const [bulkTopics, setBulkTopics] = useState('');

  const setProfile = (id: string, patch: Partial<MQTTProfile>) => {
    const next = settings.mqttProfiles.map((profile) =>
      profile.id === id ? { ...profile, ...patch } : profile
    );
    onSettingsChange({ ...settings, mqttProfiles: next });
  };

  const setDefaultProfile = (id: string) => {
    const next = settings.mqttProfiles.map((profile) => ({
      ...profile,
      isDefault: profile.id === id
    }));
    onSettingsChange({ ...settings, mqttProfiles: next, activeProfileId: id });
  };

  const addProfile = () => {
    const nextProfile = makeProfile();
    onSettingsChange({
      ...settings,
      mqttProfiles: [...settings.mqttProfiles, nextProfile],
      activeProfileId: nextProfile.id
    });
  };

  const removeProfile = (id: string) => {
    const remaining = settings.mqttProfiles.filter((profile) => profile.id !== id);
    if (remaining.length === 0) {
      const fresh = makeProfile();
      fresh.isDefault = true;
      onSettingsChange({ ...settings, mqttProfiles: [fresh], activeProfileId: fresh.id });
      return;
    }
    if (!remaining.some((profile) => profile.isDefault)) {
      remaining[0].isDefault = true;
    }
    const activeId = settings.activeProfileId === id ? remaining[0].id : settings.activeProfileId;
    onSettingsChange({ ...settings, mqttProfiles: remaining, activeProfileId: activeId });
  };

  const handleTest = async (profile: MQTTProfile) => {
    const broker = `tcp://${profile.host}:${profile.port}`;
    setTestStatus(`Test ${profile.name}...`);
    try {
      const res = await testConnection(broker);
      if (res.ok) {
        setTestStatus(`${profile.name} OK (${res.latency} ms)`);
      } else {
        setTestStatus(`${profile.name} ${res.error || 'Echec'}`);
      }
    } catch (err) {
      setTestStatus(`${profile.name} Erreur réseau`);
    }
  };

  const handleTheme = (next: ThemeName) => {
    setTheme(next);
    onSettingsChange({ ...settings, theme: next });
  };

  const setFilter = (index: number, patch: Partial<TopicFilter>) => {
    const next = settings.topicFilters.map((entry, idx) =>
      idx === index ? { ...entry, ...patch } : entry
    );
    onSettingsChange({ ...settings, topicFilters: next });
  };

  const addFiltersFromBulk = () => {
    const items = bulkTopics
      .split(/[\n,;]/g)
      .map((entry) => entry.trim())
      .filter(Boolean);
    if (items.length === 0) return;
    const existing = new Set(settings.topicFilters.map((entry) => entry.topic));
    const next = [...settings.topicFilters];
    items.forEach((topic) => {
      if (!existing.has(topic)) {
        next.push(makeFilter(topic));
      }
    });
    onSettingsChange({ ...settings, topicFilters: next });
    setBulkTopics('');
  };

  const removeFilter = (index: number) => {
    const next = settings.topicFilters.filter((_, idx) => idx !== index);
    onSettingsChange({ ...settings, topicFilters: next });
  };

  return (
    <div className="flex flex-col h-full bg-[color:var(--bg-main)] ui-font">
      <div className="p-4 border-b border-[color:var(--border)] bg-[color:var(--bg-panel)]">
        <h2 className="text-sm font-semibold">Paramètres</h2>
      </div>
      <div className="flex-1 overflow-auto p-4 space-y-6 custom-scrollbar">
        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Wifi size={12}/> Profils MQTT</div>
          <div className="space-y-4">
            {settings.mqttProfiles.map((profile) => (
              <div key={profile.id} className="border border-[color:var(--border)] rounded p-3 bg-[color:var(--bg-code)]">
                <div className="flex items-center justify-between mb-2">
                  <input
                    className="bg-transparent text-xs font-semibold w-full"
                    value={profile.name}
                    onChange={(e) => setProfile(profile.id, { name: e.target.value })}
                  />
                  <button
                    className="text-[10px] opacity-60"
                    onClick={() => removeProfile(profile.id)}
                  >
                    Supprimer
                  </button>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <div>
                    <label className="text-xs opacity-70">Serveur</label>
                    <input
                      value={profile.host}
                      onChange={(e) => setProfile(profile.id, { host: e.target.value })}
                      className="w-full bg-[color:var(--bg-panel)] border border-[color:var(--border)] rounded px-3 py-2 text-xs"
                    />
                  </div>
                  <div>
                    <label className="text-xs opacity-70">Port</label>
                    <input
                      type="number"
                      value={profile.port}
                      onChange={(e) => setProfile(profile.id, { port: Number(e.target.value) })}
                      className="w-full bg-[color:var(--bg-panel)] border border-[color:var(--border)] rounded px-3 py-2 text-xs"
                    />
                  </div>
                  <div>
                    <label className="text-xs opacity-70">Utilisateur</label>
                    <input
                      value={profile.username}
                      onChange={(e) => setProfile(profile.id, { username: e.target.value })}
                      className="w-full bg-[color:var(--bg-panel)] border border-[color:var(--border)] rounded px-3 py-2 text-xs"
                    />
                  </div>
                  <div>
                    <label className="text-xs opacity-70">Mot de passe</label>
                    <input
                      type="password"
                      value={profile.password}
                      onChange={(e) => setProfile(profile.id, { password: e.target.value })}
                      className="w-full bg-[color:var(--bg-panel)] border border-[color:var(--border)] rounded px-3 py-2 text-xs"
                    />
                  </div>
                </div>
                <div className="flex items-center gap-3 mt-3 text-xs">
                  <label className="flex items-center gap-2">
                    <input
                      type="radio"
                      checked={profile.isDefault}
                      onChange={() => setDefaultProfile(profile.id)}
                    />
                    Connexion par défaut
                  </label>
                  <button
                    onClick={() => handleTest(profile)}
                    className="px-3 py-1 text-[10px] rounded border border-[color:var(--border)]"
                  >
                    Tester
                  </button>
                  <span className="text-[10px] opacity-60">tcp://{profile.host}:{profile.port}</span>
                </div>
              </div>
            ))}
          </div>
          <button
            onClick={addProfile}
            className="px-3 py-2 text-xs rounded border border-[color:var(--border)]"
          >
            Ajouter un profil
          </button>
          {testStatus && <div className="text-xs opacity-70">{testStatus}</div>}
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Database size={12}/> Historique</div>
          <div className="text-xs opacity-70">TTL actuel : {settings.ttlDays} jours</div>
          <div className="text-xs opacity-50">La purge automatique s'effectue toutes les 10 minutes.</div>
          <label className="flex items-center gap-2 text-xs">
            <input
              type="checkbox"
              checked={settings.autoPurgePayloads}
              onChange={(e) => onSettingsChange({ ...settings, autoPurgePayloads: e.target.checked })}
            />
            Supprimer auto les messages &gt; 
            <input
              type="number"
              value={Math.round(settings.autoPurgePayloadBytes / 1024)}
              onChange={(e) => onSettingsChange({ ...settings, autoPurgePayloadBytes: Number(e.target.value) * 1024 })}
              className="w-20 bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-2 py-1 text-[10px]"
            />
            Ko
          </label>
          <div className="text-[10px] opacity-50">Utile pour filtrer les payloads volumineux (ex: images base64).</div>
          <div className="text-[10px] opacity-50">Auto-purge si la base dépasse 400 Mo : suppression des 25% les plus anciens.</div>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Activity size={12}/> Barre du bas</div>
          <label className="flex flex-col gap-1 text-xs">
            Fréquence d'actualisation (ms)
            <input
              type="number"
              value={settings.statsRefreshMs}
              onChange={(e) => onSettingsChange({ ...settings, statsRefreshMs: Number(e.target.value) })}
              className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-2 py-1"
            />
          </label>
          <div className="text-[10px] opacity-60">Affecte stats DB et résumé $SYS.</div>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Sliders size={12}/> Volets</div>
          <label className="flex flex-col gap-1 text-xs">
            Largeur barre de redimensionnement (px)
            <input
              type="number"
              value={settings.resizeHandlePx}
              onChange={(e) => onSettingsChange({ ...settings, resizeHandlePx: Number(e.target.value) })}
              className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-2 py-1"
            />
          </label>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><FolderTree size={12}/> Topics</div>
          <label className="flex items-center gap-2 text-xs">
            <input
              type="checkbox"
              checked={settings.expandTreeOnStart}
              onChange={(e) => onSettingsChange({ ...settings, expandTreeOnStart: e.target.checked })}
            />
            Ouvrir l'arbre au démarrage
          </label>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Sliders size={12}/> Thème</div>
          <select
            value={settings.theme}
            onChange={(e) => handleTheme(e.target.value as ThemeName)}
            className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-3 py-2 text-xs"
          >
            <option value="dark-monokai">Night</option>
            <option value="light">Day</option>
          </select>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Sliders size={12}/> Surbrillance</div>
          <div className="flex items-center gap-3">
            <input
              type="number"
              value={settings.highlightMs}
              onChange={(e) => onSettingsChange({ ...settings, highlightMs: Number(e.target.value) })}
              className="w-24 bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-3 py-2 text-xs"
            />
            <span className="text-xs opacity-70">ms</span>
          </div>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Sliders size={12}/> Taille police</div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-xs">
            <label className="flex flex-col gap-1">
              UI
              <input
                type="number"
                value={settings.uiFontSize}
                onChange={(e) => onSettingsChange({ ...settings, uiFontSize: Number(e.target.value) })}
                className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-2 py-1"
              />
            </label>
            <label className="flex flex-col gap-1">
              Topics
              <input
                type="number"
                value={settings.topicFontSize}
                onChange={(e) => onSettingsChange({ ...settings, topicFontSize: Number(e.target.value) })}
                className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-2 py-1"
              />
            </label>
            <label className="flex flex-col gap-1">
              Payload
              <input
                type="number"
                value={settings.payloadFontSize}
                onChange={(e) => onSettingsChange({ ...settings, payloadFontSize: Number(e.target.value) })}
                className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-2 py-1"
              />
            </label>
          </div>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Shield size={12}/> Topics ignorés</div>
          <div className="text-xs opacity-70">Liste des topics à ne pas afficher ou sauvegarder.</div>
          <div className="flex gap-2">
            <textarea
              value={bulkTopics}
              onChange={(e) => setBulkTopics(e.target.value)}
              className="flex-1 bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-3 py-2 text-xs h-20"
              placeholder="colle une liste de topics, un par ligne"
            />
            <button
              onClick={addFiltersFromBulk}
              className="px-3 py-2 text-xs rounded border border-[color:var(--border)] h-fit"
            >
              Ajouter
            </button>
          </div>
          <div className="space-y-2">
            {settings.topicFilters.length === 0 && (
              <div className="text-xs opacity-60 italic">Aucun filtre défini.</div>
            )}
            {settings.topicFilters.map((entry, index) => (
              <div key={`${entry.topic}-${index}`} className="flex items-center gap-3 text-xs">
                <input
                  value={entry.topic}
                  onChange={(e) => setFilter(index, { topic: e.target.value })}
                  className="flex-1 bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-2 py-1"
                />
                <label className="flex items-center gap-1">
                  <input
                    type="checkbox"
                    checked={entry.view}
                    onChange={(e) => setFilter(index, { view: e.target.checked })}
                  />
                  view
                </label>
                <label className="flex items-center gap-1">
                  <input
                    type="checkbox"
                    checked={entry.save}
                    onChange={(e) => setFilter(index, { save: e.target.checked })}
                  />
                  save
                </label>
                <button className="text-[10px] opacity-60" onClick={() => removeFilter(index)}>
                  supprimer
                </button>
              </div>
            ))}
          </div>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Shield size={12}/> Sécurité</div>
          <div className="text-xs opacity-70">Mode lecture seule : à venir</div>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Link size={12}/> Liens</div>
          <label className="flex flex-col gap-1 text-xs">
            Lien dépôt
            <input
              value={settings.repoUrl}
              onChange={(e) => onSettingsChange({ ...settings, repoUrl: e.target.value })}
              className="bg-[color:var(--bg-code)] border border-[color:var(--border)] rounded px-3 py-2 text-xs"
            />
          </label>
        </section>

        <section className="space-y-3">
          <div className="flex items-center gap-2 text-xs uppercase tracking-widest opacity-60"><Activity size={12}/> Diagnostic</div>
          <div className="text-xs opacity-70">Logs et stats runtime disponibles via WebSocket.</div>
        </section>
      </div>
      <div className="p-4 border-t border-[color:var(--border)] bg-[color:var(--bg-panel)] text-[10px] opacity-60">
        Sauvegarde automatique dans `settings.yml`.
      </div>
    </div>
  );
};
