import { Form, Head, Link } from '@inertiajs/react';
import { CheckCircle2, Clock, FileText, Upload, Download, ChevronLeft, ChevronDown, BookOpen, ClipboardList, Play, ChevronRight } from 'lucide-react';
import { useState } from 'react';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import RichEditor from '@/components/rich-editor';
import AppLayout from '@/layouts/app-layout';
import type { BreadcrumbItem } from '@/types';

type SimpleLesson = { id: number; title: string; type: string; order: number };
type SimpleQuiz = { id: number; title: string; order: number };
type SimpleAssignment = { id: number; title: string; order: number };
type Chapter = {
    id: number;
    title: string;
    order: number;
    lessons: SimpleLesson[];
    quizzes: SimpleQuiz[];
    assignments: SimpleAssignment[];
};

type Assignment = {
    id: number;
    chapter_id: number;
    title: string;
    description: string;
    instructions: string | null;
    deadline: string | null;
    max_score: number;
    submission_type?: 'file' | 'text' | 'both';
};

type Submission = {
    id: number;
    status: 'submitted' | 'graded' | 'late';
    score: number | null;
    feedback: string | null;
    created_at: string;
    file_path?: string | null;
    submission_text?: string | null;
} | null;

type Props = {
    course: { id: number; title: string; slug: string; chapters: Chapter[] };
    assignment: Assignment;
    submission: Submission;
    completedLessonIds: number[];
    progress: { total: number; completed: number; percent: number };
    prev_item: { id: number; type: string; url: string } | null;
    next_item: { id: number; type: string; url: string } | null;
};

function formatDate(date: string): string {
    return new Intl.DateTimeFormat('id-ID', {
        day: 'numeric',
        month: 'long',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    }).format(new Date(date));
}

function lessonTypeIcon(type: string) {
    if (type === 'video') return <Play className="h-3.5 w-3.5" />;
    if (type === 'pdf' || type === 'file') return <FileText className="h-3.5 w-3.5" />;
    return <BookOpen className="h-3.5 w-3.5" />;
}

export default function AssignmentShow({
    course,
    assignment,
    submission,
    completedLessonIds,
    progress,
    prev_item,
    next_item,
}: Props) {
    const isDeadlinePassed = assignment.deadline ? new Date() > new Date(assignment.deadline) : false;
    const [submissionText, setSubmissionText] = useState('');
    const [isEditing, setIsEditing] = useState(false);
    const [openChapters, setOpenChapters] = useState<Record<number, boolean>>({
        [assignment.chapter_id]: true
    });
    const subType = assignment.submission_type ?? 'file';

    const BRAND = '#118AB2';
    const SUCCESS = '#06D6A0';

    return (
        <>
            <Head title={`${assignment.title} — ${course.title}`} />

            <div className="flex h-[calc(100vh-64px)]" style={{ backgroundColor: '#F5F6F8' }}>

                {/* ── SIDEBAR ────────────────────────────────────────────── */}
                <aside
                    className="hidden lg:flex flex-col shrink-0 overflow-hidden"
                    style={{
                        width: 292,
                        backgroundColor: '#FFFFFF',
                        borderRight: '1px solid rgba(0,0,0,0.08)',
                    }}
                >
                    {/* Course header */}
                    <div className="shrink-0 p-4" style={{ borderBottom: '1px solid rgba(0,0,0,0.07)' }}>
                        <Link
                            href={`/my-courses/${course.slug}`}
                            className="mb-3 inline-flex items-center gap-1 text-xs transition-colors"
                            style={{ color: '#AAAAAA' }}
                            onMouseEnter={(e) => (e.currentTarget.style.color = BRAND)}
                            onMouseLeave={(e) => (e.currentTarget.style.color = '#AAAAAA')}
                        >
                            <ChevronLeft className="h-3 w-3" />
                            Kelas Saya
                        </Link>

                        <p className="text-base font-semibold leading-snug" style={{ color: '#1A1A1A' }}>
                            {course.title}
                        </p>

                        <div className="mt-3">
                            <div className="mb-1.5 flex items-center justify-between text-sm" style={{ color: '#BBBBBB' }}>
                                <span>{progress.completed}/{progress.total} materi selesai</span>
                                <span className="font-semibold" style={{ color: BRAND }}>{progress.percent}%</span>
                            </div>
                            <div className="h-1.5 overflow-hidden rounded-full" style={{ backgroundColor: 'rgba(0,0,0,0.07)' }}>
                                <div
                                    className="h-full rounded-full transition-all duration-500"
                                    style={{ width: `${progress.percent}%`, backgroundColor: BRAND }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Chapter list */}
                    <div className="flex-1 overflow-y-auto">
                        {course.chapters.map((chapter, idx) => {
                            const isOpen = !!openChapters[chapter.id];
                            const hasActiveAssignment = chapter.assignments.some((a) => a.id === assignment.id);

                            return (
                                <div key={chapter.id} style={{ borderBottom: '1px solid rgba(0,0,0,0.05)' }}>
                                    {/* Chapter header */}
                                    <button
                                        onClick={() => setOpenChapters(prev => ({ ...prev, [chapter.id]: !prev[chapter.id] }))}
                                        className="flex w-full items-center gap-2.5 px-4 py-3 text-left transition-colors"
                                        style={{
                                            backgroundColor: isOpen ? 'rgba(17,138,178,0.03)' : 'transparent',
                                        }}
                                    >
                                        <span
                                            className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold"
                                            style={
                                                hasActiveAssignment
                                                    ? { backgroundColor: BRAND, color: '#FFFFFF' }
                                                    : { backgroundColor: 'rgba(0,0,0,0.08)', color: '#888888' }
                                            }
                                        >
                                            {idx + 1}
                                        </span>
                                        <span className="flex-1 text-sm font-semibold leading-snug" style={{ color: '#2A2A2A' }}>
                                            {chapter.title}
                                        </span>
                                        <ChevronDown
                                            className="h-3.5 w-3.5 shrink-0 transition-transform"
                                            style={{
                                                color: '#CCCCCC',
                                                transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                                            }}
                                        />
                                    </button>

                                    {/* Items */}
                                    {isOpen && (
                                        <div style={{ backgroundColor: 'rgba(0,0,0,0.01)' }}>
                                            {chapter.lessons.map((l) => {
                                                const done = completedLessonIds.includes(l.id);
                                                return (
                                                    <Link
                                                        key={l.id}
                                                        href={`/courses/${course.slug}/learn/${l.id}`}
                                                        className="flex items-center gap-2.5 py-2.5 pr-4 transition-colors"
                                                        style={{
                                                            paddingLeft: 16,
                                                            borderLeft: '3px solid transparent',
                                                            backgroundColor: 'transparent',
                                                        }}
                                                        onMouseEnter={(e) => {
                                                            e.currentTarget.style.backgroundColor = 'rgba(0,0,0,0.03)';
                                                        }}
                                                        onMouseLeave={(e) => {
                                                            e.currentTarget.style.backgroundColor = 'transparent';
                                                        }}
                                                    >
                                                        <span
                                                            className="shrink-0"
                                                            style={{ color: done ? SUCCESS : '#CCCCCC' }}
                                                        >
                                                            {done ? <CheckCircle2 className="h-3.5 w-3.5" /> : lessonTypeIcon(l.type)}
                                                        </span>
                                                        <span
                                                            className="line-clamp-2 text-sm leading-snug"
                                                            style={{
                                                                color: done ? '#BBBBBB' : '#555555',
                                                                textDecoration: done ? 'line-through' : 'none',
                                                            }}
                                                        >
                                                            {l.title}
                                                        </span>
                                                    </Link>
                                                );
                                            })}

                                            {chapter.quizzes.map((q) => (
                                                <Link
                                                    key={`q-${q.id}`}
                                                    href={`/courses/${course.slug}/quiz/${q.id}`}
                                                    className="flex items-center gap-2.5 py-2.5 pr-4 transition-colors"
                                                    style={{
                                                        paddingLeft: 16,
                                                        borderLeft: '3px solid transparent',
                                                        backgroundColor: 'transparent',
                                                    }}
                                                    onMouseEnter={(e) => {
                                                        e.currentTarget.style.backgroundColor = 'rgba(255,183,3,0.06)';
                                                    }}
                                                    onMouseLeave={(e) => {
                                                        e.currentTarget.style.backgroundColor = 'transparent';
                                                    }}
                                                >
                                                    <ClipboardList className="h-3.5 w-3.5 shrink-0" style={{ color: '#D4A000' }} />
                                                    <span className="line-clamp-2 text-sm leading-snug" style={{ color: '#555555' }}>
                                                        {q.title}
                                                    </span>
                                                </Link>
                                            ))}

                                            {chapter.assignments.map((a) => {
                                                const active = a.id === assignment.id;
                                                return (
                                                    <Link
                                                        key={`a-${a.id}`}
                                                        href={`/courses/${course.slug}/assignment/${a.id}`}
                                                        className="flex items-center gap-2.5 py-2.5 pr-4 transition-colors"
                                                        style={{
                                                            paddingLeft: active ? 13 : 16,
                                                            borderLeft: `3px solid ${active ? BRAND : 'transparent'}`,
                                                            backgroundColor: active ? 'rgba(17,138,178,0.06)' : 'transparent',
                                                        }}
                                                        onMouseEnter={(e) => {
                                                            if (!active) e.currentTarget.style.backgroundColor = 'rgba(99,102,241,0.06)';
                                                        }}
                                                        onMouseLeave={(e) => {
                                                            if (!active) e.currentTarget.style.backgroundColor = 'transparent';
                                                        }}
                                                    >
                                                        <FileText className="h-3.5 w-3.5 shrink-0" style={{ color: active ? BRAND : '#6366F1' }} />
                                                        <span
                                                            className="line-clamp-2 text-sm leading-snug"
                                                            style={{
                                                                color: active ? BRAND : '#555555',
                                                                fontWeight: active ? 600 : 400,
                                                            }}
                                                        >
                                                            {a.title}
                                                        </span>
                                                    </Link>
                                                );
                                            })}
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>
                </aside>

                {/* ── MAIN CONTENT ───────────────────────────────────────── */}
                <main className="flex flex-1 flex-col overflow-hidden">
                    <div className="flex-1 overflow-y-auto">
                        <div className="mx-auto px-5 py-8 max-w-3xl">

                            <div className="mb-6">
                                <Link href={`/my-courses/${course.slug}`} className="text-sm text-primary hover:underline">
                                    ← {course.title}
                                </Link>
                                <h1 className="mt-2 text-2xl font-bold">{assignment.title}</h1>

                                {assignment.deadline && (
                                    <div
                                        className={`mt-2 flex items-center gap-1.5 text-sm ${isDeadlinePassed ? 'text-destructive' : 'text-muted-foreground'}`}
                                    >
                                        <Clock className="h-4 w-4" />
                                        <span>
                                            Deadline: {formatDate(assignment.deadline)}
                                            {isDeadlinePassed && ' (Sudah lewat)'}
                                        </span>
                                    </div>
                                )}
                            </div>

                            {/* Description */}
                            <div className="mb-6 rounded-xl border bg-card p-5">
                                <h2 className="mb-2 font-semibold">Deskripsi Tugas</h2>
                                <p className="text-sm leading-relaxed text-muted-foreground">{assignment.description}</p>
                                {assignment.instructions && (
                                    <>
                                        <h2 className="mb-2 mt-4 font-semibold">Petunjuk</h2>
                                        <div 
                                            className="prose prose-sm max-w-none text-muted-foreground leading-relaxed"
                                            dangerouslySetInnerHTML={{ __html: assignment.instructions }}
                                        />
                                    </>
                                )}
                                <p className="mt-3 text-sm text-muted-foreground">
                                    Nilai maksimal: <strong>{assignment.max_score}</strong>
                                </p>
                            </div>

                            {/* Submission Status */}
                            {submission && !isEditing ? (
                                <div className="rounded-xl border bg-card p-5 space-y-4">
                                    <div className="flex items-center gap-2">
                                        <CheckCircle2 className="h-5 w-5 text-green-500" />
                                        <h2 className="font-semibold">
                                            {submission.status === 'late' ? 'Dikumpulkan (Terlambat)' : 'Sudah Dikumpulkan'}
                                        </h2>
                                    </div>
                                    <p className="text-sm text-muted-foreground flex flex-wrap gap-2 items-center">
                                        <span>Dikumpulkan pada {formatDate(submission.created_at)}</span>
                                        {submission.updated_at && new Date(submission.updated_at).getTime() - new Date(submission.created_at).getTime() > 1000 && (
                                            <span className="text-xs text-blue-600 bg-blue-50 dark:bg-blue-950/40 px-2 py-0.5 rounded-full font-semibold">
                                                Diedit pada {formatDate(submission.updated_at)}
                                            </span>
                                        )}
                                    </p>

                                    {/* Display own submission details */}
                                    {submission.file_path && (
                                        <div className="flex items-center gap-2 rounded-lg border bg-muted/40 p-3 text-sm">
                                            <FileText className="h-5 w-5 text-blue-600" />
                                            <span className="flex-1 truncate font-medium">File Tugas Anda</span>
                                            <a
                                                href={`/courses/${course.slug}/assignment/${assignment.id}/submissions/${submission.id}/download`}
                                                className="rounded-md border bg-white px-3 py-1.5 text-xs font-semibold text-blue-600 hover:bg-blue-50 shadow-xs dark:bg-zinc-900 dark:border-zinc-800 dark:text-blue-400"
                                            >
                                                Unduh File
                                            </a>
                                        </div>
                                    )}

                                    {submission.submission_text && (
                                        <div className="rounded-xl border border-blue-100 bg-blue-50/5 p-4 dark:border-blue-950">
                                            <h4 className="font-semibold text-xs text-blue-900 dark:text-blue-100 mb-2">Jawaban Teks Anda:</h4>
                                            <div 
                                                className="prose prose-sm max-w-none text-muted-foreground leading-relaxed"
                                                dangerouslySetInnerHTML={{ __html: submission.submission_text }}
                                            />
                                        </div>
                                    )}

                                    {submission.score !== null && (
                                        <div className="mt-3 pt-3 border-t">
                                            <p className="text-sm">
                                                Nilai:{' '}
                                                <strong className="text-lg">
                                                    {submission.score}/{assignment.max_score}
                                                </strong>
                                            </p>
                                        </div>
                                    )}
                                    {submission.feedback && (
                                        <div className="mt-3 rounded-lg bg-muted p-3">
                                            <p className="mb-1 text-xs font-medium text-muted-foreground">Feedback Instruktur</p>
                                            <p className="text-sm">{submission.feedback}</p>
                                        </div>
                                    )}
                                    {submission.score === null && (
                                        <div className="flex flex-col gap-2 mt-3 pt-3 border-t">
                                            <p className="text-sm text-muted-foreground">Menunggu penilaian instruktur...</p>
                                            <div>
                                                <Button 
                                                    variant="outline" 
                                                    size="sm"
                                                    onClick={() => {
                                                        setSubmissionText(submission.submission_text ?? '');
                                                        setIsEditing(true);
                                                    }}
                                                >
                                                    Edit Jawaban
                                                </Button>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            ) : (
                                <div className="rounded-xl border bg-card p-5">
                                    <div className="flex justify-between items-center mb-4 border-b pb-2">
                                        <h2 className="font-semibold">{submission ? 'Edit Jawaban Tugas' : 'Kumpulkan Tugas'}</h2>
                                        {submission && (
                                            <Button variant="ghost" size="sm" onClick={() => setIsEditing(false)}>
                                                Batal
                                            </Button>
                                        )}
                                    </div>
                                    <Form
                                        action={`/courses/${course.slug}/assignment/${assignment.id}/submit`}
                                        method="post"
                                        onSuccess={() => setIsEditing(false)}
                                        className="flex flex-col gap-4"
                                    >
                                        {({ errors, processing }) => (
                                            <>
                                                {/* File Input (if required/optional) */}
                                                {(subType === 'file' || subType === 'both') && (
                                                    <div className="grid gap-2">
                                                        <Label htmlFor="file">
                                                            <FileText className="mr-1 inline h-4 w-4" />
                                                            File Tugas {subType === 'both' && '(Opsional)'}
                                                        </Label>
                                                        {submission?.file_path && (
                                                            <p className="text-xs text-muted-foreground bg-blue-50/50 p-2 rounded border dark:border-blue-900/30">
                                                                File saat ini sudah diunggah. Unggah file baru untuk menggantinya.
                                                            </p>
                                                        )}
                                                        <input
                                                            id="file"
                                                            type="file"
                                                            name="file"
                                                            required={subType === 'file' && !submission}
                                                            className="rounded-lg border bg-background px-3 py-2 text-sm file:mr-3 file:cursor-pointer file:rounded-md file:border-0 file:bg-primary file:px-3 file:py-1 file:text-xs file:text-primary-foreground"
                                                        />
                                                        <InputError message={errors.file} />
                                                    </div>
                                                )}

                                                {/* Rich Text Editor Input (if required/optional) */}
                                                {(subType === 'text' || subType === 'both') && (
                                                    <div className="grid gap-2">
                                                        <Label>
                                                            Jawaban Teks {subType === 'both' && '(Opsional)'}
                                                        </Label>
                                                        <RichEditor
                                                            value={submissionText}
                                                            onChange={setSubmissionText}
                                                            placeholder="Tulis jawaban atau salin tautan tugas Anda di sini..."
                                                        />
                                                        <input type="hidden" name="submission_text" value={submissionText} />
                                                        <InputError message={errors.submission_text} />
                                                    </div>
                                                )}

                                                <div className="grid gap-2">
                                                    <Label htmlFor="note">Catatan (opsional)</Label>
                                                    <textarea
                                                        id="note"
                                                        name="note"
                                                        rows={3}
                                                        defaultValue={submission?.note ?? ''}
                                                        placeholder="Tambahkan catatan untuk instruktur..."
                                                        className="rounded-lg border bg-background p-3 text-sm focus:outline-none focus:ring-1 focus:ring-primary"
                                                    />
                                                    <InputError message={errors.note} />
                                                </div>

                                                {isDeadlinePassed && (
                                                    <div className="rounded-lg border border-orange-200 bg-orange-50 p-3 text-sm text-orange-800 dark:bg-orange-950/20 dark:text-orange-300">
                                                        Deadline sudah lewat. Tugas akan ditandai sebagai terlambat.
                                                    </div>
                                                )}

                                                <Button type="submit" disabled={processing}>
                                                    {processing ? <Spinner /> : <Upload className="h-4 w-4" />}
                                                    {submission ? 'Simpan Perubahan' : 'Kumpulkan Tugas'}
                                                </Button>
                                            </>
                                        )}
                                    </Form>
                                </div>
                            )}

                            {/* Navigation & Controls */}
                            <div className="mt-8 flex items-center justify-between border-t pt-6" style={{ borderColor: 'rgba(0,0,0,0.08)' }}>
                                {/* Left: Prev button */}
                                <div className="w-1/4 flex justify-start">
                                    {prev_item ? (
                                        <Link
                                            href={prev_item.url}
                                            className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold text-gray-600 transition-all hover:bg-gray-50 hover:-translate-y-0.5 active:translate-y-0"
                                            style={{ borderColor: 'rgba(0,0,0,0.08)', backgroundColor: '#FFFFFF' }}
                                        >
                                            <ChevronLeft className="h-4 w-4" />
                                            Sebelumnya
                                        </Link>
                                    ) : (
                                        <div />
                                    )}
                                </div>

                                <div className="flex items-center gap-3 justify-center">
                                    {/* Empty / placeholder */}
                                </div>

                                {/* Right: Next button */}
                                <div className="w-1/4 flex justify-end">
                                    {next_item ? (
                                        <Link
                                            href={next_item.url}
                                            className="inline-flex items-center gap-1.5 rounded-xl border px-4 py-2 text-sm font-semibold transition-all hover:-translate-y-0.5 active:translate-y-0"
                                            style={{
                                                borderColor: BRAND,
                                                color: BRAND,
                                                backgroundColor: '#FFFFFF',
                                            }}
                                            onMouseEnter={(e) => {
                                                e.currentTarget.style.backgroundColor = 'rgba(17,138,178,0.04)';
                                            }}
                                            onMouseLeave={(e) => {
                                                e.currentTarget.style.backgroundColor = '#FFFFFF';
                                            }}
                                        >
                                            Berikutnya
                                            <ChevronRight className="h-4 w-4" />
                                        </Link>
                                    ) : (
                                        <div />
                                    )}
                                </div>
                            </div>

                        </div>
                    </div>
                </main>
            </div>
        </>
    );
}

AssignmentShow.layout = (page: React.ReactNode) => {
    const props = (page as React.ReactElement)?.props as Props | undefined;
    const breadcrumbs: BreadcrumbItem[] = props?.course
        ? [
              { title: 'Kelas Saya', href: '/my-courses' },
              { title: props.course.title, href: `/my-courses/${props.course.slug}` },
              { title: props.assignment.title, href: '#' },
          ]
        : [];
    return <AppLayout breadcrumbs={breadcrumbs}>{page}</AppLayout>;
};
