import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react';
import { toAppPath } from '@dukang/weixin-sdk';
import { clearAuth, isLoggedIn, request } from '../lib/api';

import type { PartnerMe, PartnerStaffRole } from '@dukang/shared-types';

export type PartnerAccount = PartnerMe & {
  staffRole?: PartnerStaffRole;
};

type PartnerSessionValue = {
  account: PartnerAccount | null;
  loading: boolean;
  loggedIn: boolean;
  refresh: () => Promise<void>;
  logout: () => void;
};

const PartnerSessionContext = createContext<PartnerSessionValue | null>(null);

export function PartnerSessionProvider({ children }: { children: ReactNode }) {
  const [account, setAccount] = useState<PartnerAccount | null>(null);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    if (!isLoggedIn()) {
      setAccount(null);
      setLoading(false);
      return;
    }
    try {
      const data = await request<PartnerAccount>('PARTNER_H5', '/partner/me');
      setAccount(data);
    } catch {
      setAccount(null);
    } finally {
      setLoading(false);
    }
  }, []);

  const logout = useCallback(() => {
    clearAuth();
    setAccount(null);
    window.location.href = toAppPath('/login');
  }, []);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  return (
    <PartnerSessionContext.Provider
      value={{ account, loading, loggedIn: isLoggedIn(), refresh, logout }}
    >
      {children}
    </PartnerSessionContext.Provider>
  );
}

export function usePartnerSession(): PartnerSessionValue {
  const ctx = useContext(PartnerSessionContext);
  if (!ctx) throw new Error('usePartnerSession 必须在 PartnerSessionProvider 内使用');
  return ctx;
}
