/* eslint-disable react-refresh/only-export-components */
import React, { createContext, useCallback, useContext, useRef, useState } from 'react';
import {
  adminLogin as adminLoginApi,
  fetchIgnoreList,
} from '../utils/fileUtils';

const SESSION_KEY = 'mengyanote_admin_token';
const LOGO_CLICK_WINDOW_MS = 2200;
const LOGO_CLICKS_NEEDED = 5;

const AdminContext = createContext(null);

export function AdminProvider({ children, onTreeShouldReload }) {
  const [tokenModalOpen, setTokenModalOpen] = useState(false);
  const [adminPanelOpen, setAdminPanelOpen] = useState(false);
  const [tokenSubmitError, setTokenSubmitError] = useState(null);
  const logoClicksRef = useRef({ count: 0, timer: null });

  const tryOpenAdminWithSession = useCallback(async () => {
    const token = sessionStorage.getItem(SESSION_KEY);
    if (!token) return false;
    try {
      await fetchIgnoreList(token);
      setAdminPanelOpen(true);
      return true;
    } catch {
      sessionStorage.removeItem(SESSION_KEY);
      return false;
    }
  }, []);

  const handleLogoClick = useCallback(() => {
    const r = logoClicksRef.current;
    if (r.timer) {
      clearTimeout(r.timer);
      r.timer = null;
    }
    r.count += 1;
    if (r.count >= LOGO_CLICKS_NEEDED) {
      r.count = 0;
      (async () => {
        const opened = await tryOpenAdminWithSession();
        if (!opened) {
          setTokenSubmitError(null);
          setTokenModalOpen(true);
        }
      })();
      return;
    }
    r.timer = setTimeout(() => {
      r.count = 0;
      r.timer = null;
    }, LOGO_CLICK_WINDOW_MS);
  }, [tryOpenAdminWithSession]);

  const submitToken = useCallback(
    async (token) => {
      setTokenSubmitError(null);
      try {
        await adminLoginApi(token);
        sessionStorage.setItem(SESSION_KEY, token);
        setTokenModalOpen(false);
        setAdminPanelOpen(true);
      } catch (e) {
        setTokenSubmitError(e.message || '验证失败');
      }
    },
    []
  );

  const closeTokenModal = useCallback(() => {
    setTokenModalOpen(false);
    setTokenSubmitError(null);
  }, []);

  const closeAdminPanel = useCallback(() => {
    setAdminPanelOpen(false);
  }, []);

  const logoutAdmin = useCallback(() => {
    sessionStorage.removeItem(SESSION_KEY);
    setAdminPanelOpen(false);
  }, []);

  const getStoredToken = useCallback(() => sessionStorage.getItem(SESSION_KEY), []);

  const notifyIgnoreListChanged = useCallback(() => {
    if (typeof onTreeShouldReload === 'function') {
      onTreeShouldReload();
    }
  }, [onTreeShouldReload]);

  const value = {
    tokenModalOpen,
    adminPanelOpen,
    tokenSubmitError,
    handleLogoClick,
    submitToken,
    closeTokenModal,
    closeAdminPanel,
    logoutAdmin,
    getStoredToken,
    notifyIgnoreListChanged,
  };

  return <AdminContext.Provider value={value}>{children}</AdminContext.Provider>;
}

export function useAdmin() {
  const ctx = useContext(AdminContext);
  if (!ctx) {
    throw new Error('useAdmin must be used within AdminProvider');
  }
  return ctx;
}
