import firebase from '../helpers/firebase';
import { useAuthStore } from '../stores/userStore';
import { useGetAllEmails, useGetContacts } from '../api/queries/emailsQueries';
import { useEmailStore } from '../stores/emailsStore';
import { useIsMobile } from '../helpers/mediaQuery';

import MailList from '../components/Mail/MailList';
import ThreadDisplay from '../components/Mail/ThreadDisplay';
import { useEffect, useState } from 'react';
import { getProviderId } from '../helpers/providers';
import MailLabels from '../components/Mail/MailLabels';
import { useParams } from 'react-router-dom';
import { getInboxExcludedLabelsNames } from '../helpers/utils';
import { handleResetSearchQuery } from '../helpers/emails';
import { usePaginationContext } from '../context/Pagination';
import { EMAIL_LABELS } from '../constants/emails';
import { useQueryClient } from '@tanstack/react-query';
import { getWithAuth } from '../api/queries';
import { servicesConfig } from '../config';
import { THREADS_VIEW_MODE } from '../constants/user';

const Email = ({ id }: { id?: string }) => {
  const params = useParams();
  const isMobile = useIsMobile();
  const [currentPage, setCurrentPage] = useState(0);
  const [selectId, setSelectedId] = useState<string | null>();

  const firebaseData: any = firebase;
  const queryClient = useQueryClient();
  const { user, userLoading, userSettings } = useAuthStore();
  const {
    labels,
    pageTokens,
    selectedLabel,
    searchQuery,
    setEmails,
    setContacts,
    setPageTokens,
    setSelectedLabel,
    setSelectedEmailId,
  } = useEmailStore();

  const inboxExcludedLabels = getInboxExcludedLabelsNames();
  const { setCurrentPage: setCurrentPageContext } = usePaginationContext();

  const [isLoading, setIsLoading] = useState(false);
  const [isDraftsLoading, setIsDraftsLoading] = useState(false);

  const isSplitView =
    userSettings?.layout?.threadsViewMode === THREADS_VIEW_MODE.split &&
    !isMobile;

  const exclusionQuery = inboxExcludedLabels
    .map(
      (label) =>
        `-label:${label
          .replaceAll('/', '-')
          .replaceAll(' ', '-')
          .toLowerCase()}`
    )
    .join(' ');

  // Full query string
  const query = `${exclusionQuery}`;
  const label = params.label?.includes('Label_')
    ? params.label
    : (params.label?.toUpperCase() ?? selectedLabel);

  // Build query parameters based on conditions
  const isNotAllMails = label.toLowerCase() !== 'all-mails';
  const hasSearchQuery = searchQuery?.length > 0;
  const isInboxWithExclusions =
    params.label === 'inbox' && inboxExcludedLabels.length > 0;

  const queryParams: any = {
    maxResults: 50,
    currentPage: currentPage,
    pageToken: pageTokens[currentPage] ?? '',
  };

  // Add labelIds for specific labels (not all-mails) when no search query
  if (isNotAllMails && !hasSearchQuery) {
    queryParams.labelIds = [label];
  }

  // Add query for search or inbox exclusions
  if (hasSearchQuery) {
    queryParams.query = searchQuery;
  } else if (isInboxWithExclusions) {
    queryParams.query = query;
  }

  const {
    data: emails,
    isLoading: isEmailsLoading,
    error: emailsError,
  }: any = useGetAllEmails(
    firebaseData?.currentUser?.accessToken,
    getProviderId(user),
    queryParams
  );

  const { data: contactsData, error: contactsError }: any = useGetContacts(
    firebaseData?.currentUser?.accessToken,
    getProviderId(user)
  );

  // Log errors for debugging on mobile
  useEffect(() => {
    if (emailsError) {
      console.error('Error loading emails:', emailsError);
    }
    if (contactsError) {
      console.error('Error loading contacts:', contactsError);
    }
  }, [emailsError, contactsError]);

  useEffect(() => {
    if (params.label && labels?.length) {
      const unreadThreadsCount =
        labels.find(
          (label: any) => label.id.toLowerCase() === params.label?.toLowerCase()
        )?.threadsUnread || 0;

      let labelName = labels.find(
        (label: any) => label.id.toLowerCase() === params.label?.toLowerCase()
      )?.name;

      if (labelName?.includes('[Maxwel]/AI/')) {
        labelName = labelName.replace('[Maxwel]/AI/', '');
      }

      if (params.label === 'all-mails') {
        labelName = 'All Mails';
      }

      // capitalize
      labelName = labelName?.toLowerCase();
      labelName = labelName
        ?.split(' ')
        ?.map((word: string) => word.charAt(0).toUpperCase() + word.slice(1))
        ?.join(' ');

      if (unreadThreadsCount > 0) {
        document.title = `${labelName} (${unreadThreadsCount})`;
      } else {
        document.title = labelName;
      }
    }

    return () => {
      document.title = 'Maxwel AI';
    };
  }, [params.label, labels]);

  useEffect(() => {
    if (label === EMAIL_LABELS.DRAFT && user) {
      async function fetchDrafts() {
        const providerId = getProviderId(user);
        const idToken = firebaseData?.currentUser?.accessToken;
        const queryKey = ['all-drafts', idToken, providerId];

        setIsDraftsLoading(true);

        await queryClient
          .fetchQuery({
            queryKey,
            queryFn: () =>
              getWithAuth(
                `${servicesConfig.backend}/providers/${providerId}/emails/drafts`,
                idToken
              ),
          })
          .finally(() => {
            setIsDraftsLoading(false);
          });
      }

      fetchDrafts();
    }
  }, [label, user]);

  useEffect(() => {
    if (contactsData?.contacts) setContacts(contactsData.contacts ?? []);
  }, [contactsData]);

  useEffect(() => {
    setPageTokens('', 0);
    setCurrentPage(0);
  }, [user, firebaseData.currentUser, getProviderId(user)]);

  useEffect(() => {
    setEmails(emails ?? []);
    if (emails?.nextPageToken && pageTokens.length === currentPage + 1) {
      setPageTokens(emails.nextPageToken, currentPage + 1);
    }
  }, [emails, currentPage]);

  useEffect(() => {
    setSelectedLabel(label);
    setSelectedId(params.id);
    setSelectedEmailId(params.id ?? null);
  }, [params]);

  useEffect(() => {
    return () => {
      setCurrentPage(0);
      setCurrentPageContext?.(0);
      handleResetSearchQuery();
      setSelectedEmailId(null);
      setSelectedLabel(EMAIL_LABELS.INBOX);
    };
  }, []);

  useEffect(() => {
    setIsLoading(isEmailsLoading || userLoading || isDraftsLoading);
  }, [isEmailsLoading, userLoading, isDraftsLoading]);

  return (
    <div className="email" id={id}>
      {!isMobile && <MailLabels setCurrentPage={setCurrentPage} />}
      {(isSplitView || !selectId) && (
        <MailList
          isLoading={isLoading}
          onEmailsPaginationChange={(page) => {
            if (page < 0 || page > pageTokens.length - 1) return;
            setCurrentPage(page);
          }}
          setCurrentPage={setCurrentPage}
        />
      )}
      {(isSplitView || selectId) && <ThreadDisplay isLoading={isLoading} />}
    </div>
  );
};

export default Email;
