import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './index.css';

import {
  authService,
  userService,
  questionService,
  answerService,
  partnerService,
  statsService,
  storageService,
  UserProfile,
  Answer
} from './services';

// 1. Attach global services & helper methods to window
(window as any).MatchCodeServices = {
  authService,
  userService,
  questionService,
  answerService,
  partnerService,
  statsService,
  storageService
};

(window as any).firebaseLogin = async (email: string, pass: string) => {
  try {
    const profile = await authService.login(email, pass);
    if (typeof (window as any).showToast === 'function') {
      (window as any).showToast('Erfolgreich eingeloggt!', 'success');
    }
    if (typeof (window as any).navigateTo === 'function') {
      (window as any).navigateTo('dashboard');
    }
    return profile;
  } catch (err: any) {
    console.error('Login error:', err);
    if (typeof (window as any).showToast === 'function') {
      (window as any).showToast(err.message || 'Anmeldung fehlgeschlagen.', 'error');
    }
    throw err;
  }
};

(window as any).firebaseRegister = async (
  email: string,
  pass: string,
  name: string,
  gender: string,
  birthday: string
) => {
  try {
    const profile = await authService.register(email, pass, name, gender, birthday);
    if (typeof (window as any).showToast === 'function') {
      (window as any).showToast('Konto erfolgreich erstellt!', 'success');
    }
    if (typeof (window as any).navigateTo === 'function') {
      (window as any).navigateTo('dashboard');
    }
    return profile;
  } catch (err: any) {
    console.error('Registration error:', err);
    if (typeof (window as any).showToast === 'function') {
      (window as any).showToast(err.message || 'Registrierung fehlgeschlagen.', 'error');
    }
    throw err;
  }
};

(window as any).firebaseLogout = async () => {
  try {
    await authService.logout();
    if (typeof (window as any).showToast === 'function') {
      (window as any).showToast('Erfolgreich abgemeldet.', 'info');
    }
    if (typeof (window as any).navigateTo === 'function') {
      (window as any).navigateTo('landing');
    }
  } catch (err: any) {
    console.error('Logout error:', err);
  }
};

(window as any).firebaseSaveAnswer = async (questionId: string, answerVal: any, whyVal?: string) => {
  const appState = (window as any).appState;
  if (!appState || !appState.currentUser) return;

  try {
    await answerService.saveAnswer(appState.currentUser.id, questionId, answerVal, whyVal || '');
  } catch (err) {
    console.error('Error saving answer to MySQL API:', err);
  }
};

(window as any).firebaseLinkPartner = async (partnerCode: string) => {
  const appState = (window as any).appState;
  if (!appState || !appState.currentUser) return;

  try {
    const targetUser = await partnerService.linkPartnerByCode(appState.currentUser.id, partnerCode);
    const partnerAnswers = await answerService.getUserAnswers(targetUser.uid);

    const existingIdx = appState.partners.findIndex((p: any) => p.id === targetUser.uid);
    const newPartnerObj = {
      id: targetUser.uid,
      name: targetUser.displayName,
      code: targetUser.matchingCode,
      status: 'connected',
      answers: partnerAnswers,
      photoURL: targetUser.photoURL || ''
    };

    if (existingIdx !== -1) {
      appState.partners[existingIdx] = newPartnerObj;
    } else {
      appState.partners.push(newPartnerObj);
    }

    if (typeof (window as any).showToast === 'function') {
      (window as any).showToast(`Erfolgreich mit Partner ${targetUser.displayName} verbunden!`, 'success');
    }
    if (typeof (window as any).renderPartnersView === 'function') {
      (window as any).renderPartnersView();
    }
    if (typeof (window as any).renderDashboardView === 'function') {
      (window as any).renderDashboardView();
    }
  } catch (err: any) {
    console.error('Error linking partner:', err);
    if (typeof (window as any).showToast === 'function') {
      (window as any).showToast(err.message || 'Partner konnte nicht verknüpft werden.', 'error');
    }
  }
};

// 2. Setup Auth state listener
authService.onAuthStateChanged(async (user, profile) => {
  const appState = (window as any).appState;
  const isLoggedIn = !!user;
  const uid = user ? user.uid : 'Keine';
  const isAdmin = !!(profile?.isAdmin || profile?.role === 'admin');

  console.log(
    `AUTH STATUS\n` +
    `Firebase geladen: NEIN (MySQL PHP Backend Mode)\n` +
    `User angemeldet: ${isLoggedIn ? 'JA' : 'NEIN'}\n` +
    `UID: ${uid}\n` +
    `Admin Status: ${isAdmin ? 'JA' : 'NEIN'}`
  );

  if (!appState) return;

  if (user && profile) {
    appState.currentUser = {
      id: profile.uid,
      name: profile.displayName || profile.email.split('@')[0],
      email: profile.email,
      role: profile.isAdmin ? 'admin' : (profile.role || 'user'),
      isAdmin: !!profile.isAdmin,
      gender: profile.gender || 'keine_angabe',
      birthday: profile.birthday || '1995-01-01',
      age: profile.age || 28,
      ageGroup: profile.ageGroup || '25-34',
      matchingCode: profile.matchingCode,
      photoURL: profile.photoURL || ''
    };

    // 1. Fetch Questions
    try {
      const questionsFromDb = await questionService.getQuestions();
      if (questionsFromDb && questionsFromDb.length > 0) {
        appState.questions = questionsFromDb;
      }
    } catch (e) {
      console.error('Error fetching questions:', e);
    }

    // 2. Fetch User Answers
    try {
      const userAnswersDetailed = await answerService.getUserAnswersDetailed(profile.uid);
      appState.answers = {};
      appState.answersWhy = {};

      Object.values(userAnswersDetailed).forEach((ans: Answer) => {
        appState.answers[ans.questionId] = ans.answer;
        if (ans.why) {
          appState.answersWhy[ans.questionId] = ans.why;
        }
      });
    } catch (e) {
      console.error('Error fetching user answers:', e);
    }

    // 3. Fetch Connected Partners and their Answers
    try {
      const connectedPartners = await partnerService.getConnectedPartnerProfiles(profile.uid);
      appState.partners = [];

      for (const item of connectedPartners) {
        const partnerProfile = item.profile;
        const partnerAnswers = await answerService.getUserAnswers(partnerProfile.uid);

        appState.partners.push({
          id: partnerProfile.uid,
          name: partnerProfile.displayName,
          code: partnerProfile.matchingCode,
          status: 'connected',
          answers: partnerAnswers,
          photoURL: partnerProfile.photoURL || ''
        });
      }
    } catch (e) {
      console.error('Error fetching partners:', e);
    }

    // Update UI
    if (typeof (window as any).updateAdminVisibility === 'function') {
      (window as any).updateAdminVisibility();
    }

    if (typeof (window as any).navigateTo === 'function') {
      if (appState.activeView === 'landing' || appState.activeView === 'login' || !appState.activeView) {
        (window as any).navigateTo('dashboard');
      } else if (typeof (window as any).executeActualNavigation === 'function') {
        (window as any).executeActualNavigation(appState.activeView);
      }
    }
  } else {
    appState.currentUser = null;
    appState.partners = [];
    appState.answers = {};
    appState.answersWhy = {};

    if (typeof (window as any).updateAdminVisibility === 'function') {
      (window as any).updateAdminVisibility();
    }
    if (typeof (window as any).navigateTo === 'function') {
      if (appState.activeView !== 'register') {
        (window as any).navigateTo('landing');
      }
    }
  }
});

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <App />
  </StrictMode>,
);
