"use client";

import { useCallback, useEffect, useState } from "react";
import AppShell, { ViewKey, canAccessView } from "@/components/app-shell";
import LoginView from "@/components/login-view";
import DashboardView from "@/components/dashboard-view";
import PaymentView from "@/components/payment-view";
import StudentsView from "@/components/students-view";
import ClassesView from "@/components/classes-view";
import FinanceView from "@/components/finance-view";
import ReportsView from "@/components/reports-view";
import UsersView from "@/components/users-view";
import AuditView from "@/components/audit-view";
import SettingsView from "@/components/settings-view";
import SchoolsView from "@/components/schools-view";
import { apiFetch, getActiveSchoolId, setActiveSchoolId } from "@/lib/client-utils";
import { SchoolSettingsDTO } from "@/lib/types";
import { StructureProvider } from "@/lib/structure-context";
import { Loader2 } from "lucide-react";

interface SessionUser {
  id: string;
  username: string;
  fullName: string;
  role: string;
  schoolId?: string | null;
  allowedViews?: string[] | null;
}

export default function HomePage() {
  const [user, setUser] = useState<SessionUser | null>(null);
  const [settings, setSettings] = useState<SchoolSettingsDTO | null>(null);
  const [bootLoading, setBootLoading] = useState(true);
  const [view, setView] = useState<ViewKey>("dashboard");
  const [refreshKey, setRefreshKey] = useState(0);
  const [preselectedStudent, setPreselectedStudent] = useState<string | null>(null);
  const [paymentKey, setPaymentKey] = useState(0);
  const [announcementsCount, setAnnouncementsCount] = useState(0);

  // جلب الجلسة عند التحميل
  useEffect(() => {
    apiFetch<{ user: SessionUser | null; settings: SchoolSettingsDTO | null }>("/api/auth/me")
      .then((data) => {
        setUser(data.user);
        setSettings(data.settings);
        // مدير النظام العام: ضبط المدرسة الفعالة الافتراضية عند أول دخول
        if (data.user?.role === "SUPER_ADMIN" && !getActiveSchoolId()) {
          apiFetch<{ activeSchoolId: string | null }>("/api/schools")
            .then((d) => {
              if (d.activeSchoolId) setActiveSchoolId(d.activeSchoolId);
            })
            .catch(() => undefined);
        }
        // تنظيف نطاق المدرسة عند خروج آخر جلسة
        if (!data.user) setActiveSchoolId(null);
      })
      .catch(() => setUser(null))
      .finally(() => setBootLoading(false));
  }, []);

  const refreshSettings = useCallback(async () => {
    try {
      const data = await apiFetch<{ settings: SchoolSettingsDTO | null }>("/api/settings");
      setSettings(data.settings);
    } catch {
      /* تجاهل */
    }
  }, []);

  // جلب عدد التنبيهات النشطة لعرضه في جرس الإشعارات
  useEffect(() => {
    if (!user) return;
    apiFetch<{ announcements: unknown[] }>("/api/announcements")
      .then((d) => setAnnouncementsCount(d.announcements.length))
      .catch(() => setAnnouncementsCount(0));
  }, [user, refreshKey]);

  const handleLogout = useCallback(async () => {
    try {
      await apiFetch("/api/auth/logout", { method: "POST" });
    } catch {
      /* تجاهل */
    }
    setUser(null);
    setActiveSchoolId(null);
    setView("dashboard");
  }, []);

  function goPayment(studentId?: string) {
    setPreselectedStudent(studentId ?? null);
    setPaymentKey((k) => k + 1);
    setView("payment");
  }

  function goStudents() {
    setView("students");
  }

  function bumpRefresh() {
    setRefreshKey((k) => k + 1);
  }

  if (bootLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="text-center space-y-3">
          <Loader2 className="w-10 h-10 animate-spin text-primary mx-auto" />
          <p className="text-sm text-muted-foreground">جارٍ تحميل نظام إدارة المدرسة...</p>
        </div>
      </div>
    );
  }

  if (!user) {
    return (
      <LoginView
        onLogin={(u) => {
          setUser(u);
          setView("dashboard");
          refreshSettings();
        }}
        schoolNameAr={settings?.nameAr || "المدرسة الأهلية"}
      />
    );
  }

  // التحقق من صلاحية العرض الحالي (حماية إضافية على مستوى الواجهة، تحترم الصفحات المسموحة)
  const allowed = canAccessView(user, view);
  const effectiveView: ViewKey = allowed ? view : "dashboard";

  return (
    <StructureProvider>
      <AppShell
        user={user}
        settings={settings}
        currentView={effectiveView}
        onViewChange={setView}
        onLogout={handleLogout}
        announcementsCount={announcementsCount}
      >
        {effectiveView === "schools" && user.role === "SUPER_ADMIN" && (
          <SchoolsView onSchoolChanged={bumpRefresh} />
        )}
        {effectiveView === "dashboard" && (
          <DashboardView
            settings={settings}
            userRole={user.role}
            userName={user.fullName}
            refreshKey={refreshKey}
            onGoPayment={() => goPayment()}
            onGoStudents={goStudents}
          />
        )}
        {effectiveView === "payment" && (
          <PaymentView key={paymentKey} settings={settings} onPaymentDone={bumpRefresh} preselectedId={preselectedStudent} />
        )}
        {effectiveView === "students" && (
          <StudentsView
            settings={settings}
            userRole={user.role}
            onStudentsChanged={bumpRefresh}
            onGoPayment={(id) => goPayment(id)}
          />
        )}
        {effectiveView === "classes" && (
          <ClassesView userRole={user.role} onStudentsChanged={bumpRefresh} />
        )}
        {effectiveView === "finance" && (
          <FinanceView
            settings={settings}
            userRole={user.role}
            refreshKey={refreshKey}
            onFinanceChanged={bumpRefresh}
          />
        )}
        {effectiveView === "reports" && <ReportsView settings={settings} userRole={user.role} />}
        {effectiveView === "users" && (user.role === "ADMIN" || user.role === "SUPER_ADMIN") && <UsersView currentUserId={user.id} userRole={user.role} />}
        {effectiveView === "audit" && (user.role === "ADMIN" || user.role === "SUPER_ADMIN") && <AuditView />}
        {effectiveView === "settings" && (user.role === "ADMIN" || user.role === "SUPER_ADMIN") && (
          <SettingsView settings={settings} onSettingsChanged={refreshSettings} />
        )}
      </AppShell>
    </StructureProvider>
  );
}
