import React, { useState, useEffect } from 'react';
import { doc, getDoc, setDoc } from 'firebase/firestore';
import { db, handleFirestoreError, OperationType } from '../firebase';
import { useAuth } from '../components/AuthContext';
import { AppSettings, DEFAULT_SETTINGS } from '../types';
import { Save, Plus, Trash2, Settings as SettingsIcon, Download, Upload } from 'lucide-react';

export default function Settings() {
  const { user } = useAuth();
  const [settings, setSettings] = useState<AppSettings>(DEFAULT_SETTINGS);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);

  useEffect(() => {
    if (!user) return;

    const fetchSettings = async () => {
      try {
        const docRef = doc(db, 'settings', user.uid);
        const docSnap = await getDoc(docRef);
        if (docSnap.exists()) {
          setSettings(docSnap.data() as AppSettings);
        }
      } catch (err) {
        handleFirestoreError(err, OperationType.GET, `settings/${user.uid}`);
      } finally {
        setLoading(false);
      }
    };

    fetchSettings();
  }, [user]);

  const handleSave = async () => {
    if (!user) return;
    setSaving(true);
    setMessage(null);

    try {
      // Filter out empty categories
      const cleanedSettings = {
        ...settings,
        categories: settings.categories.filter(c => c.trim() !== '')
      };
      
      if (cleanedSettings.categories.length === 0) {
        cleanedSettings.categories = ['Général']; // Fallback
      }

      await setDoc(doc(db, 'settings', user.uid), cleanedSettings);
      setSettings(cleanedSettings);
      setMessage({ type: 'success', text: 'Paramètres enregistrés avec succès.' });
    } catch (err) {
      handleFirestoreError(err, OperationType.WRITE, `settings/${user.uid}`);
      setMessage({ type: 'error', text: 'Erreur lors de l\'enregistrement des paramètres.' });
    } finally {
      setSaving(false);
    }
  };

  const handleCategoryChange = (index: number, value: string) => {
    const newCategories = [...settings.categories];
    newCategories[index] = value;
    setSettings({ ...settings, categories: newCategories });
  };

  const addCategory = () => {
    if (settings.categories.length >= 20) return;
    setSettings({ ...settings, categories: [...settings.categories, 'Nouvelle catégorie'] });
  };

  const removeCategory = (index: number) => {
    if (settings.categories.length <= 1) return;
    const newCategories = settings.categories.filter((_, i) => i !== index);
    setSettings({ ...settings, categories: newCategories });
  };

  const handleExport = () => {
    const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(settings, null, 2));
    const downloadAnchorNode = document.createElement('a');
    downloadAnchorNode.setAttribute("href", dataStr);
    downloadAnchorNode.setAttribute("download", "settings.json");
    document.body.appendChild(downloadAnchorNode);
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
  };

  const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const content = e.target?.result as string;
        const parsed = JSON.parse(content);
        
        if (parsed && typeof parsed === 'object') {
          const newSettings = { ...DEFAULT_SETTINGS, ...parsed };
          setSettings(newSettings);
          setMessage({ type: 'success', text: 'Configuration importée avec succès. N\'oubliez pas d\'enregistrer.' });
        } else {
          throw new Error('Format invalide');
        }
      } catch (err) {
        console.error(err);
        setMessage({ type: 'error', text: 'Erreur lors de l\'importation du fichier JSON.' });
      }
    };
    reader.readAsText(file);
    event.target.value = '';
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="flex items-center justify-between mb-8">
        <div className="flex items-center">
          <SettingsIcon className="h-8 w-8 text-indigo-600 mr-3" />
          <h1 className="text-3xl font-extrabold text-gray-900">Paramètres de génération</h1>
        </div>
        <div className="flex space-x-3">
          <button
            onClick={handleExport}
            className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            <Download className="h-4 w-4 mr-2" />
            Exporter
          </button>
          <label className="inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 cursor-pointer">
            <Upload className="h-4 w-4 mr-2" />
            Importer
            <input type="file" className="hidden" accept=".json" onChange={handleImport} />
          </label>
        </div>
      </div>

      {message && (
        <div className={`mb-6 p-4 rounded-md ${message.type === 'success' ? 'bg-green-50 text-green-800 border border-green-200' : 'bg-red-50 text-red-800 border border-red-200'}`}>
          {message.text}
        </div>
      )}

      <div className="bg-white shadow overflow-hidden sm:rounded-lg border border-gray-200">
        <div className="px-4 py-5 sm:p-6 space-y-6">
          
          <div>
            <label htmlFor="theme" className="block text-sm font-medium text-gray-700">
              Thème de la recherche
            </label>
            <div className="mt-1">
              <input
                type="text"
                id="theme"
                className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md py-2 px-3 border"
                value={settings.theme}
                onChange={(e) => setSettings({ ...settings, theme: e.target.value })}
              />
            </div>
            <p className="mt-2 text-sm text-gray-500">
              Le sujet principal pour la recherche d'actualités (ex: Intelligence Artificielle, Cybersécurité, etc.).
            </p>
          </div>

          <div className="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-2">
            <div>
              <label htmlFor="maxAgeDays" className="block text-sm font-medium text-gray-700">
                Ancienneté maximum (jours)
              </label>
              <div className="mt-1">
                <input
                  type="number"
                  id="maxAgeDays"
                  min="1"
                  max="365"
                  className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md py-2 px-3 border"
                  value={settings.maxAgeDays}
                  onChange={(e) => setSettings({ ...settings, maxAgeDays: parseInt(e.target.value) || 7 })}
                />
              </div>
            </div>

            <div>
              <label htmlFor="maxItemsPerCategory" className="block text-sm font-medium text-gray-700">
                Actualités max par catégorie
              </label>
              <div className="mt-1">
                <input
                  type="number"
                  id="maxItemsPerCategory"
                  min="1"
                  max="20"
                  className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md py-2 px-3 border"
                  value={settings.maxItemsPerCategory}
                  onChange={(e) => setSettings({ ...settings, maxItemsPerCategory: parseInt(e.target.value) || 4 })}
                />
              </div>
            </div>
          </div>

          <div>
            <label htmlFor="searchAgentBehavior" className="block text-sm font-medium text-gray-700">
              Comportement de l'agent de recherche
            </label>
            <div className="mt-1">
              <textarea
                id="searchAgentBehavior"
                rows={3}
                className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md py-2 px-3 border"
                value={settings.searchAgentBehavior || ''}
                onChange={(e) => setSettings({ ...settings, searchAgentBehavior: e.target.value })}
                placeholder="Tu peux également utiliser d'autres sources pertinentes trouvées via la recherche Google."
              />
            </div>
            <p className="mt-2 text-sm text-gray-500">
              Personnalisez les instructions données à l'IA concernant sa méthode de recherche.
            </p>
          </div>

          <div>
            <label htmlFor="aiModel" className="block text-sm font-medium text-gray-700">
              Modèle d'IA
            </label>
            <div className="mt-1">
              <select
                id="aiModel"
                name="aiModel"
                className="mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md border"
                value={settings.aiModel || 'gemini-3.1-pro-preview'}
                onChange={(e) => setSettings({ ...settings, aiModel: e.target.value })}
              >
                <option value="gemini-3.1-pro-preview">Gemini 3.1 Pro (conseillé)</option>
                <option value="gemini-3-flash-preview">Gemini 3.0 Flash</option>
                <option value="gemini-3.1-flash-lite-preview">Gemini 3.1 Flash Lite</option>
                <option value="gemini-2.5-flash">Gemini 2.5 Flash</option>
              </select>
            </div>
            <p className="mt-2 text-sm text-gray-500">
              Choisissez le modèle d'IA utilisé pour générer les synthèses. Le modèle Pro est conseillé pour des résultats plus pertinents et une meilleure analyse.
            </p>
          </div>

          <div>
            <div className="flex justify-between items-center mb-4">
              <label className="block text-sm font-medium text-gray-700">
                Catégories d'actualité
              </label>
              <button
                type="button"
                onClick={addCategory}
                disabled={settings.categories.length >= 20}
                className="inline-flex items-center px-3 py-1.5 border border-transparent text-xs font-medium rounded-md text-indigo-700 bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
              >
                <Plus className="h-4 w-4 mr-1" />
                Ajouter
              </button>
            </div>
            <div className="space-y-3">
              {settings.categories.map((category, index) => (
                <div key={index} className="flex items-center gap-2">
                  <span className="text-gray-500 font-medium w-6">{index + 1}.</span>
                  <input
                    type="text"
                    className="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 block w-full sm:text-sm border-gray-300 rounded-md py-2 px-3 border"
                    value={category}
                    onChange={(e) => handleCategoryChange(index, e.target.value)}
                  />
                  <button
                    type="button"
                    onClick={() => removeCategory(index)}
                    disabled={settings.categories.length <= 1}
                    className="p-2 text-red-600 hover:text-red-800 hover:bg-red-50 rounded-md disabled:opacity-50 disabled:cursor-not-allowed"
                    title="Supprimer cette catégorie"
                  >
                    <Trash2 className="h-5 w-5" />
                  </button>
                </div>
              ))}
            </div>
          </div>

        </div>
        <div className="px-4 py-3 bg-gray-50 text-right sm:px-6">
          <button
            onClick={handleSave}
            disabled={saving}
            className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
          >
            {saving ? (
              <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
            ) : (
              <Save className="h-4 w-4 mr-2" />
            )}
            Enregistrer les paramètres
          </button>
        </div>
      </div>
    </div>
  );
}
