import { useState, useEffect } from 'react';
import { useAuthStore } from '@/stores/auth';
import { getSettings, updateSettings, UserSettings } from '../services/settingsService';
import { SettingsTabs } from '../components/SettingsTabs';
import { Button } from '@/components/ui/button';
import { useToast } from '@/hooks/useToast';
import { Save, Loader2 } from 'lucide-react';
import { settingsSchema } from '../schemas/settingsSchema';
import { ZodError } from 'zod';

export function SettingsPage() {
  const { user } = useAuthStore();
  const [settings, setSettings] = useState<UserSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const { toast } = useToast();

  useEffect(() => {
    if (user?.id) {
      loadSettings();
    }
  }, [user?.id]);

  const loadSettings = async () => {
    if (!user?.id) return;
    
    try {
      setLoading(true);
      const data = await getSettings(user.id);
      setSettings(data);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erreur lors du chargement des paramètres';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    if (!user?.id || !settings) return;

    // Valider les settings avec Zod
    try {
      settingsSchema.parse(settings);
    } catch (error) {
      if (error instanceof ZodError) {
        // Afficher les erreurs de validation
        const firstError = error.errors[0];
        const fieldPath = firstError.path.join('.');
        toast.error(`Erreur de validation: ${fieldPath} - ${firstError.message}`);
        return;
      }
      toast.error('Erreur de validation inattendue');
      return;
    }

    try {
      setSaving(true);
      await updateSettings(user.id, settings);
      toast.success('Paramètres sauvegardés avec succès');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Erreur lors de la sauvegarde';
      toast.error(errorMessage);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="max-w-4xl mx-auto p-6 flex items-center justify-center min-h-[400px]">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!settings) {
    return (
      <div className="max-w-4xl mx-auto p-6">
        <div className="text-center text-muted-foreground">
          Erreur de chargement des paramètres
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold mb-2">Paramètres</h1>
        <p className="text-muted-foreground">
          Gérez vos paramètres de compte et préférences
        </p>
      </div>
      
      <SettingsTabs
        settings={settings}
        onChange={setSettings}
      />
      
      <div className="mt-6 flex justify-end">
        <Button onClick={handleSave} disabled={saving}>
          {saving ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Sauvegarde...
            </>
          ) : (
            <>
              <Save className="mr-2 h-4 w-4" />
              Sauvegarder
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

export default SettingsPage;
