import { createContext, useContext, useState, ReactNode } from 'react';

interface Admin {
  username: string;
  token: string;
}

interface AdminContextType {
  admin: Admin | null;
  setAdmin: (admin: Admin | null) => void;
  clearAdmin: () => void;
  isAuthenticated: boolean;
}

const AdminContext = createContext<AdminContextType | undefined>(undefined);

export const AdminProvider = ({ children }: { children: ReactNode }) => {
  const [admin, setAdmin] = useState<Admin | null>(() => {
    // 从localStorage恢复管理员信息
    const savedAdmin = localStorage.getItem('survey_admin');
    return savedAdmin ? JSON.parse(savedAdmin) : null;
  });

  const handleSetAdmin = (newAdmin: Admin | null) => {
    setAdmin(newAdmin);
    if (newAdmin) {
      localStorage.setItem('survey_admin', JSON.stringify(newAdmin));
    } else {
      localStorage.removeItem('survey_admin');
    }
  };

  const clearAdmin = () => {
    handleSetAdmin(null);
  };

  const isAuthenticated = !!admin;

  return (
    <AdminContext.Provider value={{ 
      admin, 
      setAdmin: handleSetAdmin, 
      clearAdmin,
      isAuthenticated 
    }}>
      {children}
    </AdminContext.Provider>
  );
};

export const useAdmin = () => {
  const context = useContext(AdminContext);
  if (!context) {
    throw new Error('useAdmin必须在AdminProvider内使用');
  }
  return context;
};