import { useCallback, useEffect, useMemo, useState } from 'react';
import { supabase } from '../lib/supabaseClient';

const normalizeEmail = (value = '') => value.trim().toLowerCase();

const buildDefaultProfile = (email = '') => ({
  firstName: '',
  lastName: '',
  country: '',
  language: 'de',
  testsVisible: false,
  email
});

const mapFromDb = (row, email = '') => ({
  firstName: row?.first_name || '',
  lastName: row?.last_name || '',
  country: row?.country || '',
  language: row?.language || 'de',
  testsVisible: Boolean(row?.tests_visible),
  email
});

const mapToDb = (profile, userId) => ({
  user_id: userId,
  first_name: profile.firstName.trim(),
  last_name: profile.lastName.trim(),
  country: profile.country.trim(),
  language: profile.language || 'de',
  tests_visible: Boolean(profile.testsVisible)
});

export const useUserProfile = (session) => {
  const userId = session?.user?.id || '';
  const sessionEmail = useMemo(() => normalizeEmail(session?.user?.email || ''), [session?.user?.email]);
  const [profile, setProfile] = useState(() => buildDefaultProfile(sessionEmail));
  const [loading, setLoading] = useState(Boolean(userId));
  const [error, setError] = useState('');

  useEffect(() => {
    if (!userId) {
      setProfile(buildDefaultProfile(sessionEmail));
      setLoading(false);
      return;
    }

    setProfile((current) => ({
      ...current,
      email: sessionEmail
    }));
    setLoading(true);
  }, [sessionEmail, userId]);

  const loadProfile = useCallback(async () => {
    if (!supabase || !userId) {
      setProfile(buildDefaultProfile(sessionEmail));
      setLoading(false);
      setError('');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const { data, error: loadError } = await supabase
        .from('user_profiles')
        .select('first_name, last_name, country, language, tests_visible')
        .eq('user_id', userId)
        .maybeSingle();

      if (loadError) throw loadError;

      setProfile(mapFromDb(data, sessionEmail));
    } catch (loadError) {
      setProfile(buildDefaultProfile(sessionEmail));
      setError(loadError.message || 'Profil konnte nicht geladen werden.');
    } finally {
      setLoading(false);
    }
  }, [sessionEmail, userId]);

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

  const saveProfile = useCallback(async (nextValues) => {
    if (!supabase || !userId) {
      return {
        ok: false,
        error: new Error('Supabase ist nicht konfiguriert.')
      };
    }

    const normalizedEmail = normalizeEmail(nextValues.email);
    if (!normalizedEmail) {
      return {
        ok: false,
        error: new Error('Bitte eine gültige E-Mail-Adresse eintragen.')
      };
    }

    try {
      let emailUpdateRequested = false;

      if (normalizedEmail !== sessionEmail) {
        const { error: emailError } = await supabase.auth.updateUser({
          email: normalizedEmail
        });

        if (emailError) throw emailError;
        emailUpdateRequested = true;
      }

      const { data, error: saveError } = await supabase
        .from('user_profiles')
        .upsert(mapToDb(nextValues, userId), { onConflict: 'user_id' })
        .select('first_name, last_name, country, language, tests_visible')
        .single();

      if (saveError) throw saveError;

      const nextProfile = mapFromDb(
        data,
        emailUpdateRequested ? normalizedEmail : sessionEmail
      );

      setProfile(nextProfile);
      setError('');

      const { data: sessionData } = await supabase.auth.getSession();

      return {
        ok: true,
        profile: nextProfile,
        session: sessionData.session,
        emailUpdateRequested
      };
    } catch (saveError) {
      const wrappedError = saveError instanceof Error
        ? saveError
        : new Error(saveError?.message || 'Profil konnte nicht gespeichert werden.');

      setError(wrappedError.message);

      return {
        ok: false,
        error: wrappedError
      };
    }
  }, [sessionEmail, userId]);

  const deleteProfileData = useCallback(async () => {
    if (!supabase || !userId) {
      return {
        ok: false,
        error: new Error('Supabase ist nicht konfiguriert.')
      };
    }

    try {
      const { error: deleteError } = await supabase.rpc('delete_current_user_profile_data');

      if (deleteError) throw deleteError;

      const nextProfile = buildDefaultProfile(sessionEmail);
      setProfile(nextProfile);
      setError('');

      return {
        ok: true,
        profile: nextProfile
      };
    } catch (deleteError) {
      const wrappedError = deleteError instanceof Error
        ? deleteError
        : new Error(deleteError?.message || 'Profil konnte nicht gelöscht werden.');

      setError(wrappedError.message);

      return {
        ok: false,
        error: wrappedError
      };
    }
  }, [sessionEmail, userId]);

  return {
    profile,
    loading,
    error,
    saveProfile,
    deleteProfileData,
    refreshProfile: loadProfile
  };
};
