import { Head, Link, router } from '@inertiajs/react';
import { ArrowLeft, Award, BookOpen, Calendar, Camera, Clock, Heart, Mail, Phone, ShieldCheck, User, UserCog } from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';
import { Button } from '@/components/ui/button';

type LessonProgress = {
    id: number;
    enrollment_id: number;
    lesson_id: number;
    completed_at: string | null;
};

type Lesson = {
    id: number;
    chapter_id: number;
};

type Chapter = {
    id: number;
    lessons: Lesson[];
};

type Enrollment = {
    id: number;
    status: string;
    enrolled_at: string | null;
    completed_at: string | null;
    course: {
        id: number;
        title: string;
        slug: string;
        thumbnail: string | null;
        chapters: Chapter[];
    };
    lesson_progress: LessonProgress[];
};

type UserDetail = {
    id: number;
    name: string;
    email: string;
    role: 'student' | 'instructor' | 'admin';
    gender: string | null;
    birth_date: string | null;
    points: number;
    avatar: string | null;
    bio: string | null;
    phone: string | null;
    created_at: string;
    enrollments_count: number;
    enrollments: Enrollment[];
};

type Props = {
    user: UserDetail;
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Admin', href: '/admin' },
    { title: 'Pengguna', href: '/admin/users' },
    { title: 'Detail Profil', href: '#' },
];

const ROLE_CONFIG: Record<string, { label: string; badge: string; avatarGradient: string; icon: React.ElementType }> = {
    student:    { label: 'Siswa',      badge: 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300',   avatarGradient: 'from-blue-100 to-sky-100 text-blue-700 dark:from-blue-950/40 dark:to-sky-950/30 dark:text-blue-300',   icon: User },
    instructor: { label: 'Instruktur', badge: 'bg-teal-100 text-teal-700 dark:bg-teal-900/40 dark:text-teal-300',   avatarGradient: 'from-teal-100 to-cyan-100 text-teal-700 dark:from-teal-950/40 dark:to-cyan-950/30 dark:text-teal-300',     icon: UserCog },
    admin:      { label: 'Admin',      badge: 'bg-rose-100 text-rose-700 dark:bg-rose-900/40 dark:text-rose-300',   avatarGradient: 'from-rose-100 to-pink-100 text-rose-700 dark:from-rose-950/40 dark:to-pink-950/30 dark:text-rose-300',     icon: ShieldCheck },
};

function getInitials(name: string) {
    return name.split(' ').slice(0, 2).map((n) => n[0]).join('').toUpperCase();
}

export default function AdminUserShow({ user }: Props) {
    const cfg = ROLE_CONFIG[user.role] ?? ROLE_CONFIG.student;
    const RoleIcon = cfg.icon;

    // Helper to calculate progress percentage for each course enrollment
    function getProgressPercentage(enrollment: Enrollment) {
        const totalLessons = enrollment.course.chapters.reduce((sum, ch) => sum + ch.lessons.length, 0);
        if (totalLessons === 0) return 0;
        const completedCount = enrollment.lesson_progress.filter((p) => p.completed_at !== null).length;
        return Math.min(Math.round((completedCount / totalLessons) * 100), 100);
    }

    function handleAvatarUpload(e: React.ChangeEvent<HTMLInputElement>) {
        const file = e.target.files?.[0];
        if (!file) return;

        const formData = new FormData();
        formData.append('avatar', file);

        router.post(`/admin/users/${user.id}/avatar`, formData, {
            preserveScroll: true,
        });
    }

    return (
        <>
            <Head title={`Profil ${user.name}`} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                {/* Back Button & Header */}
                <div className="flex items-center gap-4">
                    <Link href="/admin/users">
                        <Button variant="outline" size="icon" className="h-9 w-9">
                            <ArrowLeft className="h-4 w-4" />
                        </Button>
                    </Link>
                    <div>
                        <h1 className="text-xl font-bold text-zinc-900 dark:text-zinc-50">Profil Pengguna</h1>
                        <p className="text-xs text-muted-foreground">Detail informasi profil & progres belajar peserta</p>
                    </div>
                </div>

                {/* Profile Grid */}
                <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                    {/* Left Column - Card Profile */}
                    <div className="lg:col-span-1 space-y-6">
                        <div className="rounded-2xl border border-blue-100 bg-white p-6 shadow-xs dark:border-blue-800/30 dark:bg-card">
                            <div className="flex flex-col items-center text-center">
                                {/* Avatar */}
                                <div className="relative group mb-4">
                                    {user.avatar ? (
                                        <img
                                            src={user.avatar}
                                            alt={user.name}
                                            className="h-20 w-20 rounded-full object-cover shadow-md border-2 border-white dark:border-zinc-800"
                                        />
                                    ) : (
                                        <div className={`flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br ${cfg.avatarGradient} text-2xl font-bold`}>
                                            {getInitials(user.name)}
                                        </div>
                                    )}
                                    <label className="absolute inset-0 flex flex-col items-center justify-center bg-black/50 rounded-full opacity-0 group-hover:opacity-100 cursor-pointer transition-opacity duration-200">
                                        <input
                                            type="file"
                                            accept="image/*"
                                            className="hidden"
                                            onChange={handleAvatarUpload}
                                        />
                                        <Camera className="h-4 w-4 text-white mb-1" />
                                        <span className="text-[10px] text-white font-medium">Ubah Foto</span>
                                    </label>
                                </div>

                                <h2 className="text-lg font-bold text-zinc-950 dark:text-zinc-50">{user.name}</h2>
                                <p className="text-sm text-muted-foreground mt-0.5">{user.email}</p>

                                <span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium mt-3 ${cfg.badge}`}>
                                    <RoleIcon className="h-3.5 w-3.5" />
                                    {cfg.label}
                                </span>
                            </div>

                            <div className="mt-6 border-t border-zinc-100 pt-6 dark:border-zinc-800/50 space-y-4">
                                <div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-400">
                                    <Mail className="h-4 w-4 text-muted-foreground shrink-0" />
                                    <span className="truncate">{user.email}</span>
                                </div>
                                <div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-400">
                                    <Phone className="h-4 w-4 text-muted-foreground shrink-0" />
                                    <span>{user.phone || 'Tidak ada nomor telepon'}</span>
                                </div>
                                <div className="flex items-center gap-3 text-sm text-zinc-600 dark:text-zinc-400">
                                    <Calendar className="h-4 w-4 text-muted-foreground shrink-0" />
                                    <span>Bergabung: {new Date(user.created_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' })}</span>
                                </div>
                            </div>
                        </div>

                        {/* Extra Personal Details */}
                        <div className="rounded-2xl border border-blue-100 bg-white p-6 shadow-xs dark:border-blue-900/30 dark:bg-card">
                            <h3 className="font-semibold text-zinc-900 dark:text-zinc-100 mb-4">Informasi Tambahan</h3>
                            <div className="space-y-4 text-sm">
                                <div>
                                    <span className="text-xs text-muted-foreground block">Jenis Kelamin</span>
                                    <span className="font-medium text-zinc-800 dark:text-zinc-200">
                                        {user.gender === 'male' ? 'Laki-laki' : user.gender === 'female' ? 'Perempuan' : 'Tidak ditentukan'}
                                    </span>
                                </div>
                                <div>
                                    <span className="text-xs text-muted-foreground block">Tanggal Lahir</span>
                                    <span className="font-medium text-zinc-800 dark:text-zinc-200">
                                        {user.birth_date ? new Date(user.birth_date).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' }) : 'Tidak ditentukan'}
                                    </span>
                                </div>
                                <div>
                                    <span className="text-xs text-muted-foreground block">Biografi</span>
                                    <p className="text-xs text-zinc-600 dark:text-zinc-400 mt-1 leading-relaxed">
                                        {user.bio || 'Belum ada biografi singkat.'}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Right Column - Stats & Enrolled Courses */}
                    <div className="lg:col-span-2 space-y-6">
                        {/* Stats Overview */}
                        <div className="grid grid-cols-2 gap-4">
                            <div className="rounded-2xl border border-blue-100 bg-blue-50/20 p-5 dark:border-blue-950/20 dark:bg-blue-950/5">
                                <div className="flex items-center gap-3">
                                    <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-blue-100 dark:bg-blue-900/40">
                                        <Award className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                                    </div>
                                    <div>
                                        <p className="text-xs text-muted-foreground">Poin Belajar</p>
                                        <p className="text-xl font-bold text-blue-700 dark:text-blue-400">{user.points} XP</p>
                                    </div>
                                </div>
                            </div>
                            <div className="rounded-2xl border border-blue-100 bg-blue-50/20 p-5 dark:border-blue-950/20 dark:bg-blue-950/5">
                                <div className="flex items-center gap-3">
                                    <div className="flex h-9 w-9 items-center justify-center rounded-xl bg-blue-100 dark:bg-blue-900/40">
                                        <BookOpen className="h-5 w-5 text-blue-600 dark:text-blue-400" />
                                    </div>
                                    <div>
                                        <p className="text-xs text-muted-foreground">Kelas Diikuti</p>
                                        <p className="text-xl font-bold text-blue-700 dark:text-blue-400">{user.enrollments_count} Kelas</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Enrolled Courses list */}
                        <div className="rounded-2xl border border-blue-100 bg-white shadow-xs dark:border-blue-900/30 dark:bg-card">
                            <div className="border-b border-blue-100 px-6 py-4 dark:border-blue-800/50">
                                <h3 className="font-semibold text-zinc-950 dark:text-zinc-50">Kelas yang Diikuti</h3>
                            </div>

                            {user.enrollments.length === 0 ? (
                                <div className="flex flex-col items-center justify-center py-12 text-center">
                                    <BookOpen className="mb-2 h-10 w-10 text-zinc-200 dark:text-zinc-800" />
                                    <p className="text-sm font-medium text-zinc-500">Belum ada kelas diikuti</p>
                                </div>
                            ) : (
                                <div className="divide-y divide-blue-50 dark:divide-zinc-800/50">
                                    {user.enrollments.map((en) => {
                                        const progress = getProgressPercentage(en);
                                        return (
                                            <div key={en.id} className="p-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                                <div className="min-w-0 flex-1">
                                                    <h4 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 hover:text-blue-600 dark:hover:text-blue-400">
                                                        {en.course.title}
                                                    </h4>
                                                    <div className="mt-1.5 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
                                                        <span className={`inline-flex items-center rounded-full px-2 py-0.5 font-medium ${
                                                            en.status === 'active'    ? 'bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400' :
                                                            en.status === 'completed' ? 'bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400' :
                                                                                       'bg-zinc-100 text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400'
                                                        }`}>
                                                            {en.status === 'active' ? 'Aktif' : en.status === 'completed' ? 'Selesai' : en.status}
                                                        </span>
                                                        {en.enrolled_at && (
                                                            <span className="flex items-center gap-1">
                                                                <Clock className="h-3.5 w-3.5" />
                                                                Terdaftar: {new Date(en.enrolled_at).toLocaleDateString('id-ID', { day: 'numeric', month: 'short', year: 'numeric' })}
                                                            </span>
                                                        )}
                                                    </div>
                                                </div>

                                                <div className="w-full sm:w-48 shrink-0 space-y-1">
                                                    <div className="flex items-center justify-between text-xs font-medium text-zinc-600 dark:text-zinc-400">
                                                        <span>Progres Belajar</span>
                                                        <span>{progress}%</span>
                                                    </div>
                                                    <div className="h-2 w-full bg-zinc-100 dark:bg-zinc-800 rounded-full overflow-hidden">
                                                        <div
                                                            className="h-full bg-blue-500 rounded-full transition-all duration-300"
                                                            style={{ width: `${progress}%` }}
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}

AdminUserShow.layout = (page: React.ReactNode) => <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
