import React, { createContext, useState, useEffect } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { registerForPushNotificationsAsync } from "../services/NotificationService";

export const AuthContext = createContext();

const STORAGE_KEY_ACCOUNTS = "@ruang_multi_accounts_v2";
const STORAGE_KEY_ACTIVE_ACCOUNT = "@ruang_active_account_email_v2";
const STORAGE_KEY_DOMAINS = "@ruang_multi_domains_v2";
const STORAGE_KEY_ACTIVE_DOMAIN = "@ruang_active_domain_name_v2";

export const AuthProvider = ({ children }) => {
  // Multi-Account Webmail State
  const [accounts, setAccounts] = useState([]);
  const [activeAccount, setActiveAccount] = useState(null);

  // Multi-Domain Manage State
  const [managedDomains, setManagedDomains] = useState([]);
  const [activeDomainSession, setActiveDomainSession] = useState(null);

  const [isLoadingAuth, setIsLoadingAuth] = useState(true);

  useEffect(() => {
    bootstrapAuth();
    registerForPushNotificationsAsync();
  }, []);

  const bootstrapAuth = async () => {
    try {
      // 1. Load Multi Accounts
      const rawAccounts = await AsyncStorage.getItem(STORAGE_KEY_ACCOUNTS);
      const rawActiveEmail = await AsyncStorage.getItem(STORAGE_KEY_ACTIVE_ACCOUNT);
      if (rawAccounts) {
        const parsedAccounts = JSON.parse(rawAccounts);
        setAccounts(parsedAccounts);

        const current =
          parsedAccounts.find((a) => a.email.toLowerCase() === (rawActiveEmail || "").toLowerCase()) ||
          parsedAccounts[0] ||
          null;
        setActiveAccount(current);
      }

      // 2. Load Multi Domains
      const rawDomains = await AsyncStorage.getItem(STORAGE_KEY_DOMAINS);
      const rawActiveDomain = await AsyncStorage.getItem(STORAGE_KEY_ACTIVE_DOMAIN);
      if (rawDomains) {
        const parsedDomains = JSON.parse(rawDomains);
        setManagedDomains(parsedDomains);

        const currentDom =
          parsedDomains.find((d) => d.domain.toLowerCase() === (rawActiveDomain || "").toLowerCase()) ||
          parsedDomains[0] ||
          null;
        setActiveDomainSession(currentDom);
      }
    } catch (err) {
      console.log("Error loading persistent sessions:", err);
    } finally {
      setIsLoadingAuth(false);
    }
  };

  // --- Webmail Multi-Account Actions ---
  const addWebmailAccount = async (email, password, name = "") => {
    const cleanEmail = email.trim().toLowerCase();
    const domain = cleanEmail.split("@")[1] || "";
    const newAcc = {
      email: cleanEmail,
      password,
      name: name.trim() || cleanEmail.split("@")[0],
      domain,
      addedAt: Date.now(),
    };

    const updated = [newAcc, ...accounts.filter((a) => a.email.toLowerCase() !== cleanEmail)];
    setAccounts(updated);
    setActiveAccount(newAcc);

    await AsyncStorage.setItem(STORAGE_KEY_ACCOUNTS, JSON.stringify(updated));
    await AsyncStorage.setItem(STORAGE_KEY_ACTIVE_ACCOUNT, cleanEmail);
  };

  const switchWebmailAccount = async (email) => {
    const found = accounts.find((a) => a.email.toLowerCase() === email.toLowerCase());
    if (found) {
      setActiveAccount(found);
      await AsyncStorage.setItem(STORAGE_KEY_ACTIVE_ACCOUNT, found.email);
    }
  };

  const removeWebmailAccount = async (email) => {
    const updated = accounts.filter((a) => a.email.toLowerCase() !== email.toLowerCase());
    setAccounts(updated);
    await AsyncStorage.setItem(STORAGE_KEY_ACCOUNTS, JSON.stringify(updated));

    if (activeAccount && activeAccount.email.toLowerCase() === email.toLowerCase()) {
      const nextActive = updated[0] || null;
      setActiveAccount(nextActive);
      if (nextActive) {
        await AsyncStorage.setItem(STORAGE_KEY_ACTIVE_ACCOUNT, nextActive.email);
      } else {
        await AsyncStorage.removeItem(STORAGE_KEY_ACTIVE_ACCOUNT);
      }
    }
  };

  // --- Domain Manager Multi-Domain Actions ---
  const addManageDomain = async (domain, password, email = "") => {
    const cleanDomain = domain.trim().toLowerCase();
    const newDom = {
      domain: cleanDomain,
      password,
      email: email.trim().toLowerCase() || `admin@${cleanDomain}`,
      addedAt: Date.now(),
    };

    const updated = [newDom, ...managedDomains.filter((d) => d.domain.toLowerCase() !== cleanDomain)];
    setManagedDomains(updated);
    setActiveDomainSession(newDom);

    await AsyncStorage.setItem(STORAGE_KEY_DOMAINS, JSON.stringify(updated));
    await AsyncStorage.setItem(STORAGE_KEY_ACTIVE_DOMAIN, cleanDomain);
  };

  const switchManageDomain = async (domain) => {
    const found = managedDomains.find((d) => d.domain.toLowerCase() === domain.toLowerCase());
    if (found) {
      setActiveDomainSession(found);
      await AsyncStorage.setItem(STORAGE_KEY_ACTIVE_DOMAIN, found.domain);
    }
  };

  const removeManageDomain = async (domain) => {
    const updated = managedDomains.filter((d) => d.domain.toLowerCase() !== domain.toLowerCase());
    setManagedDomains(updated);
    await AsyncStorage.setItem(STORAGE_KEY_DOMAINS, JSON.stringify(updated));

    if (activeDomainSession && activeDomainSession.domain.toLowerCase() === domain.toLowerCase()) {
      const nextActive = updated[0] || null;
      setActiveDomainSession(nextActive);
      if (nextActive) {
        await AsyncStorage.setItem(STORAGE_KEY_ACTIVE_DOMAIN, nextActive.domain);
      } else {
        await AsyncStorage.removeItem(STORAGE_KEY_ACTIVE_DOMAIN);
      }
    }
  };

  return (
    <AuthContext.Provider
      value={{
        isLoadingAuth,
        // Webmail Multi-Account
        accounts,
        activeAccount,
        addWebmailAccount,
        switchWebmailAccount,
        removeWebmailAccount,
        // Manage Multi-Domain
        managedDomains,
        activeDomainSession,
        addManageDomain,
        switchManageDomain,
        removeManageDomain,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
