import { useState, useEffect } from 'react';
import { usePage, Link } from '@inertiajs/react';
import { Head } from '@inertiajs/react';
import {
    BookOpen,
    Clock,
    CheckSquare,
    Calendar,
    ArrowRight,
    Award,
    UserRound,
    AlertCircle,
    Sparkles,
    Trophy,
    LockKeyhole,
    X,
} from 'lucide-react';
import StudentLayout from '@/layouts/StudentLayout';
import WeeklyScheduleCard from '@/components/WeeklyScheduleCard';
import { UpcomingHolidaysWidget, type UpcomingHolidayItem } from '@/components/UpcomingHolidaysWidget';
import ClassGoodNewsTicker from '@/components/ClassGoodNewsTicker';
import ClassRecognitionsModal from '@/components/ClassRecognitionsModal';
import { cn } from '@/lib/utils';
import type { PageProps } from '@/types';

interface StudentDashboardProps extends PageProps {
    stats: {
        totalMaterials: number;
        pendingAssignments: number;
        gradedCount: number;
        attendance: {
            hadir: number;
            sakit: number;
            izin: number;
            alpa: number;
            terlambat: number;
        };
    };
    student: {
        full_name: string;
        nisn: string;
        class_name: string;
    };
    recentMaterials: Array<{
        id: number;
        title: string;
        subject_name: string;
        teacher_name: string;
        published_at: string;
    }>;
    upcomingAssignments: Array<{
        id: number;
        title: string;
        material_id: number;
        subject_name: string;
        due_date: string;
        submission_type: string;
        access_status: 'open' | 'locked' | 'closed';
        opens_at: string | null;
    }>;
    gamification: {
        xp: number;
        level: number;
        rank_title: string;
        xp_required: number;
    };
    bookingSchedule?: any;
    upcomingHolidays?: UpcomingHolidayItem[];
    classGoodNews?: Array<{
        uuid: string;
        type: 'appreciation' | 'achievement';
        title: string;
        recognized_on: string;
        recipients: string[];
        recipient_count: number;
        is_mine: boolean;
    }>;
    studentProfileSummary: {
        percentage: number;
        missing: string[];
        is_complete: boolean;
        status: 'not_started' | 'draft' | 'submitted' | 'verified' | 'revision_requested';
        revision_notes: string | null;
    };
}

export default function Dashboard() {
    const { 
        stats, 
        student,
        recentMaterials,
        upcomingAssignments,
        gamification,
        bookingSchedule,
        upcomingHolidays = [],
        classGoodNews = [],
        studentProfileSummary,
    } = usePage<StudentDashboardProps>().props;

    const studentStatCards = [
        { key: 'totalMaterials', label: 'Materi Tersedia', icon: BookOpen, color: 'text-sky-400', bgHover: 'hover:shadow-sky-500/10' },
        { key: 'pendingAssignments', label: 'Tugas Belum Selesai', icon: Clock, color: 'text-amber-400', bgHover: 'hover:shadow-amber-500/10' },
        { key: 'gradedCount', label: 'Tugas Dinilai', icon: CheckSquare, color: 'text-emerald-400', bgHover: 'hover:shadow-emerald-500/10' },
    ] as const;

    const [isRecognitionsModalOpen, setIsRecognitionsModalOpen] = useState(false);
    const [isBiodataDismissed, setIsBiodataDismissed] = useState(() => {
        try {
            return sessionStorage.getItem('uticlass_dismiss_biodata_prompt') === 'true';
        } catch {
            return false;
        }
    });

    const handleDismissBiodata = (e: React.MouseEvent) => {
        e.preventDefault();
        e.stopPropagation();
        try {
            sessionStorage.setItem('uticlass_dismiss_biodata_prompt', 'true');
        } catch {
            // ignore
        }
        setIsBiodataDismissed(true);
    };

    return (
        <>
            <Head title="Beranda Siswa" />

            {/* Greeting */}
            <div className="mb-5 sm:mb-8 flex flex-col md:flex-row md:items-end justify-between gap-3 sm:gap-4">
                <div className="reveal">
                    <h1 className="text-xl sm:text-3xl font-black bg-linear-to-r from-primary-500 via-teal-400 to-sky-400 bg-clip-text text-transparent mb-1 sm:mb-2">
                        Halo, {student.full_name.split(' ')[0]}! 👋
                    </h1>
                    <p className="mt-0.5 text-text-muted font-medium flex flex-wrap items-center gap-1.5 sm:gap-2">
                        <span className="bg-surface px-2.5 py-0.5 sm:px-3 sm:py-1 rounded-full text-[9px] sm:text-xs shadow-sm ring-1 ring-border/50">Kelas {student.class_name}</span>
                        <span className="bg-surface px-2.5 py-0.5 sm:px-3 sm:py-1 rounded-full text-[9px] sm:text-xs shadow-sm ring-1 ring-border/50">NISN: {student.nisn}</span>
                    </p>
                </div>
                
                {/* Gamification Badge */}
                {gamification && (
                    <div className="glass reveal reveal-delay-1 rounded-xl sm:rounded-2xl p-2.5 sm:p-4 flex items-center gap-2.5 sm:gap-4 border-2 border-primary/20 bg-linear-to-br from-primary-500/5 to-teal-500/5 min-w-[260px] sm:min-w-[300px] hover:scale-[1.02] transition-transform duration-300">
                        <div className="shrink-0 h-10 w-10 sm:h-16 sm:w-16 rounded-full bg-linear-to-br from-primary-400 to-teal-500 flex items-center justify-center text-white relative shadow-lg shadow-primary-500/30 ring-2 sm:ring-4 ring-white dark:ring-slate-900">
                            <Award className="h-4.5 w-4.5 sm:h-8 sm:w-8" />
                            <div className="absolute -bottom-1 -right-1 sm:-bottom-2 sm:-right-2 bg-slate-900 dark:bg-white text-white dark:text-slate-900 text-[8px] sm:text-xs font-bold px-1 sm:px-2 py-0.5 rounded-full shadow-md">
                                Lvl {gamification.level}
                            </div>
                        </div>
                        <div className="flex-1 min-w-0">
                            <div className="flex justify-between items-end mb-1">
                                <span className="font-bold text-xs sm:text-base text-text-light truncate">{gamification.rank_title}</span>
                                <span className="text-[9px] sm:text-xs font-bold text-primary-500 bg-primary-500/10 px-1.5 py-0.5 rounded-full whitespace-nowrap">{gamification.xp} / {gamification.xp_required} XP</span>
                            </div>
                            <div className="h-1.5 sm:h-2 w-full bg-surface-hover rounded-full overflow-hidden shadow-inner">
                                <div 
                                    className="h-full bg-linear-to-r from-primary-500 to-teal-400 rounded-full relative transition-all duration-1000 ease-out"
                                    style={{ width: `${Math.min(100, Math.max(0, (gamification.xp / gamification.xp_required) * 100))}%` }}
                                >
                                    <div className="absolute top-0 right-0 bottom-0 left-0 bg-white/20 animate-pulse"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
            </div>

            {/* Slim Dismissible Biodata Banner */}
            {studentProfileSummary && studentProfileSummary.status !== 'verified' && !isBiodataDismissed && (
                <div className="mb-4 flex items-center justify-between gap-2.5 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs transition-all duration-200 sm:mb-6 sm:px-4 sm:py-2.5">
                    <Link
                        href="/student/profile"
                        className="flex min-w-0 flex-1 items-center gap-2 text-amber-200 transition-colors hover:text-amber-100"
                    >
                        <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-lg bg-amber-500/20 text-amber-400">
                            {studentProfileSummary.status === 'revision_requested' ? (
                                <AlertCircle className="h-3.5 w-3.5" />
                            ) : (
                                <UserRound className="h-3.5 w-3.5" />
                            )}
                        </span>
                        <span className="truncate font-bold">
                            {studentProfileSummary.status === 'revision_requested'
                                ? 'Biodata perlu diperbaiki'
                                : 'Lengkapi biodata siswa'}{' '}
                            <span className="font-black text-amber-400">
                                ({studentProfileSummary.percentage}%)
                            </span>
                        </span>
                    </Link>

                    <div className="flex shrink-0 items-center gap-1.5 sm:gap-2">
                        <Link
                            href="/student/profile"
                            className="inline-flex items-center gap-1 rounded-lg bg-amber-500/20 px-2.5 py-1 text-[11px] font-extrabold text-amber-300 transition-colors hover:bg-amber-500/30 hover:text-amber-100"
                        >
                            Lengkapi <ArrowRight className="h-3 w-3" />
                        </Link>
                        <button
                            type="button"
                            onClick={handleDismissBiodata}
                            className="flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-semibold text-amber-200/70 transition-colors hover:bg-amber-500/15 hover:text-amber-100"
                            title="Sembunyikan selama sesi ini"
                        >
                            Nanti saja
                        </button>
                    </div>
                </div>
            )}

            {/* Compact Good News Ticker & Modal */}
            {classGoodNews.length > 0 && (
                <>
                    <ClassGoodNewsTicker
                        items={classGoodNews}
                        onOpenModal={() => setIsRecognitionsModalOpen(true)}
                    />
                    <ClassRecognitionsModal
                        isOpen={isRecognitionsModalOpen}
                        onClose={() => setIsRecognitionsModalOpen(false)}
                        items={classGoodNews}
                    />
                </>
            )}

            {/* Stat Cards */}
            <div className="mb-6 sm:mb-8 grid gap-2 sm:gap-4 grid-cols-2 sm:grid-cols-4">
                {studentStatCards.map((card, index) => {
                    const value = (stats as any)?.[card.key] ?? 0;
                    return (
                        <div
                            key={card.key}
                            className={cn("glass reveal group relative overflow-hidden rounded-xl sm:rounded-3xl p-3 sm:p-6 transition-all duration-300 hover:-translate-y-1.5 hover:shadow-2xl border border-white/20 dark:border-white/5", card.bgHover, `reveal-delay-${index + 2}`)}
                        >
                            <div className="flex flex-row sm:flex-row-reverse sm:items-center justify-start sm:justify-between gap-2.5 sm:gap-4 h-full">
                                <div
                                    className={cn(
                                        'flex h-8 w-8 sm:h-14 sm:w-14 items-center justify-center rounded-lg sm:rounded-2xl bg-surface ring-1 ring-border/50 transition-transform group-hover:scale-110 shrink-0',
                                        card.color,
                                    )}
                                >
                                    <card.icon className="h-4 w-4 sm:h-7 sm:w-7" />
                                </div>
                                <div className="min-w-0 flex-1">
                                    <p className="text-[10px] sm:text-sm font-bold sm:font-medium text-text-muted leading-tight">
                                        {card.label}
                                    </p>
                                    <h2 className="mt-0.5 sm:mt-2 text-xl sm:text-4xl font-black text-text-light tracking-tight">
                                        {value}
                                    </h2>
                                </div>
                            </div>
                        </div>
                    );
                })}

                {/* Kehadiran Card */}
                <div className="glass reveal reveal-delay-5 group relative overflow-hidden rounded-xl sm:rounded-3xl p-3 sm:p-6 transition-all duration-300 hover:-translate-y-1.5 hover:shadow-2xl border border-white/20 dark:border-white/5 hover:shadow-emerald-500/10">
                    <div className="flex flex-row sm:flex-row-reverse sm:items-center justify-start sm:justify-between gap-2.5 sm:gap-4 h-full">
                        <div className="flex h-8 w-8 sm:h-14 sm:w-14 items-center justify-center rounded-lg sm:rounded-2xl bg-surface ring-1 ring-border/50 transition-transform group-hover:scale-110 shrink-0 text-emerald-400">
                            <Calendar className="h-4 w-4 sm:h-7 sm:w-7" />
                        </div>
                        <div className="min-w-0 flex-1 w-full">
                            <p className="text-[10px] sm:text-sm font-bold sm:font-medium text-text-muted leading-tight">
                                Kehadiran
                            </p>
                                <div className="mt-1 sm:mt-2 flex flex-row items-center justify-between gap-2 flex-wrap">
                                    <h2 className="text-base sm:text-2xl font-black text-text-light tracking-tight flex items-baseline gap-1">
                                        <span className="text-emerald-400">{stats.attendance?.hadir ?? 0}</span>
                                        <span className="text-[10px] sm:text-xs font-normal text-text-muted">Hadir</span>
                                    </h2>
                                    <div className="flex items-center gap-1 sm:gap-1.5 text-[9px] sm:text-xs text-text-muted font-bold bg-surface-lighter/50 border border-border/30 px-2 py-0.5 rounded-full">
                                        <span className="text-amber-500">{stats.attendance?.sakit ?? 0}S</span>
                                        <span className="text-border/40">•</span>
                                        <span className="text-sky-500">{stats.attendance?.izin ?? 0}I</span>
                                        <span className="text-border/40">•</span>
                                        <span className="text-rose-500">{stats.attendance?.alpa ?? 0}A</span>
                                    </div>
                                </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Booking Schedule from KALASI'U */}
            {bookingSchedule && (
                <div className="mb-6 sm:mb-8 reveal reveal-delay-6">
                    <WeeklyScheduleCard data={bookingSchedule} />
                </div>
            )}

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                {/* Upcoming Assignments */}
                <div className="glass reveal reveal-delay-7 rounded-xl sm:rounded-2xl p-4 sm:p-6 flex flex-col">
                    <div className="mb-4 sm:mb-6 flex items-center justify-between">
                        <div className="flex items-center gap-2 sm:gap-3">
                            <div className="flex h-8 w-8 sm:h-10 sm:w-10 items-center justify-center rounded-lg sm:rounded-xl bg-surface text-amber-500">
                                <Clock className="h-4 w-4 sm:h-5 sm:w-5" />
                            </div>
                            <h3 className="text-sm sm:text-lg font-bold text-text-light">Tugas Mendatang</h3>
                        </div>
                    </div>

                    {upcomingAssignments && upcomingAssignments.length > 0 ? (
                        <div className="space-y-2 sm:space-y-3 flex-1">
                            {upcomingAssignments.map((assignment) => (
                                <Link
                                    key={assignment.id}
                                    href={route('materials.show', assignment.material_id)}
                                    className="group block rounded-lg sm:rounded-xl bg-surface/50 p-3 sm:p-4 border border-border/30 hover:bg-surface transition-all"
                                >
                                    <div className="flex items-center justify-between gap-2">
                                        <div className="min-w-0">
                                            <p className="text-xs sm:text-base font-bold text-text-light group-hover:text-amber-400 transition-colors truncate">
                                                {assignment.title}
                                            </p>
                                            <p className="text-[10px] sm:text-sm text-text-muted mt-0.5 truncate">
                                                {assignment.subject_name}
                                            </p>
                                        </div>
                                        <div className="text-right shrink-0">
                                            <div className="flex items-center gap-1 text-[9px] sm:text-xs font-bold text-amber-400 bg-amber-500/10 px-2 py-0.5 sm:px-2.5 sm:py-1 rounded-full mb-1">
                                                {assignment.access_status === 'open' ? <Calendar className="h-3 w-3 sm:h-3.5 sm:w-3.5" /> : <LockKeyhole className="h-3 w-3 sm:h-3.5 sm:w-3.5" />}
                                                {assignment.access_status === 'open' ? assignment.due_date : assignment.opens_at ? `Buka ${assignment.opens_at}` : 'Menunggu jadwal'}
                                            </div>
                                            <p className="text-[9px] sm:text-xs text-text-muted uppercase tracking-wider font-semibold">
                                                {assignment.submission_type}
                                            </p>
                                        </div>
                                    </div>
                                </Link>
                            ))}
                        </div>
                    ) : (
                        <div className="flex-1 flex flex-col items-center justify-center py-6 sm:py-8 text-center">
                            <CheckSquare className="h-8 w-8 sm:h-12 sm:w-12 text-text-muted/30 mb-2 sm:mb-3" />
                            <p className="text-xs sm:text-sm text-text-muted">Hore! Tidak ada tugas yang tertunda.</p>
                        </div>
                    )}
                </div>

                {/* Recent Materials */}
                <div className="glass reveal reveal-delay-8 rounded-xl sm:rounded-2xl p-4 sm:p-6 flex flex-col">
                    <div className="mb-4 sm:mb-6 flex items-center gap-2 sm:gap-3">
                        <div className="flex h-8 w-8 sm:h-10 sm:w-10 items-center justify-center rounded-lg sm:rounded-xl bg-surface text-sky-500">
                            <BookOpen className="h-4 w-4 sm:h-5 sm:w-5" />
                        </div>
                        <h3 className="text-sm sm:text-lg font-bold text-text-light">Materi Terbaru</h3>
                    </div>

                    {recentMaterials && recentMaterials.length > 0 ? (
                        <div className="space-y-2 sm:space-y-3 flex-1">
                            {recentMaterials.map((material) => (
                                <Link
                                    key={material.id}
                                    href={route('materials.show', material.id)}
                                    className="group block rounded-lg sm:rounded-xl bg-surface/50 p-3 sm:p-4 border border-border/30 hover:bg-surface transition-all"
                                >
                                    <div className="flex items-center justify-between gap-2">
                                        <div className="min-w-0">
                                            <p className="text-xs sm:text-base font-bold text-text-light group-hover:text-sky-400 transition-colors truncate">
                                                {material.title}
                                            </p>
                                            <div className="flex items-center gap-1.5 sm:gap-2 mt-0.5 min-w-0">
                                                <span className="text-[9px] sm:text-xs font-semibold bg-surface-lighter px-1.5 py-0.5 rounded text-text-muted truncate">
                                                    {material.subject_name}
                                                </span>
                                                <span className="text-[10px] sm:text-xs text-text-muted truncate">
                                                    {material.teacher_name}
                                                </span>
                                            </div>
                                        </div>
                                        <div className="flex items-center justify-center h-7 w-7 sm:h-8 sm:w-8 rounded-full bg-surface group-hover:bg-sky-500/10 group-hover:text-sky-400 transition-colors shrink-0">
                                            <ArrowRight className="h-3.5 w-3.5 text-text-muted group-hover:text-sky-400" />
                                        </div>
                                    </div>
                                </Link>
                            ))}
                        </div>
                    ) : (
                        <div className="flex-1 flex flex-col items-center justify-center py-6 sm:py-8 text-center">
                            <BookOpen className="h-8 w-8 sm:h-12 sm:w-12 text-text-muted/30 mb-2 sm:mb-3" />
                            <p className="text-xs sm:text-sm text-text-muted">Belum ada materi baru dipublikasikan.</p>
                        </div>
                    )}
                    
                    <div className="mt-4 sm:mt-6 pt-3 sm:pt-4 border-t border-border/40 text-center">
                        <Link
                            href={route('materials.index')}
                            className="inline-flex items-center gap-1.5 text-xs sm:text-sm font-semibold text-sky-400 hover:text-sky-300"
                        >
                            Lihat Semua Materi <ArrowRight className="h-3.5 w-3.5" />
                        </Link>
                    </div>
                </div>

                <div className="lg:col-span-2">
                    <UpcomingHolidaysWidget holidays={upcomingHolidays} />
                </div>
            </div>
        </>
    );
}

Dashboard.layout = (page: any) => <StudentLayout title="Beranda Siswa">{page}</StudentLayout>;
