import React, { useState } from 'react';
import { CollegeProvider, useCollege } from './context/CollegeContext';
import { Header } from './components/Header';
import { RegistrationFormModal } from './components/RegistrationFormModal';
import { BankPaymentModal } from './components/BankPaymentModal';
import { ReportCardModal } from './components/ReportCardModal';
import { CalendarSyncModal } from './components/CalendarSyncModal';
import { NotificationDrawer } from './components/NotificationDrawer';
import { AuthModal } from './components/AuthModal';

import { AdminDashboard } from './views/AdminDashboard';
import { TeacherDashboard } from './views/TeacherDashboard';
import { StudentDashboard } from './views/StudentDashboard';
import { ParentDashboard } from './views/ParentDashboard';
import { CoursesCatalogView } from './views/CoursesCatalogView';
import { StudyHubView } from './views/StudyHubView';
import { MessagesView } from './views/MessagesView';
import { AcademicsView } from './views/AcademicsView';
import { PhpCodebaseView } from './views/PhpCodebaseView';

import {
  AlertTriangle,
  X,
  CreditCard,
  Building,
  GraduationCap,
  Calendar,
  Phone,
  Mail,
  MapPin,
  CheckCircle2,
} from 'lucide-react';

const MainLayout: React.FC = () => {
  const { currentUser, notifications, fees, isResultsLocked } = useCollege();

  // Navigation State
  const [activeTab, setActiveTab] = useState<string>('dashboard');

  // Modal States
  const [isRegisterOpen, setIsRegisterOpen] = useState(false);
  const [registerPreselectCourse, setRegisterPreselectCourse] = useState<string | undefined>();
  const [isBankPaymentOpen, setIsBankPaymentOpen] = useState(false);
  const [isReportCardOpen, setIsReportCardOpen] = useState(false);
  const [reportCardStudentId, setReportCardStudentId] = useState<string>('STC/2026/ICT-108');
  const [isCalendarSyncOpen, setIsCalendarSyncOpen] = useState(false);
  const [isNotifDrawerOpen, setIsNotifDrawerOpen] = useState(false);
  const [isAuthModalOpen, setIsAuthModalOpen] = useState(false);

  // Urgent Banner Dismissal
  const [dismissUrgentBanner, setDismissUrgentBanner] = useState(false);

  // Check for unread urgent alerts
  const urgentAlert = notifications.find(n => n.type === 'urgent' && !n.read);

  // Fee lock alert for current user if student/parent
  const userStudentId = currentUser.studentId || 'STC/2026/ICT-108';
  const lockStatus = (currentUser.role === 'student' || currentUser.role === 'parent')
    ? isResultsLocked(userStudentId)
    : { isLocked: false, balanceDue: 0 };

  const handleOpenReportCard = (studentId: string) => {
    setReportCardStudentId(studentId);
    setIsReportCardOpen(true);
  };

  const handleOpenRegisterWithCourse = (courseCode?: string) => {
    setRegisterPreselectCourse(courseCode);
    setIsRegisterOpen(true);
  };

  return (
    <div className="min-h-screen bg-slate-100 flex flex-col font-sans text-slate-900 antialiased selection:bg-emerald-500 selection:text-white">
      
      {/* GLOBAL URGENT ALERT BANNER */}
      {urgentAlert && !dismissUrgentBanner && (
        <div className="bg-rose-700 text-white px-4 py-2.5 text-xs font-semibold flex items-center justify-between shadow-sm shrink-0 border-b border-rose-800 animate-in fade-in">
          <div className="flex items-center gap-2 max-w-4xl mx-auto truncate">
            <AlertTriangle className="w-4 h-4 text-amber-300 shrink-0" />
            <span className="font-bold uppercase tracking-wider bg-rose-900 px-2 py-0.5 rounded text-[10px]">
              Urgent Broadcast
            </span>
            <span className="truncate">
              <strong>{urgentAlert.title}:</strong> {urgentAlert.message}
            </span>
          </div>
          <button
            onClick={() => setDismissUrgentBanner(true)}
            className="p-1 hover:bg-rose-800 rounded transition shrink-0 ml-2"
            title="Dismiss"
          >
            <X className="w-4 h-4" />
          </button>
        </div>
      )}

      {/* HEADER COMPONENT (3-zone top bar contract) */}
      <Header
        activeTab={activeTab}
        setActiveTab={setActiveTab}
        onOpenRegisterModal={() => handleOpenRegisterWithCourse()}
        onOpenBankPayment={() => setIsBankPaymentOpen(true)}
        onOpenNotifications={() => setIsNotifDrawerOpen(true)}
        onOpenAuthModal={() => setIsAuthModalOpen(true)}
        onOpenCalendarSync={() => setIsCalendarSyncOpen(true)}
      />

      {/* MAIN CONTENT CONTAINER */}
      <main className="flex-1 max-w-7xl w-full mx-auto p-4 sm:p-6 lg:p-8">
        
        {/* FEE BALANCE NOTICE (For Students/Parents with locked results) */}
        {lockStatus.isLocked && activeTab !== 'courses' && (
          <div className="mb-6 p-4 bg-amber-50 border border-amber-300 rounded-2xl flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs shadow-xs animate-in fade-in">
            <div className="flex items-start sm:items-center gap-3">
              <div className="w-9 h-9 rounded-xl bg-amber-200 text-amber-900 flex items-center justify-center shrink-0">
                <CreditCard className="w-5 h-5" />
              </div>
              <div>
                <strong className="text-amber-950 block text-sm">
                  Action Required: Outstanding Tuition Fee Balance of MK {lockStatus.balanceDue.toLocaleString()} MWK
                </strong>
                <p className="text-slate-600 text-[11px]">
                  Examination results and transcripts remain restricted until payment is cleared into National Bank A/C 1003452219 (Customs Road).
                </p>
              </div>
            </div>

            <button
              onClick={() => setIsBankPaymentOpen(true)}
              className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg text-xs shrink-0 shadow-sm transition flex items-center justify-center gap-1.5"
            >
              <CreditCard className="w-4 h-4" />
              Submit Bank Deposit Slip
            </button>
          </div>
        )}

        {/* VIEW ROUTING */}
        {activeTab === 'dashboard' && (
          <>
            {currentUser.role === 'admin' && (
              <AdminDashboard
                onOpenRegisterModal={() => handleOpenRegisterWithCourse()}
                onOpenCalendarSync={() => setIsCalendarSyncOpen(true)}
                onOpenReportCard={handleOpenReportCard}
              />
            )}
            {currentUser.role === 'teacher' && (
              <TeacherDashboard
                onOpenReportCard={handleOpenReportCard}
                onOpenMessages={() => setActiveTab('messages')}
              />
            )}
            {currentUser.role === 'student' && (
              <StudentDashboard
                onOpenBankPayment={() => setIsBankPaymentOpen(true)}
                onOpenReportCard={handleOpenReportCard}
                onOpenCalendarSync={() => setIsCalendarSyncOpen(true)}
              />
            )}
            {currentUser.role === 'parent' && (
              <ParentDashboard
                onOpenBankPayment={() => setIsBankPaymentOpen(true)}
                onOpenReportCard={handleOpenReportCard}
                onOpenMessages={() => setActiveTab('messages')}
              />
            )}
          </>
        )}

        {activeTab === 'php-codebase' && <PhpCodebaseView />}

        {activeTab === 'academics' && (
          <AcademicsView
            onOpenReportCard={handleOpenReportCard}
            onOpenBankPayment={() => setIsBankPaymentOpen(true)}
          />
        )}

        {activeTab === 'courses' && (
          <CoursesCatalogView
            onOpenRegisterModal={handleOpenRegisterWithCourse}
            onOpenBankPayment={() => setIsBankPaymentOpen(true)}
          />
        )}

        {(activeTab === 'studyhub' || activeTab === 'learning-hub') && <StudyHubView />}

        {activeTab === 'messages' && <MessagesView />}
      </main>

      {/* FOOTER */}
      <footer className="bg-slate-900 text-slate-400 border-t border-slate-800 text-xs py-8 px-4 sm:px-6 lg:px-8 mt-12 shrink-0">
        <div className="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-4 gap-6 pb-6 border-b border-slate-800">
          
          <div className="space-y-2 md:col-span-2">
            <div className="flex items-center gap-2">
              <div className="w-7 h-7 rounded bg-emerald-600 text-white flex items-center justify-center font-bold text-xs">
                STC
              </div>
              <span className="text-white font-bold text-sm tracking-tight">SOCHE TECHNICAL COLLEGE</span>
            </div>
            <p className="text-slate-400 text-xs leading-relaxed max-w-md">
              A public technical college under the Ministry of Labour & Manpower Development, Republic of Malawi. Accredited examining center for ICAM, IOBM, City & Guilds, ABE, ABMA, CIPS, ICM, and NCIC.
            </p>
            <p className="text-[11px] text-emerald-400 font-mono">
              July 2026 Intake • Continuous Education Programmes
            </p>
          </div>

          <div className="space-y-1 text-xs">
            <strong className="text-white block font-semibold uppercase tracking-wider text-[11px]">
              Institutional Contacts
            </strong>
            <p className="flex items-center gap-1.5 text-slate-300">
              <MapPin className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
              Private Bag 515, Limbe, Malawi
            </p>
            <p className="flex items-center gap-1.5 text-slate-300">
              <Phone className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
              +265 1 845 384 / +265 999 123 456
            </p>
            <p className="flex items-center gap-1.5 text-slate-300">
              <Mail className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
              principal@sochetech.org
            </p>
          </div>

          <div className="space-y-1 text-xs">
            <strong className="text-white block font-semibold uppercase tracking-wider text-[11px]">
              Official Bank Account
            </strong>
            <p className="text-slate-300">National Bank of Malawi</p>
            <p className="text-slate-300">Service Centre: <strong>Customs Road</strong></p>
            <p className="font-mono text-emerald-400 font-bold">A/C: 1003452219</p>
            <p className="text-[10px] text-slate-500">Name: Soche Technical College</p>
          </div>
        </div>

        <div className="max-w-7xl mx-auto pt-4 flex flex-col sm:flex-row items-center justify-between gap-2 text-[11px] text-slate-500">
          <p>© 2026 Soche Technical College Management System. All Rights Reserved.</p>
          <div className="flex items-center gap-4">
            <button
              onClick={() => setActiveTab('php-codebase')}
              className="text-blue-400 font-bold hover:underline cursor-pointer"
            >
              📥 Download PHP & MySQL Project
            </button>
            <span className="hover:text-slate-300 cursor-pointer">Security & Encryption Policy</span>
            <span className="hover:text-slate-300 cursor-pointer">Academic Regulations</span>
            <span className="hover:text-slate-300 cursor-pointer">Accounts Clearance Guidelines</span>
          </div>
        </div>
      </footer>

      {/* MODALS & DRAWERS */}
      <RegistrationFormModal
        isOpen={isRegisterOpen}
        onClose={() => {
          setIsRegisterOpen(false);
          setRegisterPreselectCourse(undefined);
        }}
        preselectedCourseCode={registerPreselectCourse}
      />

      <BankPaymentModal
        isOpen={isBankPaymentOpen}
        onClose={() => setIsBankPaymentOpen(false)}
      />

      <ReportCardModal
        isOpen={isReportCardOpen}
        onClose={() => setIsReportCardOpen(false)}
        studentId={reportCardStudentId}
        onOpenBankPayment={() => setIsBankPaymentOpen(true)}
      />

      <CalendarSyncModal
        isOpen={isCalendarSyncOpen}
        onClose={() => setIsCalendarSyncOpen(false)}
      />

      <NotificationDrawer
        isOpen={isNotifDrawerOpen}
        onClose={() => setIsNotifDrawerOpen(false)}
      />

      <AuthModal
        isOpen={isAuthModalOpen}
        onClose={() => setIsAuthModalOpen(false)}
      />
    </div>
  );
};

export default function App() {
  return (
    <CollegeProvider>
      <MainLayout />
    </CollegeProvider>
  );
}
