import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import type { AdminUser } from '@/types';

interface AuthContextType {
  isAuthenticated: boolean;
  user: AdminUser | null;
  login: (username: string, password: string) => boolean;
  logout: () => void;
  updatePassword: (oldPassword: string, newPassword: string) => boolean;
}

const defaultAdmin: AdminUser = {
  username: 'admin',
  password: 'admin123',
  role: 'admin'
};

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

const STORAGE_KEY = 'zlo_admin_auth';
const ADMIN_KEY = 'zlo_admin_user';

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [user, setUser] = useState<AdminUser | null>(null);

  useEffect(() => {
    // Check if admin exists in localStorage, if not create default
    const savedAdmin = localStorage.getItem(ADMIN_KEY);
    if (!savedAdmin) {
      localStorage.setItem(ADMIN_KEY, JSON.stringify(defaultAdmin));
    }

    // Check session
    const session = localStorage.getItem(STORAGE_KEY);
    if (session) {
      try {
        const parsed = JSON.parse(session);
        if (parsed.expires > Date.now()) {
          setIsAuthenticated(true);
          setUser(parsed.user);
        } else {
          localStorage.removeItem(STORAGE_KEY);
        }
      } catch {
        localStorage.removeItem(STORAGE_KEY);
      }
    }
  }, []);

  const login = useCallback((username: string, password: string): boolean => {
    const savedAdmin = localStorage.getItem(ADMIN_KEY);
    if (!savedAdmin) return false;

    try {
      const admin: AdminUser = JSON.parse(savedAdmin);
      if (admin.username === username && admin.password === password) {
        setIsAuthenticated(true);
        setUser(admin);
        
        // Create session (24 hours)
        const session = {
          user: admin,
          expires: Date.now() + 24 * 60 * 60 * 1000
        };
        localStorage.setItem(STORAGE_KEY, JSON.stringify(session));
        return true;
      }
    } catch {
      return false;
    }
    return false;
  }, []);

  const logout = useCallback(() => {
    setIsAuthenticated(false);
    setUser(null);
    localStorage.removeItem(STORAGE_KEY);
  }, []);

  const updatePassword = useCallback((oldPassword: string, newPassword: string): boolean => {
    const savedAdmin = localStorage.getItem(ADMIN_KEY);
    if (!savedAdmin) return false;

    try {
      const admin: AdminUser = JSON.parse(savedAdmin);
      if (admin.password !== oldPassword) {
        return false;
      }

      const updatedAdmin = { ...admin, password: newPassword };
      localStorage.setItem(ADMIN_KEY, JSON.stringify(updatedAdmin));
      
      // Update session
      const session = {
        user: updatedAdmin,
        expires: Date.now() + 24 * 60 * 60 * 1000
      };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(session));
      setUser(updatedAdmin);
      
      return true;
    } catch {
      return false;
    }
  }, []);

  return (
    <AuthContext.Provider value={{
      isAuthenticated,
      user,
      login,
      logout,
      updatePassword
    }}>
      {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;
}
