// app/admin/page.tsx

"use client";

import React, { useState, useEffect } from 'react';
import { Lock, Unlock, CalendarRange, ClipboardCheck, Users as UsersIcon, Loader2, WifiOff } from 'lucide-react';
import { AppUser } from './adminTypes';
import { useAdminState } from './useAdminState';
import { SetupTab } from './SetupTab';
import { AttendanceTab } from './AttendanceTab';
import { ReportTab } from './ReportTab';

import { verifyLogin } from '../actions/admin';

export default function Admin() {
    const [currentUser, setCurrentUser] = useState<AppUser | null>(null);
    const [isCheckingSession, setIsCheckingSession] = useState(true); // NEW: Prevents login screen flashing

    const [username, setUsername] = useState('');
    const [pin, setPin] = useState('');

    const [isLoading, setIsLoading] = useState(false);
    const [loginError, setLoginError] = useState(false);

    const [activeTab, setActiveTab] = useState<'setup' | 'today' | 'report'>('report');
    const adminState = useAdminState();

    // NEW: Check for a saved session when the app loads
    useEffect(() => {
        const savedSession = localStorage.getItem('kullaberg_admin_session');
        if (savedSession) {
            const user = JSON.parse(savedSession) as AppUser;
            setCurrentUser(user);

            // Set their correct tab based on role
            if (user.role === 'Viewer') setActiveTab('report');
            else if (user.role === 'Staff') setActiveTab('today');
            else setActiveTab('today'); // Admins go to today by default if logged in via session
        }
        setIsCheckingSession(false);
    }, []);

    const handleLogin = async (e: React.SyntheticEvent<HTMLFormElement>) => {
        e.preventDefault();
        setIsLoading(true);
        setLoginError(false);

        const result = await verifyLogin(username, pin);

        if (result.success && result.user) {
            const user = result.user as AppUser;
            setCurrentUser(user);

            // NEW: Save the session to the browser
            localStorage.setItem('kullaberg_admin_session', JSON.stringify(user));

            if (user.role === 'Viewer') setActiveTab('report');
            else if (user.role === 'Staff') setActiveTab('today');
            else setActiveTab(adminState.periods.length > 0 ? 'today' : 'setup');
        } else {
            setPin('');
            setLoginError(true);
        }
        setIsLoading(false);
    };

    const handleLogout = () => {
        setCurrentUser(null);
        setUsername('');
        setPin('');
        localStorage.removeItem('kullaberg_admin_session');
    };

    if (isCheckingSession) {
        return <div className="flex justify-center py-20"><Loader2 className="animate-spin text-slate-teal" size={40} /></div>;
    }

    if (!currentUser) {
        return (
            <div className="flex flex-col items-center justify-center py-20 animate-fade-in px-4">
                <div className="bg-eggshell border-2 border-slate-teal/20 p-8 rounded-2xl shadow-lg w-full max-w-sm text-center">
                    <div className="bg-slate-teal/10 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                        <Lock size={32} className="text-slate-teal" />
                    </div>
                    <h2 className="text-2xl font-black text-ebony uppercase mb-6">Admin Login</h2>

                    <form onSubmit={handleLogin} className="space-y-4 text-left">
                        {/* New Text Input for Username */}
                        <input
                            type="text"
                            value={username}
                            onChange={(e) => { setUsername(e.target.value); setLoginError(false); }}
                            placeholder="Användarnamn"
                            className="w-full bg-eggshell/50 border-2 border-slate-teal/30 text-ebony font-bold p-3 rounded-xl focus:outline-none focus:border-slate-teal"
                        />

                        <input
                            type="password"
                            value={pin}
                            onChange={(e) => { setPin(e.target.value); setLoginError(false); }}
                            placeholder="•••••"
                            className={`w-full bg-eggshell/50 border-2 text-center text-2xl tracking-[0.5em] text-ebony font-mono p-3 rounded-xl focus:outline-none ${loginError ? 'border-emergency/50 bg-emergency/10' : 'border-slate-teal/30 focus:border-slate-teal'}`}
                        />

                        {loginError && <p className="text-emergency text-xs font-bold text-center mt-1">Fel namn eller lösenord.</p>}

                        <button type="submit" disabled={isLoading || !pin || !username} className="w-full bg-slate-teal text-eggshell font-black uppercase py-3 rounded-xl hover:bg-ebony transition-colors disabled:opacity-50">
                            {isLoading ? <Loader2 className="animate-spin mx-auto" /> : 'Logga in'}
                        </button>
                    </form>
                </div>
            </div>
        );
    }

    // Role-based tabs logic that was missing!
    const availableTabs = [];
    if (currentUser.role === 'Admin') {
        availableTabs.push({ id: 'setup', icon: CalendarRange, label: 'Perioder' });
    }
    if (currentUser.role === 'Admin' || currentUser.role === 'Staff') {
        availableTabs.push({ id: 'today', icon: ClipboardCheck, label: 'Närvaro' });
    }
    availableTabs.push({ id: 'report', icon: UsersIcon, label: 'Rapport' });

    return (
        <div className="space-y-8 animate-fade-in w-full">
            <div className="flex justify-between items-end border-b-2 border-slate-teal/20 pb-4">
                <div className="flex flex-col">
                    <h1 className="text-3xl font-black text-slate-teal uppercase flex items-center">
                        <Unlock className="mr-3 text-seafoam" size={28} /> Admin
                    </h1>
                    {/* Display Offline Badge if no internet! */}
                    {adminState.isOffline && (
                        <div className="flex items-center mt-2 text-xs font-bold bg-goldenrod/20 text-goldenrod px-3 py-1 rounded-full w-fit">
                            <WifiOff size={14} className="mr-2" /> Offline Läge (Synkar när nätverk finns)
                        </div>
                    )}
                </div>
                <div className="text-right">
                    <p className="text-xs font-bold text-moss mb-1">Inloggad: {currentUser.name}</p>
                    <button onClick={handleLogout} className="text-sm font-bold text-ebony/60 hover:text-goldenrod">Logga ut</button>
                </div>
            </div>

            {adminState.isLoadingData && adminState.periods.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-20 text-slate-teal">
                    <Loader2 size={48} className="animate-spin mb-4" />
                    <p className="font-bold animate-pulse">Hämtar data...</p>
                </div>
            ) : (
                <>
                    {availableTabs.length > 1 && (
                        <div className="border-b border-slate-teal/20 flex gap-2 overflow-x-auto scrollbar-hide">
                            {availableTabs.map(tab => (
                                <button key={tab.id} onClick={() => setActiveTab(tab.id as any)} className={`flex items-center whitespace-nowrap px-4 py-2.5 rounded-t-lg font-bold text-sm transition-colors border-b-2 ${activeTab === tab.id ? 'bg-slate-teal text-eggshell border-slate-teal' : 'bg-eggshell text-slate-teal border-transparent hover:bg-slate-teal/5'}`}>
                                    <tab.icon size={16} className="mr-2 hidden md:block shrink-0" /> {tab.label}
                                </button>
                            ))}
                        </div>
                    )}

                    {activeTab === 'setup' && currentUser.role === 'Admin' && <SetupTab {...adminState} />}

                    {activeTab === 'today' && (currentUser.role === 'Admin' || currentUser.role === 'Staff') && (
                        <AttendanceTab
                            periods={adminState.periods}
                            attendance={adminState.attendance}
                            setManualAttendance={adminState.setManualAttendance}
                            bulkSetManualAttendance={adminState.bulkSetManualAttendance}
                            addPendingAttendance={adminState.addPendingAttendance}
                            removeAttendanceEntry={adminState.removeAttendanceEntry}
                            activePeriodId={adminState.activePeriodId}
                            setActivePeriodId={adminState.setActivePeriodId}
                        />
                    )}

                    {activeTab === 'report' && (
                        <ReportTab
                            periods={adminState.periods}
                            attendance={adminState.attendance}
                            activePeriodId={adminState.activePeriodId}
                            setActivePeriodId={adminState.setActivePeriodId}
                            currentUserRole={currentUser.role}
                        />
                    )}
                </>
            )}
        </div>
    );
}