import React from 'react'
import { AuthProvider, SignInForm, UserMenu, RequireAuth, RequireRole } from './index'
import { authManager } from './index'

export function AppWithAuth() {
  return (
    <AuthProvider authManager={authManager}>
      <div className="min-h-screen bg-gray-100">
        <nav className="bg-white shadow">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex justify-between h-16">
              <div className="flex items-center">
                <h1 className="text-xl font-semibold">BCT Admin</h1>
              </div>
              <div className="flex items-center">
                <UserMenu />
              </div>
            </div>
          </div>
        </nav>

        <main className="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
          <Dashboard />
        </main>
      </div>
    </AuthProvider>
  )
}

function Dashboard() {
  return (
    <RequireAuth>
      <div className="space-y-6">
        <div className="bg-white shadow rounded-lg p-6">
          <h2 className="text-lg font-medium mb-4">Dashboard</h2>
          <p>Welcome to your dashboard!</p>
        </div>

        <RequireRole role="admin">
          <div className="bg-white shadow rounded-lg p-6">
            <h2 className="text-lg font-medium mb-4">Admin Panel</h2>
            <p>This is only visible to admins.</p>
          </div>
        </RequireRole>

        <RequireRole role="super_admin">
          <div className="bg-white shadow rounded-lg p-6">
            <h2 className="text-lg font-medium mb-4">Super Admin Panel</h2>
            <p>This is only visible to super admins.</p>
          </div>
        </RequireRole>
      </div>
    </RequireAuth>
  )
}

export function LoginPage() {
  return (
    <AuthProvider authManager={authManager}>
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="max-w-md w-full space-y-8">
          <div>
            <h2 className="mt-6 text-center text-3xl font-extrabold text-gray-900">
              Sign in to your account
            </h2>
          </div>
          
          <SignInForm
            onSuccess={() => {
              window.location.href = '/dashboard'
            }}
            onError={(error) => {
              console.error('Login error:', error)
            }}
            className="mt-8"
          />
        </div>
      </div>
    </AuthProvider>
  )
}

export function useAuthExample() {
  const { state, signIn, signOut, hasPermission } = useAuth()

  const handleLogin = async () => {
    try {
      const result = await signIn({
        email: 'user@example.com',
        password: 'password123'
      })
      
      if (result.error) {
        console.error('Login failed:', result.error.message)
      } else {
        console.log('Login successful:', result.user)
      }
    } catch (error) {
      console.error('Login error:', error)
    }
  }

  const handleLogout = async () => {
    try {
      await signOut()
      console.log('Logged out successfully')
    } catch (error) {
      console.error('Logout error:', error)
    }
  }

  return {
    user: state.user,
    isAuthenticated: state.isAuthenticated,
    isLoading: state.isLoading,
    canManageEvents: hasPermission('canManageEvents'),
    canAccessAdminPanel: hasPermission('canAccessAdminPanel'),
    handleLogin,
    handleLogout,
  }
}

export function useApiClientExample() {
  const { createAuthAwareApiClient } = useAuth()
  
  const apiClient = createAuthAwareApiClient(authManager)

  const fetchDashboardStats = async () => {
    try {
      const response = await apiClient.get('/api/dashboard/stats')
      return response.data
    } catch (error) {
      console.error('API error:', error)
      throw error
    }
  }

  const createEvent = async (eventData: any) => {
    try {
      const response = await apiClient.post('/api/events', eventData)
      return response.data
    } catch (error) {
      console.error('API error:', error)
      throw error
    }
  }

  return {
    fetchDashboardStats,
    createEvent,
  }
}