'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { toast } from 'sonner';

interface User {
  id: string;
  username: string;
  realName: string;
  email?: string;
  phone?: string;
  role: 'admin' | 'user';
  enterpriseName?: string;
  department?: string;
  lastLoginTime?: string;
}

interface AuthState {
  isAuthenticated: boolean;
  user: User | null;
  token: string | null;
}

interface AuthContextType {
  authState: AuthState;
  login: (username: string, password: string) => Promise<boolean>;
  logout: () => void;
  updateUser: (userData: Partial<User>) => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [authState, setAuthState] = useState<AuthState>({
    isAuthenticated: false,
    user: null,
    token: null,
  });

  // 在组件挂载时检查本地存储的认证信息
  useEffect(() => {
    const token = localStorage.getItem('auth_token');
    const userStr = localStorage.getItem('user_info');

    if (token && userStr) {
      try {
        const user = JSON.parse(userStr);
        setAuthState({
          isAuthenticated: true,
          user,
          token,
        });
      } catch (error) {
        console.error('Failed to parse user info:', error);
        // 清除无效数据
        localStorage.removeItem('auth_token');
        localStorage.removeItem('user_info');
        // 如果数据无效，自动登录默认用户
        autoLoginDefaultUser();
      }
    } else {
      // 如果没有本地存储数据，自动登录默认用户
      autoLoginDefaultUser();
    }
  }, []);

  // 自动登录默认用户
  const autoLoginDefaultUser = () => {
    const defaultUser: User = {
      id: '1',
      username: 'admin',
      realName: '系统管理员',
      email: 'admin@smartagriculture.com',
      phone: '13800138000',
      role: 'admin',
      enterpriseName: '智慧农业科技有限公司',
      department: '技术部',
      lastLoginTime: new Date().toLocaleString('zh-CN'),
    };

    const token = 'mock-jwt-token-default';

    // 保存到本地存储
    localStorage.setItem('auth_token', token);
    localStorage.setItem('user_info', JSON.stringify(defaultUser));

    setAuthState({
      isAuthenticated: true,
      user: defaultUser,
      token,
    });
  };

  const login = async (username: string, password: string): Promise<boolean> => {
    try {
      // 模拟登录请求
      if (username === 'admin' && password === 'admin123') {
        const user: User = {
          id: '1',
          username: 'admin',
          realName: '系统管理员',
          email: 'admin@smartagriculture.com',
          phone: '13800138000',
          role: 'admin',
          enterpriseName: '智慧农业科技有限公司',
          department: '技术部',
          lastLoginTime: new Date().toLocaleString('zh-CN'),
        };

        const token = 'mock-jwt-token-' + Date.now();

        // 保存到本地存储
        localStorage.setItem('auth_token', token);
        localStorage.setItem('user_info', JSON.stringify(user));

        setAuthState({
          isAuthenticated: true,
          user,
          token,
        });

        toast.success('登录成功');
        return true;
      } else {
        toast.error('用户名或密码错误');
        return false;
      }
    } catch (error) {
      console.error('Login error:', error);
      toast.error('登录失败，请重试');
      return false;
    }
  };

  const logout = () => {
    // 清除本地存储
    localStorage.removeItem('auth_token');
    localStorage.removeItem('user_info');

    setAuthState({
      isAuthenticated: false,
      user: null,
      token: null,
    });

    toast.success('已安全退出');
  };

  const updateUser = (userData: Partial<User>) => {
    if (authState.user) {
      const updatedUser = { ...authState.user, ...userData };

      // 更新本地存储
      localStorage.setItem('user_info', JSON.stringify(updatedUser));

      setAuthState(prev => ({
        ...prev,
        user: updatedUser,
      }));
    }
  };

  return (
    <AuthContext.Provider value={{
      authState,
      login,
      logout,
      updateUser,
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}