import { useEffect, useState } from "react"
import { Routes, Route, Navigate } from "react-router-dom"
import Navbar from "./components/Navbar.jsx"
import Dashboard from "./components/Dashboard.jsx"
import Login from "./components/Login.jsx"
import Register from "./components/Register.jsx"
import Books from "./components/Books.jsx"
import Borrows from "./components/Borrows.jsx"
import Members from "./components/Members.jsx"

import { Toaster } from "react-hot-toast"
import useStore from "./store.js"

// Protected Route Component - checks authentication AND role
function ProtectedRoute({ children, allowedRoles }) {
  const { isAuthenticated, authRole } = useStore()

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  // If allowedRoles is specified, check the user's role
  if (allowedRoles && !allowedRoles.includes(authRole)) {
    // Redirect students to books page, librarians to dashboard
    if (authRole === 'student') {
      return <Navigate to="/books" replace />
    }
    return <Navigate to="/dashboard" replace />
  }

  return children
}

// Librarian Route - only accessible by librarians
function LibrarianRoute({ children }) {
  const { isAuthenticated, authRole } = useStore()

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  if (authRole !== 'librarian') {
    // Redirect unauthorized users
    if (authRole === 'student') {
      return <Navigate to="/books" replace />
    }
    return <Navigate to="/dashboard" replace />
  }

  return children
}

function App() {
  const { isAuthenticated, checkAuth, authRole } = useStore()
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const init = async () => {
      await checkAuth()
      setLoading(false)
    }
    init()
  }, [])

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-12 h-12 border-4 border-primary-200 border-t-primary-600 rounded-full animate-spin mx-auto mb-4" />
          <p className="text-sm text-gray-500">Loading...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <Toaster
        position="top-right"
        toastOptions={{
          duration: 3000,
          style: {
            background: '#fff',
            color: '#374151',
            borderRadius: '0.75rem',
            boxShadow: '0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1)',
            border: '1px solid #f3f4f6',
            padding: '12px 16px',
            fontSize: '14px',
          },
          success: {
            iconTheme: {
              primary: '#22c55e',
              secondary: '#fff',
            },
          },
          error: {
            iconTheme: {
              primary: '#ef4444',
              secondary: '#fff',
            },
          },
        }}
      />
      <Navbar isAuthenticated={isAuthenticated} authRole={authRole} />
      <Routes>
        <Route path="/" element={<Navigate to="/dashboard" />} />
        <Route path="/login" element={!isAuthenticated ? <Login /> : <Navigate to="/dashboard" />} />
        <Route path="/register" element={!isAuthenticated ? <Register /> : <Navigate to="/dashboard" />} />

        {/* Dashboard - accessible to all authenticated users but shows different content based on role */}
        <Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />

        {/* Books - accessible to all authenticated users */}
        <Route path="/books" element={<ProtectedRoute><Books /></ProtectedRoute>} />

        {/* Borrows - accessible to all authenticated users but with role-based UI */}
        <Route path="/borrows" element={<ProtectedRoute><Borrows /></ProtectedRoute>} />

        {/* Members - librarians only */}
        <Route path="/members" element={<LibrarianRoute><Members /></LibrarianRoute>} />

        {/* Catch all - redirect to dashboard */}
        <Route path="*" element={<Navigate to="/dashboard" />} />
      </Routes>
    </div>
  )
}

export default App