import { useEffect, useState } from 'react';
import { HashRouter, Routes, Route, Navigate, useParams, useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/stores/authStore';
import { useUIStore } from '@/stores/uiStore';
import { useStudentStore } from '@/stores/studentStore';
import { useTimingStore } from '@/stores/timingStore';
import { useAttendanceStore } from '@/stores/attendanceStore';
import { useFeeStore } from '@/stores/feeStore';
import { useSprintRaceStore } from '@/stores/sprintRaceStore';
import { useEquipmentStore } from '@/stores/equipmentStore';
import AppShell from '@/components/layout/AppShell';
import SplashScreen from '@/screens/auth/SplashScreen';
import AdminLoginScreen from '@/screens/auth/AdminLoginScreen';
import AssistantLoginScreen from '@/screens/auth/AssistantLoginScreen';
import StudentLoginScreen from '@/screens/auth/StudentLoginScreen';
import AdminDashboard from '@/screens/dashboard/AdminDashboard';
import AssistantDashboard from '@/screens/dashboard/AssistantDashboard';
import StudentDashboard from '@/screens/student-portal/StudentDashboard';
import StudentListScreen from '@/screens/students/StudentListScreen';
import StudentDetailScreen from '@/screens/students/StudentDetailScreen';
import AssistantStudentDetail from '@/screens/students/AssistantStudentDetail';
import AddStudentScreen from '@/screens/students/AddStudentScreen';
import AttendanceMarkingScreen from '@/screens/attendance/AttendanceMarkingScreen';
import TimingEntryScreen from '@/screens/timing/TimingEntryScreen';
import TimingHistoryScreen from '@/screens/timing/TimingHistoryScreen';
import FeeDashboardScreen from '@/screens/fees/FeeDashboardScreen';
import RecordPaymentScreen from '@/screens/fees/RecordPaymentScreen';
import EquipmentListScreen from '@/screens/equipment/EquipmentListScreen';
import RecordBuyScreen from '@/screens/equipment/RecordBuyScreen';
import RecordSellScreen from '@/screens/equipment/RecordSellScreen';
import SalesDashboardScreen from '@/screens/sales/SalesDashboardScreen';
import MoreMenuScreen from '@/screens/more/MoreMenuScreen';
import AssistantMoreMenu from '@/screens/more/AssistantMoreMenu';
import StudentMoreMenu from '@/screens/student-portal/StudentMoreMenu';
import SettingsScreen from '@/screens/more/SettingsScreen';
import SprintRaceListScreen from '@/screens/sprint/SprintRaceListScreen';
import SprintRaceCreateScreen from '@/screens/sprint/SprintRaceCreateScreen';
import SprintRaceTimerScreen from '@/screens/sprint/SprintRaceTimerScreen';
import SprintRaceDetailScreen from '@/screens/sprint/SprintRaceDetailScreen';
import CoachFeeScreen from '@/screens/fees/CoachFeeScreen';
import ManageCoachesScreen from '@/screens/coaches/ManageCoachesScreen';
import ProfitDashboardScreen from '@/screens/profit/ProfitDashboardScreen';
import AddExpenseScreen from '@/screens/expenses/AddExpenseScreen';
import BatchManagementScreen from '@/screens/batches/BatchManagementScreen';
import { Toaster } from '@/components/ui/sonner';
import { toast } from 'sonner';
import { Lock, ArrowRight } from 'lucide-react';
import type { UserRole } from '@/types';

// ============ SCREENS ============

function AccessDeniedScreen() {
  const navigate = useNavigate();
  return (
    <div className="px-4 pt-4 pb-4 flex flex-col items-center justify-center min-h-[60vh]">
      <div className="w-16 h-16 bg-red-50 rounded-2xl flex items-center justify-center mb-4">
        <Lock className="w-8 h-8 text-red-400" />
      </div>
      <h2 className="text-lg font-bold text-gray-900">Access Denied</h2>
      <p className="text-sm text-gray-400 mt-1 text-center max-w-[260px]">You don't have permission.</p>
      <button onClick={() => navigate(-1)} className="mt-6 px-6 py-2.5 bg-gray-100 text-gray-700 text-sm font-semibold rounded-xl">Go Back</button>
    </div>
  );
}

function PlaceholderScreen({ title, desc }: { title: string; desc?: string }) {
  const navigate = useNavigate();
  return (
    <div className="px-4 pt-4 pb-4 flex flex-col items-center justify-center min-h-[60vh]">
      <div className="w-16 h-16 bg-orange-50 rounded-2xl flex items-center justify-center mb-4"><span className="text-3xl">🚧</span></div>
      <h2 className="text-lg font-bold text-gray-900">{title}</h2>
      <p className="text-sm text-gray-400 mt-1 text-center max-w-[260px]">{desc || 'Coming soon!'}</p>
      <button onClick={() => navigate(-1)} className="mt-6 px-6 py-2.5 brand-gradient text-white text-sm font-semibold rounded-xl">Go Back</button>
    </div>
  );
}

// ============ ADMIN PORTAL PAGE ============
function AdminPortalScreen() {
  const navigate = useNavigate();
  return (
    <div className="min-h-screen bg-gray-50 flex flex-col items-center px-6 py-10">
      <div className="w-full max-w-sm">
        <div className="text-center mb-8">
          <img src="/logo.jpg" alt="Logo" className="w-20 h-auto mx-auto rounded-2xl shadow-xl mb-4" />
          <h1 className="text-2xl font-extrabold text-gray-900">Admin Portal</h1>
          <p className="text-sm text-gray-400 mt-1">Select a login portal</p>
        </div>

        {/* Admin Login */}
        <button onClick={() => navigate('/admin/login')}
          className="w-full brand-gradient rounded-2xl p-5 card-shadow flex items-center gap-4 text-left active:scale-[0.97] transition-transform mb-3">
          <div className="w-14 h-14 bg-white/20 rounded-2xl flex items-center justify-center text-white">
            <Lock className="w-7 h-7" />
          </div>
          <div className="flex-1">
            <h3 className="text-base font-bold text-white">Admin Login</h3>
            <p className="text-xs text-white/70">Full access to all features</p>
          </div>
          <ArrowRight className="w-5 h-5 text-white/60" />
        </button>

        {/* Coach Login */}
        <button onClick={() => navigate('/coach')}
          className="w-full bg-white rounded-2xl p-5 card-shadow flex items-center gap-4 text-left active:scale-[0.97] transition-transform mb-3">
          <div className="w-14 h-14 bg-blue-500 rounded-2xl flex items-center justify-center text-white shadow-md">
            <img src="/icons/coach-icon.png" alt="" className="w-7 h-7" onError={e => (e.currentTarget.style.display = 'none')} />
            <span className="text-xl font-bold">C</span>
          </div>
          <div className="flex-1">
            <h3 className="text-base font-bold text-gray-900">Assistant Coach Portal</h3>
            <p className="text-xs text-gray-400">Attendance, timing & students</p>
          </div>
          <ArrowRight className="w-5 h-5 text-gray-300" />
        </button>

        {/* Student Login */}
        <button onClick={() => navigate('/student')}
          className="w-full bg-white rounded-2xl p-5 card-shadow flex items-center gap-4 text-left active:scale-[0.97] transition-transform">
          <div className="w-14 h-14 bg-emerald-500 rounded-2xl flex items-center justify-center text-white shadow-md">
            <span className="text-xl font-bold">S</span>
          </div>
          <div className="flex-1">
            <h3 className="text-base font-bold text-gray-900">Student Portal</h3>
            <p className="text-xs text-gray-400">View progress & timings</p>
          </div>
          <ArrowRight className="w-5 h-5 text-gray-300" />
        </button>
      </div>
    </div>
  );
}

// ============ LOGIN WRAPPER ============
function LoginWrapper() {
  const { role } = useParams<{ role: string }>();

  if (role === 'admin') return <AdminLoginScreen role="admin" />;
  if (role === 'assistant') return <AssistantLoginScreen role="assistant" />;
  if (role === 'student') return <StudentLoginScreen role="student" />;
  return <Navigate to="/admin" />;
}

// ============ DATA LOADER ============
function DataLoader({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuthStore();
  const { fetchStudents } = useStudentStore();
  const { fetchRecords } = useTimingStore();
  const { fetchRaces } = useSprintRaceStore();
  const { fetchEquipment } = useEquipmentStore();
  const { fetchReceipts, fetchDueList } = useFeeStore();

  useEffect(() => {
    if (isAuthenticated) {
      // Fetch all data from backend on app load
      fetchStudents().catch(() => {});
      fetchRecords().catch(() => {});
      fetchRaces().catch(() => {});
      fetchEquipment().catch(() => {});
      fetchReceipts().catch(() => {});
      fetchDueList().catch(() => {});
    }
  }, [isAuthenticated, fetchStudents, fetchRecords, fetchRaces, fetchEquipment, fetchReceipts, fetchDueList]);

  return <>{children}</>;
}

// ============ TOAST BRIDGE ============
function ToastBridge() {
  const { toast: toastData, clearToast } = useUIStore();
  useEffect(() => {
    if (toastData) { toast[toastData.type](toastData.message); clearToast(); }
  }, [toastData, clearToast]);
  return null;
}

// ============ AUTH GUARD ============
function AuthGuard({ allowedRole, children }: { allowedRole: UserRole; children: React.ReactNode }) {
  const { isAuthenticated, user } = useAuthStore();
  if (!isAuthenticated) return <Navigate to={`/${allowedRole === 'assistant' ? 'coach' : allowedRole}`} />;
  if (user?.role !== allowedRole) return <AccessDeniedScreen />;
  return <>{children}</>;
}

// ============ ADMIN ROUTER ============
function AdminRouter() {
  const { activeScreen } = useUIStore();
  switch (activeScreen) {
    case 'dashboard': return <AdminDashboard />;
    case 'students': return <StudentListScreen />;
    case 'studentDetail': return <StudentDetailScreen />;
    case 'addStudent': return <AddStudentScreen />;
    case 'attendance': return <AttendanceMarkingScreen />;
    case 'timing': return <TimingEntryScreen />;
    case 'timingHistory': return <TimingHistoryScreen />;
    case 'fees': return <FeeDashboardScreen />;
    case 'recordPayment': return <RecordPaymentScreen />;
    case 'dueFees': return <PlaceholderScreen title="Due Fees" />;
    case 'equipment': return <EquipmentListScreen />;
    case 'addEquipment': return <PlaceholderScreen title="Add Equipment" />;
    case 'recordBuy': return <RecordBuyScreen />;
    case 'recordSell': return <RecordSellScreen />;
    case 'sales': return <SalesDashboardScreen />;
    case 'transactions': return <SalesDashboardScreen />;
    case 'reports': return <PlaceholderScreen title="Reports" />;
    case 'more': return <MoreMenuScreen />;
    case 'manageCoaches': return <ManageCoachesScreen />;
    case 'batchManagement': return <BatchManagementScreen />;
    case 'profitDashboard': return <ProfitDashboardScreen />;
    case 'addExpense': return <AddExpenseScreen />;
    case 'settings': return <SettingsScreen />;
    case 'birthdays': return <PlaceholderScreen title="Birthdays" />;
    case 'whatsapp': return <PlaceholderScreen title="WhatsApp" />;
    case 'sprintRaceList': return <SprintRaceListScreen />;
    case 'sprintRaceCreate': return <SprintRaceCreateScreen />;
    case 'sprintRaceTimer': return <SprintRaceTimerScreen />;
    case 'sprintRaceDetail': return <SprintRaceDetailScreen />;
    default: return <AdminDashboard />;
  }
}

// ============ ASSISTANT ROUTER ============
function AssistantRouter() {
  const { activeScreen } = useUIStore();
  switch (activeScreen) {
    case 'dashboard': return <AssistantDashboard />;
    case 'students': return <StudentListScreen />;
    case 'studentDetail': return <AssistantStudentDetail />;
    case 'addStudent': return <AddStudentScreen />;
    case 'attendance': return <AttendanceMarkingScreen />;
    case 'timing': return <TimingEntryScreen />;
    case 'coachFees': return <CoachFeeScreen />;
    case 'settings': return <SettingsScreen />;
    case 'sprintRaceList': return <SprintRaceListScreen />;
    case 'sprintRaceCreate': return <SprintRaceCreateScreen />;
    case 'sprintRaceTimer': return <SprintRaceTimerScreen />;
    case 'sprintRaceDetail': return <SprintRaceDetailScreen />;
    case 'more': return <AssistantMoreMenu />;
    default: return <AssistantDashboard />;
  }
}

// ============ STUDENT ROUTER ============
function StudentRouter() {
  const { activeScreen } = useUIStore();
  switch (activeScreen) {
    case 'dashboard': return <StudentDashboard />;
    case 'studentMessages': return <PlaceholderScreen title="My Messages" desc="Messages from your coach" />;
    case 'timingHistory': return <TimingHistoryScreen />;
    case 'settings': return <SettingsScreen />;
    case 'sprintRaceList': return <SprintRaceListScreen />;
    case 'sprintRaceDetail': return <SprintRaceDetailScreen />;
    case 'more': return <StudentMoreMenu />;
    default: return <StudentDashboard />;
  }
}

// ============ MAIN APP ============
export default function App() {
  const { isAuthenticated, user, checkSession } = useAuthStore();
  const [showSplash, setShowSplash] = useState(true);

  useEffect(() => { checkSession(); }, []);

  return (
    <HashRouter>
      <Routes>
        {/* SPLASH */}
        <Route path="/splash" element={<SplashScreen onComplete={() => setShowSplash(false)} />} />

        {/* ADMIN PORTAL - Can see all logins */}
        <Route path="/admin" element={<AppShell><AdminPortalScreen /><ToastBridge /><Toaster position="top-center" richColors /></AppShell>} />
        <Route path="/admin/login" element={<AppShell><AdminLoginScreen role="admin" /><ToastBridge /><Toaster position="top-center" richColors /></AppShell>} />

        {/* COACH PORTAL - Only coach login, NO admin */}
        <Route path="/coach" element={<AppShell><AssistantLoginScreen role="assistant" /><ToastBridge /><Toaster position="top-center" richColors /></AppShell>} />

        {/* STUDENT PORTAL - Only student login, NO admin/coach */}
        <Route path="/student" element={<AppShell><StudentLoginScreen role="student" /><ToastBridge /><Toaster position="top-center" richColors /></AppShell>} />

        {/* Generic login route */}
        <Route path="/login/:role" element={<AppShell><LoginWrapper /><ToastBridge /><Toaster position="top-center" richColors /></AppShell>} />

        {/* Redirect root to admin */}
        <Route path="/" element={<Navigate to="/admin" />} />

        {/* DASHBOARD ROUTES - Role protected */}
        <Route path="/app/*" element={
          isAuthenticated ? (
            user?.role === 'admin' ? (
              <AppShell><DataLoader><AdminRouter /><ToastBridge /><Toaster position="top-center" richColors /></DataLoader></AppShell>
            ) : user?.role === 'assistant' ? (
              <AppShell><DataLoader><AssistantRouter /><ToastBridge /><Toaster position="top-center" richColors /></DataLoader></AppShell>
            ) : (
              <AppShell><DataLoader><StudentRouter /><ToastBridge /><Toaster position="top-center" richColors /></DataLoader></AppShell>
            )
          ) : (
            <Navigate to="/admin" />
          )
        } />
        <Route path="/timing-history" element={
          isAuthenticated && user?.role === 'student' ? (
            <AppShell><TimingHistoryScreen /><ToastBridge /><Toaster position="top-center" richColors /></AppShell>
          ) : (
            <Navigate to="/student" />
          )
        } />
      </Routes>
    </HashRouter>
  );
}
