import React, { createContext, useContext, useState, useEffect } from 'react';
import type { ReactNode } from 'react';
import type { User } from '../types';
import { apiService } from '../services/api';

interface AuthContextType {
  user: User | null;
  loading: boolean;
  login: (initData: string) => Promise<boolean>;
  logout: () => void;
  isAuthenticated: boolean;
  isAdmin: boolean;
  updateUser: (userData: Partial<User>) => void;
  deepLinkAction: { type: string; value: string } | null;
  clearDeepLinkAction: () => void;
}

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

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

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [isAdmin, setIsAdmin] = useState(false);
  const [deepLinkAction, setDeepLinkAction] = useState<{ type: string; value: string } | null>(null);

  useEffect(() => {
    const initAuth = async () => {
      if (apiService.isAuthenticated()) {
        try {
          const response = await apiService.getCurrentUser();
          if (response.success && response.data) {
            setUser(response.data);

            // Check admin role
            const adminResponse = await apiService.checkAdminRole();
            if (adminResponse.success && adminResponse.data) {
              setIsAdmin(['admin', 'operator'].includes(adminResponse.data.role));
            }
          } else {
            apiService.clearAuthToken();
          }
        } catch (error) {
          console.error('Auth initialization error:', error);
          apiService.clearAuthToken();
        }
      }
      setLoading(false);
    };

    initAuth();
  }, []);

  const login = async (initData: string): Promise<boolean> => {
    try {
      const response = await apiService.validateTelegramInitData(initData);

      if (response.success) {
        apiService.setTelegramInitData(initData);

        const userResponse = await apiService.getCurrentUser();

        if (userResponse.success && userResponse.data) {
          setUser(userResponse.data);

          // Check admin role
          const adminResponse = await apiService.checkAdminRole();
          if (adminResponse.success && adminResponse.data) {
            setIsAdmin(['admin', 'operator'].includes(adminResponse.data.role));
          }

          // Handle deep link parameters from Telegram Web App
          if (window.Telegram?.WebApp?.initDataUnsafe?.start_param) {
            const startParam = window.Telegram.WebApp.initDataUnsafe.start_param;
            handleDeepLink(startParam);
          }

          return true;
        }
      }
      return false;
    } catch (error) {
      console.error('Login error:', error);
      return false;
    }
  };

  const updateUser = (userData: Partial<User>) => {
    setUser(prev => prev ? { ...prev, ...userData } : null);
  };

  const handleDeepLink = (startParam: string) => {
    // Parse start_param format: "reward_50", "quiz_123", "shop", "reward_789"
    const parts = startParam.split('_');
    const type = parts[0];
    const value = parts.slice(1).join('_');

    if (['reward', 'quiz', 'shop'].includes(type)) {
      setDeepLinkAction({ type, value });
    }
  };

  const clearDeepLinkAction = () => {
    setDeepLinkAction(null);
  };

  const logout = () => {
    apiService.clearAuthToken();
    setUser(null);
    setIsAdmin(false);
    setDeepLinkAction(null);
  };

  const value = {
    user,
    loading,
    login,
    logout,
    isAuthenticated: !!user,
    isAdmin,
    updateUser,
    deepLinkAction,
    clearDeepLinkAction,
  };

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