import { Head, Link, useForm } from '@inertiajs/react';
import {
    AlertCircle,
    ArrowDown,
    ArrowUp,
    CheckCircle,
    ChevronLeft,
    ChevronRight,
    FileText,
    HelpCircle,
    ListChecks,
    Plus,
    RotateCcw,
    Trash2,
} from 'lucide-react';
import { type FormEvent, type MouseEvent, useState, useEffect } from 'react';
import AuthenticatedLayout from '@/layouts/AuthenticatedLayout';
import RichTextEditor from '@/components/RichTextEditor';
import AssignmentAvailabilityFields, { type ReleaseSchedule } from '@/components/AssignmentAvailabilityFields';
import AssignmentStorageFields, { type DriveSummary } from '@/components/AssignmentStorageFields';
import { cn } from '@/lib/utils';
import { ASSESSMENT_CATEGORIES, type AssessmentCategory, getCategoryInfo } from '@/lib/kktp';
import type { PageProps } from '@/types';

type AssignmentType = 'standard' | 'quiz' | 'worksheet';
type WorksheetType = 'short_answer' | 'paragraph' | 'multiple_choice' | 'ordering';
type Option = { id?: string; text: string; is_correct?: boolean };
type WorksheetItem = {
    id?: number;
    item_type: WorksheetType;
    prompt: string;
    options: Option[];
    answer_key: { accepted_answers?: string[] };
    points: number;
    is_required: boolean;
};
type QuizQuestion = {
    id?: number;
    item_type: 'multiple_choice' | 'true_false';
    question_text: string;
    question_image?: string | File | null;
    options: Array<{ text: string; is_correct: boolean }>;
    points: number;
};

interface Material {
    id: number;
    title: string;
    classes?: Array<{ id: number; name: string }>;
    synced_class?: { id: number; name: string } | null;
    subject?: { id: number; name: string } | null;
}

interface ExistingAssignment {
    id: number;
    title: string;
    description: string | null;
    assignment_type: AssignmentType;
    category?: AssessmentCategory;
    kktp?: number;
    submission_type: 'text' | 'file' | 'link' | 'physical' | 'quiz';
    file_storage?: 'local' | 'google_drive';
    due_date: string;
    max_points: number;
    allow_resubmit: boolean;
    quiz_config?: { max_attempts?: number; shuffle_questions?: boolean; shuffle_options?: boolean } | null;
    quiz_questions?: QuizQuestion[];
    worksheet_items?: WorksheetItem[];
    has_submissions?: boolean;
    classes?: Array<{ id: number; name: string }>;
    release_mode?: 'meeting' | 'schedule' | 'manual_only' | 'manual' | 'immediate';
    due_mode?: 'relative' | 'fixed';
    due_days?: number | null;
    close_after_days?: number | null;
    availability_overrides?: Array<{ class_id: number; opens_at: string }>;
}

interface Props extends PageProps {
    material: Material;
    assignment: ExistingAssignment | null;
    errors: Record<string, string>;
    releaseSchedule: ReleaseSchedule;
    drive?: DriveSummary;
}

const newOptionId = () =>
    typeof crypto !== 'undefined' && crypto.randomUUID
        ? crypto.randomUUID()
        : `option-${Date.now()}-${Math.random()}`;

const blankWorksheetItem = (): WorksheetItem => ({
    item_type: 'short_answer',
    prompt: '',
    options: [],
    answer_key: { accepted_answers: [] },
    points: 10,
    is_required: true,
});

const blankQuizQuestion = (): QuizQuestion => ({
    item_type: 'multiple_choice',
    question_text: '',
    question_image: null,
    options: [
        { text: '', is_correct: true },
        { text: '', is_correct: false },
    ],
    points: 10,
});

const TRUE_FALSE_OPTIONS = (correctIsBenar: boolean): Array<{ text: string; is_correct: boolean }> => [
    { text: 'Benar', is_correct: correctIsBenar },
    { text: 'Salah', is_correct: !correctIsBenar },
];

export default function AssignmentForm({ material, assignment, errors, releaseSchedule, drive }: Props) {
    const editing = Boolean(assignment);
    const availableClasses = material.classes?.length
        ? material.classes
        : material.synced_class
            ? [material.synced_class]
            : [];
    const initialClassIds = assignment?.classes?.length
        ? assignment.classes.map((item) => item.id)
        : availableClasses.map((item) => item.id);

    const [currentStep, setCurrentStep] = useState<1 | 2 | 3>(1);
    const [clientErrors, setClientErrors] = useState<Record<string, string>>({});
    const storageKey = `uticlass_draft_assign_${material.id}`;
    const [hasDraft, setHasDraft] = useState(false);
    const [draftDismissed, setDraftDismissed] = useState(false);

    const form = useForm({
        material_id: material.id,
        file_storage: (assignment?.file_storage ?? (drive?.ready ? 'google_drive' : 'local')) as 'local' | 'google_drive',
        title: assignment?.title || '',
        description: assignment?.description || '',
        assignment_type: (assignment?.assignment_type || 'worksheet') as AssignmentType,
        category: (assignment?.category || (assignment?.assignment_type === 'worksheet' ? 'formatif_lkpd' : 'tugas_harian')) as AssessmentCategory,
        kktp: assignment?.kktp !== undefined ? Number(assignment.kktp) : 75,
        submission_type: (assignment?.submission_type === 'quiz' ? 'text' : assignment?.submission_type || 'text') as
            | 'text'
            | 'file'
            | 'link'
            | 'physical'
            | 'quiz',
        due_date: assignment?.due_date ? assignment.due_date.substring(0, 16) : '',
        release_mode: (assignment?.release_mode || 'meeting') as
            | 'meeting'
            | 'schedule'
            | 'manual_only'
            | 'manual'
            | 'immediate',
        due_mode: (assignment?.due_mode || 'relative') as 'relative' | 'fixed',
        due_days: assignment?.due_days || 7,
        close_after_days: (assignment?.close_after_days ?? null) as number | null,
        availability_overrides: (assignment?.availability_overrides || []) as Array<{
            class_id: number;
            opens_at: string;
        }>,
        max_points: assignment?.max_points || 100,
        allow_resubmit: assignment?.allow_resubmit || false,
        synced_class_ids: initialClassIds as number[],
        quiz_config: assignment?.quiz_config || {
            max_attempts: 3,
            shuffle_questions: true,
            shuffle_options: true,
        },
        quiz_questions: (assignment?.quiz_questions || [blankQuizQuestion()]) as QuizQuestion[],
        worksheet_items: (assignment?.worksheet_items || [blankWorksheetItem()]) as WorksheetItem[],
    });

    const worksheetTotal = form.data.worksheet_items.reduce((total, item) => total + Number(item.points || 0), 0);

    // Check saved draft on mount
    useEffect(() => {
        if (!editing) {
            try {
                const saved = sessionStorage.getItem(storageKey);
                if (saved) {
                    const parsed = JSON.parse(saved);
                    if (
                        parsed &&
                        (parsed.title ||
                            parsed.description ||
                            (parsed.worksheet_items && parsed.worksheet_items.length > 0 && parsed.worksheet_items[0].prompt) ||
                            (parsed.quiz_questions && parsed.quiz_questions.length > 0 && parsed.quiz_questions[0].question_text))
                    ) {
                        setHasDraft(true);
                    }
                }
            } catch (e) {
                console.error('Failed to check draft', e);
            }
        }
    }, [editing, storageKey]);

    // Debounced autosave to sessionStorage
    useEffect(() => {
        if (editing) return;
        const timeout = setTimeout(() => {
            try {
                const quizQuestionsClean = form.data.quiz_questions.map((q) => ({
                    ...q,
                    question_image: typeof q.question_image === 'string' ? q.question_image : null,
                }));

                const draftData = {
                    title: form.data.title,
                    description: form.data.description,
                    assignment_type: form.data.assignment_type,
                    category: form.data.category,
                    kktp: form.data.kktp,
                    submission_type: form.data.submission_type,
                    file_storage: form.data.file_storage,
                    synced_class_ids: form.data.synced_class_ids,
                    due_date: form.data.due_date,
                    release_mode: form.data.release_mode,
                    due_mode: form.data.due_mode,
                    due_days: form.data.due_days,
                    close_after_days: form.data.close_after_days,
                    availability_overrides: form.data.availability_overrides,
                    max_points: form.data.max_points,
                    allow_resubmit: form.data.allow_resubmit,
                    quiz_config: form.data.quiz_config,
                    quiz_questions: quizQuestionsClean,
                    worksheet_items: form.data.worksheet_items,
                };
                sessionStorage.setItem(storageKey, JSON.stringify(draftData));
            } catch (e) {
                // Ignore storage errors
            }
        }, 800);
        return () => clearTimeout(timeout);
    }, [form.data, editing, storageKey]);

    // Auto-navigate to step when backend validation errors arrive
    useEffect(() => {
        if (Object.keys(errors).length === 0) return;

        const step1Keys = ['title', 'description', 'assignment_type', 'category', 'synced_class_ids'];
        const step2Keys = ['worksheet_items', 'quiz_questions', 'quiz_config', 'submission_type', 'file_storage'];
        const step3Keys = ['due_date', 'release_mode', 'due_mode', 'due_days', 'close_after_days', 'availability_overrides', 'max_points', 'kktp'];

        const hasStep1Error = Object.keys(errors).some((k) => step1Keys.some((sk) => k.startsWith(sk)));
        const hasStep2Error = Object.keys(errors).some((k) => step2Keys.some((sk) => k.startsWith(sk)));
        const hasStep3Error = Object.keys(errors).some((k) => step3Keys.some((sk) => k.startsWith(sk)));

        if (hasStep1Error) {
            setCurrentStep(1);
        } else if (hasStep2Error) {
            setCurrentStep(2);
        } else if (hasStep3Error) {
            setCurrentStep(3);
        }
    }, [errors]);

    function restoreDraft() {
        try {
            const saved = sessionStorage.getItem(storageKey);
            if (saved) {
                const parsed = JSON.parse(saved);
                Object.entries(parsed).forEach(([key, val]) => {
                    form.setData(key as any, val);
                });
                setHasDraft(false);
            }
        } catch (e) {
            console.error('Failed to restore draft', e);
        }
    }

    function discardDraft() {
        try {
            sessionStorage.removeItem(storageKey);
            setHasDraft(false);
            setDraftDismissed(true);
        } catch (e) {}
    }

    function validateStep1(): boolean {
        const errs: Record<string, string> = {};
        if (!form.data.title.trim()) {
            errs.title = 'Judul penugasan wajib diisi.';
        }
        if (form.data.synced_class_ids.length === 0) {
            errs.synced_class_ids = 'Pilih minimal 1 kelas untuk menerima tugas ini.';
        }
        setClientErrors(errs);
        return Object.keys(errs).length === 0;
    }

    function validateStep2(): boolean {
        const errs: Record<string, string> = {};
        if (form.data.assignment_type === 'worksheet') {
            if (form.data.worksheet_items.length === 0) {
                errs.worksheet_items = 'Tambahkan minimal 1 pertanyaan pada worksheet.';
            }
        } else if (form.data.assignment_type === 'quiz') {
            if (form.data.quiz_questions.length === 0) {
                errs.quiz_questions = 'Tambahkan minimal 1 soal quiz.';
            }
        }
        setClientErrors(errs);
        return Object.keys(errs).length === 0;
    }

    function handleTabClick(targetStep: 1 | 2 | 3) {
        if (targetStep === currentStep) return;

        if (currentStep === 1 && targetStep > 1) {
            if (!validateStep1()) return;
        }
        if (currentStep === 2 && targetStep === 3) {
            if (!validateStep2()) return;
        }

        setClientErrors({});
        setCurrentStep(targetStep);
        window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    function handleNext(event: MouseEvent<HTMLButtonElement>) {
        // Cancel the click's default action before switching to the submit button.
        event.preventDefault();

        if (currentStep === 1) {
            if (validateStep1()) {
                setClientErrors({});
                setCurrentStep(2);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        } else if (currentStep === 2) {
            if (validateStep2()) {
                setClientErrors({});
                setCurrentStep(3);
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }
        }
    }

    function handleBack() {
        if (currentStep > 1) {
            setClientErrors({});
            setCurrentStep((prev) => (prev - 1) as 1 | 2 | 3);
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    }

    function submit(event: FormEvent) {
        event.preventDefault();

        if (currentStep !== 3 || form.processing) return;

        if (!validateStep1()) {
            setCurrentStep(1);
            return;
        }
        if (!validateStep2()) {
            setCurrentStep(2);
            return;
        }

        let payload = { ...form.data };
        if (payload.assignment_type === 'standard') {
            delete (payload as any).worksheet_items;
            delete (payload as any).quiz_questions;
            delete (payload as any).quiz_config;
        } else if (payload.assignment_type === 'worksheet') {
            payload.max_points = Math.max(1, worksheetTotal);
            payload.submission_type = 'text';
            delete (payload as any).quiz_questions;
            delete (payload as any).quiz_config;
        } else if (payload.assignment_type === 'quiz') {
            payload.submission_type = 'quiz';
            delete (payload as any).worksheet_items;
        }

        form.transform(() => payload);
        if (editing) {
            form.put(`/assignments/${assignment!.id}`);
        } else {
            form.post('/assignments', {
                onSuccess: () => {
                    try {
                        sessionStorage.removeItem(storageKey);
                    } catch {}
                },
            });
        }
    }

    function updateWorksheetItem(index: number, changes: Partial<WorksheetItem>) {
        form.setData(
            'worksheet_items',
            form.data.worksheet_items.map((item, itemIndex) =>
                itemIndex === index ? { ...item, ...changes } : item
            )
        );
    }

    function changeWorksheetType(index: number, type: WorksheetType) {
        const options =
            type === 'multiple_choice'
                ? [
                      { id: newOptionId(), text: '', is_correct: true },
                      { id: newOptionId(), text: '', is_correct: false },
                  ]
                : type === 'ordering'
                    ? [{ id: newOptionId(), text: '' }, { id: newOptionId(), text: '' }]
                    : [];
        updateWorksheetItem(index, { item_type: type, options, answer_key: { accepted_answers: [] } });
    }

    function updateWorksheetOption(itemIndex: number, optionIndex: number, changes: Partial<Option>) {
        const item = form.data.worksheet_items[itemIndex];
        const options = item.options.map((option, index) =>
            index === optionIndex ? { ...option, ...changes } : option
        );
        updateWorksheetItem(itemIndex, { options });
    }

    function move<T>(items: T[], from: number, to: number): T[] {
        if (to < 0 || to >= items.length) return items;
        const next = [...items];
        const [selected] = next.splice(from, 1);
        next.splice(to, 0, selected);
        return next;
    }

    const itemLocked = Boolean(assignment?.has_submissions);

    const steps = [
        {
            id: 1 as const,
            title: '1. Detail & Target',
            shortTitle: 'Detail',
            subtitle: 'Judul, Tipe & Kelas',
            icon: FileText,
            hasError: Boolean(
                clientErrors.title ||
                    clientErrors.synced_class_ids ||
                    errors.title ||
                    errors.synced_class_ids ||
                    errors.description
            ),
        },
        {
            id: 2 as const,
            title: '2. Soal & Konten',
            shortTitle: 'Soal',
            subtitle:
                form.data.assignment_type === 'worksheet'
                    ? 'Worksheet Builder'
                    : form.data.assignment_type === 'quiz'
                        ? 'Quiz Builder'
                        : 'Metode Pengumpulan',
            icon: ListChecks,
            hasError: Boolean(
                clientErrors.worksheet_items ||
                    clientErrors.quiz_questions ||
                    errors.worksheet_items ||
                    errors.quiz_questions ||
                    Object.keys(errors).some(
                        (k) => k.startsWith('worksheet_items.') || k.startsWith('quiz_questions.')
                    )
            ),
        },
        {
            id: 3 as const,
            title: '3. Jadwal & Aturan',
            shortTitle: 'Jadwal',
            subtitle: 'Ketersediaan & Batas Waktu',
            icon: HelpCircle,
            hasError: Boolean(
                errors.due_date ||
                    errors.max_points ||
                    Object.keys(errors).some((k) => k.startsWith('availability_overrides'))
            ),
        },
    ];

    return (
        <AuthenticatedLayout
            title={editing ? 'Edit Penugasan' : 'Tambah Penugasan'}
            backHref={`/materials/${material.id}`}
        >
            <Head title={editing ? 'Edit Penugasan' : 'Tambah Penugasan'} />

            <div className="mx-auto max-w-5xl">
                {/* Draft notification banner */}
                {hasDraft && !editing && !draftDismissed && (
                    <div className="glass mb-6 flex flex-col gap-3 rounded-2xl border border-sky-500/30 bg-sky-500/10 p-4 sm:flex-row sm:items-center sm:justify-between shadow-sm animate-in fade-in duration-200">
                        <div className="flex items-center gap-3">
                            <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-sky-500/20 text-sky-400">
                                <RotateCcw className="h-4.5 w-4.5" />
                            </div>
                            <div>
                                <h4 className="text-sm font-semibold text-sky-200">Ditemukan Draf Belum Selesai</h4>
                                <p className="text-xs text-text-muted">
                                    Sistem menemukan isian tugas yang tersimpan otomatis di browser ini. Ingin memulihkannya?
                                </p>
                            </div>
                        </div>
                        <div className="flex items-center gap-2 self-end sm:self-center">
                            <button
                                type="button"
                                onClick={restoreDraft}
                                className="rounded-xl bg-sky-500 px-3.5 py-1.5 text-xs font-bold text-white shadow-sm hover:bg-sky-600 transition-colors"
                            >
                                Pulihkan Draf
                            </button>
                            <button
                                type="button"
                                onClick={discardDraft}
                                className="rounded-xl border border-border bg-surface px-3 py-1.5 text-xs font-medium text-text-muted hover:bg-surface-hover transition-colors"
                            >
                                Buang Draf
                            </button>
                        </div>
                    </div>
                )}

                {/* Hybrid Stepper Tabs Header */}
                <div className="glass sticky top-4 z-20 mb-6 rounded-2xl border border-border/80 p-2 shadow-lg backdrop-blur-md">
                    <div className="grid grid-cols-3 gap-2">
                        {steps.map((step) => {
                            const isActive = currentStep === step.id;
                            const isCompleted = currentStep > step.id;
                            const hasError = step.hasError;
                            const StepIcon = step.icon;

                            return (
                                <button
                                    key={step.id}
                                    type="button"
                                    onClick={() => handleTabClick(step.id)}
                                    className={cn(
                                        'group relative flex items-center gap-2.5 sm:gap-3 rounded-xl px-2.5 py-2 sm:px-3.5 sm:py-2.5 text-left transition-all',
                                        isActive
                                            ? 'bg-primary-500/15 border border-primary-500/40 text-primary-300 shadow-sm'
                                            : isCompleted
                                                ? 'bg-surface/60 border border-border/50 text-text hover:bg-surface-hover'
                                                : 'border border-transparent text-text-muted hover:bg-surface/40 hover:text-text'
                                    )}
                                >
                                    <div
                                        className={cn(
                                            'flex h-7 w-7 sm:h-8 sm:w-8 shrink-0 items-center justify-center rounded-lg text-xs font-bold transition-colors',
                                            isActive
                                                ? 'bg-primary-500 text-white shadow-sm'
                                                : isCompleted
                                                    ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
                                                    : 'bg-surface border border-border text-text-muted'
                                        )}
                                    >
                                        {isCompleted ? (
                                            <CheckCircle className="h-4 w-4 text-emerald-400" />
                                        ) : (
                                            step.id
                                        )}
                                    </div>
                                    <div className="min-w-0 flex-1">
                                        <div className="flex items-center gap-1.5">
                                            <span
                                                className={cn(
                                                    'text-xs font-bold truncate',
                                                    isActive ? 'text-primary-300' : 'text-text'
                                                )}
                                            >
                                                <span className="sm:hidden">{step.shortTitle}</span>
                                                <span className="hidden sm:inline">{step.title}</span>
                                            </span>
                                            {hasError && (
                                                <span
                                                    className="h-2 w-2 shrink-0 rounded-full bg-rose-500 ring-2 ring-rose-500/20"
                                                    title="Ada isian yang perlu diperbaiki"
                                                />
                                            )}
                                        </div>
                                        <p className="truncate text-[11px] text-text-muted hidden sm:block">
                                            {step.subtitle}
                                        </p>
                                    </div>
                                </button>
                            );
                        })}
                    </div>
                </div>

                {/* Form Body */}
                <form onSubmit={submit} className="space-y-6">
                    {/* ================= STEP 1: DETAIL & TARGET ================= */}
                    {currentStep === 1 && (
                        <div className="space-y-6 animate-in fade-in duration-150">
                            <section className="glass rounded-2xl p-6 space-y-5">
                                <div>
                                    <p className="text-xs font-bold uppercase tracking-wider text-primary-400">
                                        {material.subject?.name || 'Mata Pelajaran'}
                                    </p>
                                    <h2 className="mt-1 text-xl font-bold text-text-light">{material.title}</h2>
                                </div>

                                <div>
                                    <label className="mb-1.5 block text-sm font-medium text-text-muted">
                                        Judul Penugasan <span className="text-rose-400">*</span>
                                    </label>
                                    <input
                                        value={form.data.title}
                                        onChange={(event) => {
                                            form.setData('title', event.target.value);
                                            if (clientErrors.title) {
                                                setClientErrors((prev) => {
                                                    const next = { ...prev };
                                                    delete next.title;
                                                    return next;
                                                });
                                            }
                                        }}
                                        className={cn(
                                            'w-full rounded-xl border bg-surface px-4 py-2.5 text-sm transition-colors',
                                            clientErrors.title || errors.title
                                                ? 'border-rose-500 ring-1 ring-rose-500/20'
                                                : 'border-border focus:border-primary-500'
                                        )}
                                        placeholder="Contoh: LKPD 1 - Struktur Teks Prosedur"
                                        required
                                    />
                                    {(clientErrors.title || errors.title) && (
                                        <p className="mt-1 text-xs text-rose-400">
                                            {clientErrors.title || errors.title}
                                        </p>
                                    )}
                                </div>

                                <div>
                                    <label className="mb-1.5 block text-sm font-medium text-text-muted">
                                        Petunjuk Pengerjaan
                                    </label>
                                    <RichTextEditor
                                        compact
                                        value={form.data.description}
                                        onChange={(value) => form.setData('description', value)}
                                        placeholder="Tuliskan petunjuk untuk siswa..."
                                    />
                                </div>

                                <div>
                                    <div className="flex items-center justify-between mb-2">
                                        <label className="block text-sm font-medium text-text-muted">
                                            Kategori Asesmen (Kurikulum Merdeka) <span className="text-rose-400">*</span>
                                        </label>
                                        <span className="text-[11px] text-text-muted hidden sm:inline">
                                            Formatif LKPD vs Sumatif Lingkup Materi
                                        </span>
                                    </div>
                                    <div className="grid gap-3 sm:grid-cols-2">
                                        {(Object.values(ASSESSMENT_CATEGORIES) as Array<typeof ASSESSMENT_CATEGORIES[keyof typeof ASSESSMENT_CATEGORIES]>).map((cat) => {
                                            const isSelected = form.data.category === cat.key;
                                            return (
                                                <button
                                                    key={cat.key}
                                                    type="button"
                                                    onClick={() => form.setData('category', cat.key)}
                                                    className={cn(
                                                        'rounded-xl border-2 p-3.5 text-left transition-all',
                                                        isSelected
                                                            ? 'border-primary-500 bg-primary-500/10 shadow-sm'
                                                            : 'border-border bg-surface hover:border-border-hover'
                                                    )}
                                                >
                                                    <div className="flex items-center justify-between gap-2">
                                                        <span className="font-bold text-sm text-text-light">{cat.label}</span>
                                                        <span className={cn('text-[10px] px-2 py-0.5 rounded-md font-semibold shrink-0', cat.badgeClass)}>
                                                            {cat.shortLabel}
                                                        </span>
                                                    </div>
                                                    <span className="mt-1 block text-xs text-text-muted leading-relaxed">
                                                        {cat.description}
                                                    </span>
                                                </button>
                                            );
                                        })}
                                    </div>
                                </div>

                                <div>
                                    <label className="mb-2 block text-sm font-medium text-text-muted">
                                        Tipe Penugasan
                                    </label>
                                    <div className="grid gap-3 sm:grid-cols-3">
                                        {(
                                            [
                                                ['worksheet', 'Worksheet', 'LKPD interaktif & autosave'],
                                                ['standard', 'Tugas Biasa', 'Teks, file, link, atau fisik'],
                                                ['quiz', 'Quiz', 'Pilihan ganda otomatis'],
                                            ] as const
                                        ).map(([type, label, description]) => (
                                            <button
                                                key={type}
                                                type="button"
                                                disabled={itemLocked}
                                                onClick={() => form.setData('assignment_type', type)}
                                                className={cn(
                                                    'rounded-xl border-2 p-4 text-left transition-all disabled:opacity-60',
                                                    form.data.assignment_type === type
                                                        ? 'border-primary-500 bg-primary-500/10 shadow-sm'
                                                        : 'border-border bg-surface hover:border-border-hover'
                                                )}
                                            >
                                                <span className="font-bold text-text-light">{label}</span>
                                                <span className="mt-1 block text-xs text-text-muted">
                                                    {description}
                                                </span>
                                            </button>
                                        ))}
                                    </div>
                                    {itemLocked && (
                                        <p className="mt-2 rounded-xl bg-amber-500/10 p-3 text-xs text-amber-300">
                                            Pertanyaan dikunci karena siswa sudah mulai mengerjakan. Judul, deadline,
                                            dan opsi submit ulang tetap dapat diperbarui.
                                        </p>
                                    )}
                                </div>
                            </section>

                            {/* Target Kelas Penugasan */}
                            {availableClasses.length > 1 && (
                                <section className="glass rounded-2xl p-6 space-y-3">
                                    <div className="flex flex-wrap items-center justify-between gap-2">
                                        <div>
                                            <h3 className="text-sm font-bold text-text-light">
                                                Target Kelas Penugasan
                                            </h3>
                                            <p className="text-xs text-text-muted">
                                                Pilih kelas yang menerima tugas ini. Siswa di kelas lain tidak akan
                                                melihat tugas ini.
                                            </p>
                                        </div>
                                        {!itemLocked && (
                                            <div className="flex items-center gap-2 text-xs">
                                                <button
                                                    type="button"
                                                    onClick={() => {
                                                        form.setData(
                                                            'synced_class_ids',
                                                            availableClasses.map((c) => c.id)
                                                        );
                                                        if (clientErrors.synced_class_ids) {
                                                            setClientErrors((prev) => {
                                                                const next = { ...prev };
                                                                delete next.synced_class_ids;
                                                                return next;
                                                            });
                                                        }
                                                    }}
                                                    className="text-primary-400 hover:underline"
                                                >
                                                    Pilih Semua
                                                </button>
                                                <span className="text-text-muted">·</span>
                                                <button
                                                    type="button"
                                                    onClick={() => {
                                                        if (availableClasses.length > 0) {
                                                            form.setData('synced_class_ids', [availableClasses[0].id]);
                                                        }
                                                    }}
                                                    className="text-text-muted hover:underline"
                                                >
                                                    Hanya 1 Kelas
                                                </button>
                                            </div>
                                        )}
                                    </div>

                                    <div className="flex flex-wrap gap-2.5 pt-1">
                                        {availableClasses.map((c) => {
                                            const isChecked = form.data.synced_class_ids.includes(c.id);
                                            return (
                                                <button
                                                    key={c.id}
                                                    type="button"
                                                    disabled={itemLocked}
                                                    onClick={() => {
                                                        const current = form.data.synced_class_ids;
                                                        let next: number[];
                                                        if (isChecked) {
                                                            if (current.length === 1) return;
                                                            next = current.filter((id) => id !== c.id);
                                                        } else {
                                                            next = [...current, c.id];
                                                        }
                                                        form.setData('synced_class_ids', next);
                                                        if (clientErrors.synced_class_ids) {
                                                            setClientErrors((prev) => {
                                                                const n = { ...prev };
                                                                delete n.synced_class_ids;
                                                                return n;
                                                            });
                                                        }
                                                    }}
                                                    className={cn(
                                                        'inline-flex items-center gap-2 rounded-xl border px-3.5 py-2 text-sm font-semibold transition-all disabled:opacity-60',
                                                        isChecked
                                                            ? 'border-primary-500 bg-primary-500/15 text-primary-300 shadow-sm'
                                                            : 'border-border bg-surface text-text-muted hover:border-border-hover'
                                                    )}
                                                >
                                                    <span
                                                        className={cn(
                                                            'flex h-4 w-4 items-center justify-center rounded border text-[10px] font-bold',
                                                            isChecked
                                                                ? 'border-primary-400 bg-primary-500 text-white'
                                                                : 'border-border'
                                                        )}
                                                    >
                                                        {isChecked ? '✓' : ''}
                                                    </span>
                                                    {c.name}
                                                </button>
                                            );
                                        })}
                                    </div>
                                    {(clientErrors.synced_class_ids || errors.synced_class_ids) && (
                                        <p className="text-xs text-rose-400">
                                            {clientErrors.synced_class_ids || errors.synced_class_ids}
                                        </p>
                                    )}
                                </section>
                            )}
                        </div>
                    )}

                    {/* ================= STEP 2: SOAL & KONTEN ================= */}
                    {currentStep === 2 && (
                        <div className="space-y-6 animate-in fade-in duration-150">
                            {/* Standard Assignment */}
                            {form.data.assignment_type === 'standard' && (
                                <section className="glass rounded-2xl p-6 space-y-4">
                                    <div className="flex items-center gap-3">
                                        <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary-500/15 text-primary-400">
                                            <FileText className="h-5 w-5" />
                                        </div>
                                        <div>
                                            <h3 className="text-base font-bold text-text-light">
                                                Tugas Biasa (Standard)
                                            </h3>
                                            <p className="text-xs text-text-muted">
                                                Pilih metode yang digunakan siswa untuk mengumpulkan tugas ini.
                                            </p>
                                        </div>
                                    </div>

                                    <div className="pt-2">
                                        <label className="mb-2 block text-sm font-medium text-text-muted">
                                            Cara Mengumpulkan
                                        </label>
                                        <select
                                            value={form.data.submission_type}
                                            onChange={(event) =>
                                                form.setData('submission_type', event.target.value as any)
                                            }
                                            className="w-full rounded-xl border border-border bg-surface px-4 py-2.5 text-sm focus:border-primary-500"
                                        >
                                            <option value="text">Jawaban Teks (Siswa mengetik langsung di editor)</option>
                                            <option value="file">Upload File (Dokumen, Foto, Video MP4)</option>
                                            <option value="link">
                                                Tautan Web (Link Google Docs, Canva, Github, dll.)
                                            </option>
                                            <option value="physical">Kumpul Fisik (Buku catatan, kertas ulangan)</option>
                                        </select>
                                        {form.data.submission_type === 'file' && (
                                            <AssignmentStorageFields value={form.data.file_storage} onChange={(value) => form.setData('file_storage', value)} drive={drive} error={errors.file_storage} />
                                        )}
                                    </div>

                                    <div className="rounded-xl border border-sky-500/20 bg-sky-500/5 p-4 text-xs text-text-muted leading-relaxed">
                                        💡 <strong>Informasi:</strong> Tugas biasa tidak memerlukan pengisian butir soal
                                        interaktif di langkah ini. Soal atau panduan pengerjaan dapat ditulis pada petunjuk
                                        di Langkah 1. Silakan lanjutkan ke <strong>Langkah 3 (Jadwal & Aturan)</strong>{' '}
                                        untuk mengatur tenggat waktu dan ketersediaan kelas.
                                    </div>
                                </section>
                            )}

                            {/* Worksheet Builder */}
                            {form.data.assignment_type === 'worksheet' && (
                                <section className="glass rounded-2xl p-6 space-y-5">
                                    <div className="flex flex-wrap items-center justify-between gap-3">
                                        <div>
                                            <h3 className="text-lg font-semibold text-text-light">Worksheet Builder</h3>
                                            <p className="text-xs text-text-muted">
                                                Total nilai:{' '}
                                                <strong className="text-primary-300 font-bold">{worksheetTotal}</strong>{' '}
                                                poin
                                            </p>
                                        </div>
                                        <button
                                            type="button"
                                            disabled={itemLocked}
                                            onClick={() =>
                                                form.setData('worksheet_items', [
                                                    ...form.data.worksheet_items,
                                                    blankWorksheetItem(),
                                                ])
                                            }
                                            className="inline-flex items-center gap-1 rounded-lg bg-primary-500 px-3 py-2 text-xs font-bold text-white shadow-sm hover:bg-primary-600 transition-colors disabled:opacity-50"
                                        >
                                            <Plus className="h-4 w-4" /> Tambah Pertanyaan
                                        </button>
                                    </div>

                                    {(clientErrors.worksheet_items || errors.worksheet_items) && (
                                        <p className="text-sm text-rose-400">
                                            {clientErrors.worksheet_items || errors.worksheet_items}
                                        </p>
                                    )}

                                    {form.data.worksheet_items.map((item, index) => (
                                        <article
                                            key={item.id ?? index}
                                            className="rounded-2xl border border-border/50 bg-surface/60 p-5 space-y-4 shadow-sm"
                                        >
                                            <div className="flex flex-wrap items-center gap-2">
                                                <span className="mr-auto text-sm font-bold text-text-light">
                                                    Pertanyaan {index + 1}
                                                </span>
                                                <button
                                                    type="button"
                                                    disabled={itemLocked || index === 0}
                                                    onClick={() =>
                                                        form.setData(
                                                            'worksheet_items',
                                                            move(form.data.worksheet_items, index, index - 1)
                                                        )
                                                    }
                                                    className="rounded-lg p-1.5 text-text-muted hover:bg-surface-hover disabled:opacity-30"
                                                    title="Pindah ke atas"
                                                >
                                                    <ArrowUp className="h-4 w-4" />
                                                </button>
                                                <button
                                                    type="button"
                                                    disabled={itemLocked || index === form.data.worksheet_items.length - 1}
                                                    onClick={() =>
                                                        form.setData(
                                                            'worksheet_items',
                                                            move(form.data.worksheet_items, index, index + 1)
                                                        )
                                                    }
                                                    className="rounded-lg p-1.5 text-text-muted hover:bg-surface-hover disabled:opacity-30"
                                                    title="Pindah ke bawah"
                                                >
                                                    <ArrowDown className="h-4 w-4" />
                                                </button>
                                                <button
                                                    type="button"
                                                    disabled={itemLocked || form.data.worksheet_items.length === 1}
                                                    onClick={() =>
                                                        form.setData(
                                                            'worksheet_items',
                                                            form.data.worksheet_items.filter(
                                                                (_, itemIndex) => itemIndex !== index
                                                            )
                                                        )
                                                    }
                                                    className="rounded-lg p-1.5 text-rose-400 hover:bg-rose-500/10 disabled:opacity-30"
                                                    title="Hapus pertanyaan"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </button>
                                            </div>

                                            <div className="grid gap-3 sm:grid-cols-3">
                                                <select
                                                    disabled={itemLocked}
                                                    value={item.item_type}
                                                    onChange={(event) =>
                                                        changeWorksheetType(index, event.target.value as WorksheetType)
                                                    }
                                                    className="rounded-xl border border-border bg-surface px-3 py-2 text-sm disabled:opacity-60"
                                                >
                                                    <option value="short_answer">Short Answer</option>
                                                    <option value="paragraph">Paragraph</option>
                                                    <option value="multiple_choice">Multiple Choice</option>
                                                    <option value="ordering">Menyusun Urutan</option>
                                                </select>
                                                <label className="flex items-center gap-2 rounded-xl border border-border bg-surface px-3 py-2 text-sm">
                                                    <input
                                                        type="checkbox"
                                                        disabled={itemLocked}
                                                        checked={item.is_required}
                                                        onChange={(event) =>
                                                            updateWorksheetItem(index, {
                                                                is_required: event.target.checked,
                                                            })
                                                        }
                                                    />{' '}
                                                    Wajib dijawab
                                                </label>
                                                <label className="flex items-center gap-2 rounded-xl border border-border bg-surface px-3 py-2 text-sm">
                                                    Poin{' '}
                                                    <input
                                                        type="number"
                                                        disabled={itemLocked}
                                                        min={1}
                                                        max={1000}
                                                        value={item.points}
                                                        onChange={(event) =>
                                                            updateWorksheetItem(index, {
                                                                points: Number(event.target.value),
                                                            })
                                                        }
                                                        className="min-w-0 flex-1 bg-transparent text-right font-semibold text-primary-300"
                                                    />
                                                </label>
                                            </div>

                                            <RichTextEditor
                                                compact
                                                value={item.prompt}
                                                onChange={(value) => updateWorksheetItem(index, { prompt: value })}
                                                placeholder="Tuliskan pertanyaan..."
                                            />
                                            {errors[`worksheet_items.${index}.prompt`] && (
                                                <p className="text-xs text-rose-400">
                                                    {errors[`worksheet_items.${index}.prompt`]}
                                                </p>
                                            )}

                                            {item.item_type === 'short_answer' && (
                                                <div>
                                                    <label className="mb-1 block text-xs font-medium text-text-muted">
                                                        Kunci jawaban otomatis (pisahkan dengan koma, boleh kosong untuk
                                                        dinilai manual)
                                                    </label>
                                                    <input
                                                        disabled={itemLocked}
                                                        value={(item.answer_key.accepted_answers || []).join(', ')}
                                                        onChange={(event) =>
                                                            updateWorksheetItem(index, {
                                                                answer_key: {
                                                                    accepted_answers: event.target.value
                                                                        .split(',')
                                                                        .map((value) => value.trim())
                                                                        .filter(Boolean),
                                                                },
                                                            })
                                                        }
                                                        className="w-full rounded-xl border border-border bg-surface px-3 py-2 text-sm"
                                                    />
                                                </div>
                                            )}

                                            {(item.item_type === 'multiple_choice' ||
                                                item.item_type === 'ordering') && (
                                                <div className="space-y-2">
                                                    <p className="text-xs font-medium text-text-muted">
                                                        {item.item_type === 'ordering'
                                                            ? 'Urutkan bagian sesuai urutan benar.'
                                                            : 'Tandai satu jawaban benar.'}
                                                    </p>
                                                    {item.options.map((option, optionIndex) => (
                                                        <div key={option.id ?? optionIndex} className="space-y-1">
                                                            <div className="flex items-center gap-2">
                                                                {item.item_type === 'multiple_choice' ? (
                                                                    <button
                                                                        type="button"
                                                                        disabled={itemLocked}
                                                                        onClick={() =>
                                                                            updateWorksheetItem(index, {
                                                                                options: item.options.map(
                                                                                    (value, valueIndex) => ({
                                                                                        ...value,
                                                                                        is_correct:
                                                                                            valueIndex === optionIndex,
                                                                                    })
                                                                                ),
                                                                            })
                                                                        }
                                                                        className={cn(
                                                                            'flex h-7 w-7 shrink-0 items-center justify-center rounded-full border-2 transition-colors',
                                                                            option.is_correct
                                                                                ? 'border-emerald-500 bg-emerald-500'
                                                                                : 'border-border'
                                                                        )}
                                                                    >
                                                                        <CheckCircle
                                                                            className={`h-4 w-4 ${option.is_correct ? 'text-white' : 'text-transparent'}`}
                                                                        />
                                                                    </button>
                                                                ) : (
                                                                    <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary-500/10 text-xs font-bold text-primary-300">
                                                                        {optionIndex + 1}
                                                                    </span>
                                                                )}
                                                                <input
                                                                    disabled={itemLocked}
                                                                    value={option.text}
                                                                    onChange={(event) =>
                                                                        updateWorksheetOption(index, optionIndex, {
                                                                            text: event.target.value,
                                                                        })
                                                                    }
                                                                    className="min-w-0 flex-1 rounded-xl border border-border bg-surface px-3 py-2 text-sm"
                                                                    required
                                                                />
                                                                {item.item_type === 'ordering' && (
                                                                    <>
                                                                        <button
                                                                            type="button"
                                                                            disabled={itemLocked || optionIndex === 0}
                                                                            onClick={() =>
                                                                                updateWorksheetItem(index, {
                                                                                    options: move(
                                                                                        item.options,
                                                                                        optionIndex,
                                                                                        optionIndex - 1
                                                                                    ),
                                                                                })
                                                                            }
                                                                            className="p-1 text-text-muted hover:text-text disabled:opacity-30"
                                                                        >
                                                                            <ArrowUp className="h-4 w-4" />
                                                                        </button>
                                                                        <button
                                                                            type="button"
                                                                            disabled={
                                                                                itemLocked ||
                                                                                optionIndex === item.options.length - 1
                                                                            }
                                                                            onClick={() =>
                                                                                updateWorksheetItem(index, {
                                                                                    options: move(
                                                                                        item.options,
                                                                                        optionIndex,
                                                                                        optionIndex + 1
                                                                                    ),
                                                                                })
                                                                            }
                                                                            className="p-1 text-text-muted hover:text-text disabled:opacity-30"
                                                                        >
                                                                            <ArrowDown className="h-4 w-4" />
                                                                        </button>
                                                                    </>
                                                                )}
                                                                <button
                                                                    type="button"
                                                                    disabled={itemLocked || item.options.length <= 2}
                                                                    onClick={() =>
                                                                        updateWorksheetItem(index, {
                                                                            options: item.options.filter(
                                                                                (_, valueIndex) =>
                                                                                    valueIndex !== optionIndex
                                                                            ),
                                                                        })
                                                                    }
                                                                    className="p-1 text-rose-400 hover:bg-rose-500/10 disabled:opacity-30"
                                                                >
                                                                    <Trash2 className="h-4 w-4" />
                                                                </button>
                                                            </div>
                                                            {errors[
                                                                `worksheet_items.${index}.options.${optionIndex}.text`
                                                            ] && (
                                                                <p className="text-xs text-rose-400 ml-9">
                                                                    {
                                                                        errors[
                                                                            `worksheet_items.${index}.options.${optionIndex}.text`
                                                                        ]
                                                                    }
                                                                </p>
                                                            )}
                                                        </div>
                                                    ))}
                                                    <button
                                                        type="button"
                                                        disabled={itemLocked || item.options.length >= 20}
                                                        onClick={() =>
                                                            updateWorksheetItem(index, {
                                                                options: [
                                                                    ...item.options,
                                                                    { id: newOptionId(), text: '', is_correct: false },
                                                                ],
                                                            })
                                                        }
                                                        className="text-xs font-semibold text-primary-400 hover:underline"
                                                    >
                                                        + Tambah opsi
                                                    </button>
                                                    {errors[`worksheet_items.${index}.options`] && (
                                                        <p className="text-xs text-rose-400">
                                                            {errors[`worksheet_items.${index}.options`]}
                                                        </p>
                                                    )}
                                                </div>
                                            )}
                                        </article>
                                    ))}

                                    <div className="pt-4 border-t border-border/50 flex justify-center">
                                        <button
                                            type="button"
                                            disabled={itemLocked}
                                            onClick={() =>
                                                form.setData('worksheet_items', [
                                                    ...form.data.worksheet_items,
                                                    blankWorksheetItem(),
                                                ])
                                            }
                                            className="inline-flex items-center gap-2 rounded-xl border-2 border-primary-500/20 bg-surface px-6 py-3 text-sm font-bold text-primary-400 transition-colors hover:bg-primary-500/10 disabled:opacity-50 shadow-sm"
                                        >
                                            <Plus className="h-5 w-5" /> Tambah Pertanyaan Berikutnya
                                        </button>
                                    </div>
                                </section>
                            )}

                            {/* Quiz Builder */}
                            {form.data.assignment_type === 'quiz' && (
                                <section className="glass rounded-2xl p-6 space-y-5">
                                    <div className="flex flex-wrap items-center justify-between gap-3">
                                        <div>
                                            <h3 className="text-lg font-semibold text-text-light">Quiz Builder</h3>
                                            <p className="text-xs text-text-muted">
                                                Jawaban dinilai otomatis & skor terbaik masuk leaderboard.
                                            </p>
                                        </div>
                                        <button
                                            type="button"
                                            disabled={itemLocked}
                                            onClick={() =>
                                                form.setData('quiz_questions', [
                                                    ...form.data.quiz_questions,
                                                    blankQuizQuestion(),
                                                ])
                                            }
                                            className="rounded-lg bg-primary-500 px-3 py-2 text-xs font-bold text-white shadow-sm hover:bg-primary-600 transition-colors disabled:opacity-50"
                                        >
                                            + Tambah Soal
                                        </button>
                                    </div>

                                    {(clientErrors.quiz_questions || errors.quiz_questions) && (
                                        <p className="text-sm text-rose-400">
                                            {clientErrors.quiz_questions || errors.quiz_questions}
                                        </p>
                                    )}

                                    {/* Quiz config */}
                                    <div className="rounded-xl border border-border/50 bg-surface/60 p-4 grid gap-4 sm:grid-cols-3">
                                        <label className="flex flex-col gap-1 text-xs font-medium text-text-muted">
                                            Maks. percobaan
                                            <input
                                                type="number"
                                                min={1}
                                                max={10}
                                                disabled={itemLocked}
                                                value={form.data.quiz_config.max_attempts ?? 3}
                                                onChange={(event) =>
                                                    form.setData('quiz_config', {
                                                        ...form.data.quiz_config,
                                                        max_attempts: Number(event.target.value),
                                                    })
                                                }
                                                className="rounded-lg border border-border bg-surface px-3 py-2 text-sm disabled:opacity-60"
                                            />
                                        </label>
                                        <label className="flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-2.5 text-xs font-medium text-text-muted">
                                            <input
                                                type="checkbox"
                                                disabled={itemLocked}
                                                checked={form.data.quiz_config.shuffle_questions ?? true}
                                                onChange={(event) =>
                                                    form.setData('quiz_config', {
                                                        ...form.data.quiz_config,
                                                        shuffle_questions: event.target.checked,
                                                    })
                                                }
                                            />
                                            Acak urutan soal
                                        </label>
                                        <label className="flex items-center gap-2 rounded-lg border border-border bg-surface px-3 py-2.5 text-xs font-medium text-text-muted">
                                            <input
                                                type="checkbox"
                                                disabled={itemLocked}
                                                checked={form.data.quiz_config.shuffle_options ?? true}
                                                onChange={(event) =>
                                                    form.setData('quiz_config', {
                                                        ...form.data.quiz_config,
                                                        shuffle_options: event.target.checked,
                                                    })
                                                }
                                            />
                                            Acak urutan opsi
                                        </label>
                                    </div>

                                    {form.data.quiz_questions.map((question, index) => (
                                        <article
                                            key={question.id ?? index}
                                            className="rounded-xl border border-border bg-surface/60 p-4 space-y-3 shadow-sm"
                                        >
                                            <div className="flex flex-wrap items-center gap-2">
                                                <strong className="mr-auto text-sm text-text-light">
                                                    Soal {index + 1}
                                                </strong>
                                                <select
                                                    disabled={itemLocked}
                                                    value={question.item_type}
                                                    onChange={(event) => {
                                                        const type = event.target.value as QuizQuestion['item_type'];
                                                        form.setData(
                                                            'quiz_questions',
                                                            form.data.quiz_questions.map((value, valueIndex) =>
                                                                valueIndex === index
                                                                    ? {
                                                                          ...value,
                                                                          item_type: type,
                                                                          options:
                                                                              type === 'true_false'
                                                                                  ? TRUE_FALSE_OPTIONS(true)
                                                                                  : [
                                                                                        { text: '', is_correct: true },
                                                                                        { text: '', is_correct: false },
                                                                                    ],
                                                                      }
                                                                    : value
                                                            )
                                                        );
                                                    }}
                                                    className="rounded-lg border border-border bg-surface px-2 py-1 text-xs disabled:opacity-60"
                                                >
                                                    <option value="multiple_choice">Pilihan Ganda</option>
                                                    <option value="true_false">Benar / Salah</option>
                                                </select>
                                                <input
                                                    type="number"
                                                    min={1}
                                                    disabled={itemLocked}
                                                    value={question.points}
                                                    onChange={(event) =>
                                                        form.setData(
                                                            'quiz_questions',
                                                            form.data.quiz_questions.map((value, valueIndex) =>
                                                                valueIndex === index
                                                                    ? { ...value, points: Number(event.target.value) }
                                                                    : value
                                                            )
                                                        )
                                                    }
                                                    className="w-20 rounded-lg border border-border bg-surface px-2 py-1 text-sm disabled:opacity-60"
                                                    title="Poin soal"
                                                />
                                                <button
                                                    type="button"
                                                    disabled={itemLocked}
                                                    onClick={() =>
                                                        form.setData(
                                                            'quiz_questions',
                                                            form.data.quiz_questions.filter(
                                                                (_, valueIndex) => valueIndex !== index
                                                            )
                                                        )
                                                    }
                                                    className="text-rose-400 hover:bg-rose-500/10 p-1 rounded-lg disabled:opacity-30"
                                                >
                                                    <Trash2 className="h-4 w-4" />
                                                </button>
                                            </div>

                                            <RichTextEditor
                                                compact
                                                value={question.question_text}
                                                onChange={(value) =>
                                                    form.setData(
                                                        'quiz_questions',
                                                        form.data.quiz_questions.map((item, valueIndex) =>
                                                            valueIndex === index
                                                                ? { ...item, question_text: value }
                                                                : item
                                                        )
                                                    )
                                                }
                                            />

                                            {/* Gambar soal */}
                                            <div className="flex flex-wrap items-center gap-3">
                                                <label className="flex cursor-pointer items-center gap-2 rounded-lg border border-dashed border-border bg-surface px-3 py-2 text-xs font-medium text-text-muted hover:bg-surface-hover">
                                                    <Plus className="h-4 w-4" />
                                                    {question.question_image ? 'Ganti gambar' : 'Tambah gambar soal'}
                                                    <input
                                                        type="file"
                                                        accept="image/*"
                                                        disabled={itemLocked}
                                                        className="hidden"
                                                        onChange={(event) => {
                                                            const file = event.target.files?.[0];
                                                            if (!file) return;
                                                            form.setData(
                                                                'quiz_questions',
                                                                form.data.quiz_questions.map((item, valueIndex) =>
                                                                    valueIndex === index
                                                                        ? { ...item, question_image: file }
                                                                        : item
                                                                )
                                                            );
                                                        }}
                                                    />
                                                </label>
                                                {question.question_image &&
                                                    typeof question.question_image === 'string' && (
                                                        <div className="relative">
                                                            <img
                                                                src={`/storage/${question.question_image}`}
                                                                alt="Gambar soal"
                                                                className="h-16 w-24 rounded-lg border border-border object-cover"
                                                            />
                                                            <button
                                                                type="button"
                                                                disabled={itemLocked}
                                                                onClick={() =>
                                                                    form.setData(
                                                                        'quiz_questions',
                                                                        form.data.quiz_questions.map((item, valueIndex) =>
                                                                            valueIndex === index
                                                                                ? { ...item, question_image: null }
                                                                                : item
                                                                        )
                                                                    )
                                                                }
                                                                className="absolute -top-1.5 -right-1.5 rounded-full bg-rose-500 p-0.5 text-white disabled:opacity-30"
                                                            >
                                                                <Trash2 className="h-3 w-3" />
                                                            </button>
                                                        </div>
                                                    )}
                                                {question.question_image &&
                                                    typeof question.question_image !== 'string' && (
                                                        <span className="text-xs text-primary-300 font-semibold">
                                                            Gambar baru: {question.question_image.name}
                                                        </span>
                                                    )}
                                            </div>

                                            {question.item_type === 'multiple_choice' ? (
                                                <div className="space-y-2">
                                                    {question.options.map((option, optionIndex) => (
                                                        <div key={optionIndex} className="flex items-center gap-2">
                                                            <button
                                                                type="button"
                                                                disabled={itemLocked}
                                                                onClick={() =>
                                                                    form.setData(
                                                                        'quiz_questions',
                                                                        form.data.quiz_questions.map((item, valueIndex) =>
                                                                            valueIndex === index
                                                                                ? {
                                                                                      ...item,
                                                                                      options: item.options.map(
                                                                                          (entry, entryIndex) => ({
                                                                                              ...entry,
                                                                                              is_correct:
                                                                                                  entryIndex ===
                                                                                                  optionIndex,
                                                                                          })
                                                                                      ),
                                                                                  }
                                                                                : item
                                                                        )
                                                                    )
                                                                }
                                                                className={cn(
                                                                    'h-6 w-6 rounded-full border transition-colors',
                                                                    option.is_correct
                                                                        ? 'border-emerald-500 bg-emerald-500'
                                                                        : 'border-border'
                                                                )}
                                                                title={
                                                                    option.is_correct
                                                                        ? 'Jawaban benar'
                                                                        : 'Tandai sebagai jawaban benar'
                                                                }
                                                            />
                                                            <input
                                                                disabled={itemLocked}
                                                                value={option.text}
                                                                onChange={(event) =>
                                                                    form.setData(
                                                                        'quiz_questions',
                                                                        form.data.quiz_questions.map((item, valueIndex) =>
                                                                            valueIndex === index
                                                                                ? {
                                                                                      ...item,
                                                                                      options: item.options.map(
                                                                                          (entry, entryIndex) =>
                                                                                              entryIndex === optionIndex
                                                                                                  ? {
                                                                                                        ...entry,
                                                                                                        text: event.target
                                                                                                            .value,
                                                                                                    }
                                                                                                  : entry
                                                                                      ),
                                                                                  }
                                                                                : item
                                                                        )
                                                                    )
                                                                }
                                                                className="flex-1 rounded-lg border border-border bg-surface px-3 py-2 text-sm disabled:opacity-60"
                                                                required
                                                                placeholder={`Opsi ${String.fromCharCode(65 + optionIndex)}`}
                                                            />
                                                            <button
                                                                type="button"
                                                                disabled={itemLocked || question.options.length <= 2}
                                                                onClick={() =>
                                                                    form.setData(
                                                                        'quiz_questions',
                                                                        form.data.quiz_questions.map((item, valueIndex) =>
                                                                            valueIndex === index
                                                                                ? {
                                                                                      ...item,
                                                                                      options: item.options.filter(
                                                                                          (_, entryIndex) =>
                                                                                              entryIndex !== optionIndex
                                                                                      ),
                                                                                  }
                                                                                : item
                                                                        )
                                                                    )
                                                                }
                                                                className="p-1 text-rose-400 hover:bg-rose-500/10 disabled:opacity-30"
                                                            >
                                                                <Trash2 className="h-4 w-4" />
                                                            </button>
                                                        </div>
                                                    ))}
                                                    <button
                                                        type="button"
                                                        disabled={itemLocked || question.options.length >= 20}
                                                        onClick={() =>
                                                            form.setData(
                                                                'quiz_questions',
                                                                form.data.quiz_questions.map((item, valueIndex) =>
                                                                    valueIndex === index
                                                                        ? {
                                                                              ...item,
                                                                              options: [
                                                                                  ...item.options,
                                                                                  { text: '', is_correct: false },
                                                                              ],
                                                                          }
                                                                        : item
                                                                )
                                                            )
                                                        }
                                                        className="text-xs font-semibold text-primary-400 hover:underline"
                                                    >
                                                        + Tambah opsi
                                                    </button>
                                                </div>
                                            ) : (
                                                <div className="grid gap-2 sm:grid-cols-2">
                                                    {TRUE_FALSE_OPTIONS(
                                                        question.options.some((o) => o.text === 'Benar' && o.is_correct)
                                                    ).map((option) => (
                                                        <button
                                                            key={option.text}
                                                            type="button"
                                                            disabled={itemLocked}
                                                            onClick={() =>
                                                                form.setData(
                                                                    'quiz_questions',
                                                                    form.data.quiz_questions.map((item, valueIndex) =>
                                                                        valueIndex === index
                                                                            ? {
                                                                                  ...item,
                                                                                  options: TRUE_FALSE_OPTIONS(
                                                                                      option.is_correct
                                                                                  ),
                                                                              }
                                                                            : item
                                                                    )
                                                                )
                                                            }
                                                            className={cn(
                                                                'rounded-xl border-2 px-4 py-3 text-sm font-bold transition-all',
                                                                option.is_correct
                                                                    ? 'border-emerald-500 bg-emerald-500/10 text-emerald-300'
                                                                    : 'border-border bg-surface text-text-muted'
                                                            )}
                                                        >
                                                            {option.text} {option.is_correct && '(Jawaban benar)'}
                                                        </button>
                                                    ))}
                                                </div>
                                            )}
                                        </article>
                                    ))}

                                    <div className="pt-4 border-t border-border/50 flex justify-center">
                                        <button
                                            type="button"
                                            disabled={itemLocked}
                                            onClick={() =>
                                                form.setData('quiz_questions', [
                                                    ...form.data.quiz_questions,
                                                    blankQuizQuestion(),
                                                ])
                                            }
                                            className="inline-flex items-center gap-2 rounded-xl border-2 border-primary-500/20 bg-surface px-6 py-3 text-sm font-bold text-primary-400 transition-colors hover:bg-primary-500/10 disabled:opacity-50 shadow-sm"
                                        >
                                            <Plus className="h-5 w-5" /> Tambah Soal Berikutnya
                                        </button>
                                    </div>
                                </section>
                            )}
                        </div>
                    )}

                    {/* ================= STEP 3: JADWAL & ATURAN ================= */}
                    {currentStep === 3 && (
                        <div className="space-y-6 animate-in fade-in duration-150">
                            {/* Jadwal & Rilis */}
                            <AssignmentAvailabilityFields
                                value={form.data}
                                classIds={form.data.synced_class_ids}
                                classes={availableClasses}
                                subjectId={material.subject?.id || 0}
                                releaseSchedule={releaseSchedule}
                                errors={errors}
                                onChange={(changes) =>
                                    Object.entries(changes).forEach(([key, value]) =>
                                        form.setData(key as keyof typeof form.data, value as never)
                                    )
                                }
                            />

                            {/* Nilai Maks & Izin Resubmit */}
                            <section className="glass rounded-2xl p-6 space-y-4">
                                <h3 className="text-base font-bold text-text-light">Penilaian & Batasan</h3>
                                <div className="grid gap-4 sm:grid-cols-2">
                                    <div>
                                        <label className="mb-1.5 block text-sm font-medium text-text-muted">
                                            Nilai Maksimal
                                        </label>
                                        <input
                                            type="number"
                                            min={1}
                                            disabled={form.data.assignment_type === 'worksheet'}
                                            value={
                                                form.data.assignment_type === 'worksheet'
                                                    ? worksheetTotal
                                                    : form.data.max_points
                                            }
                                            onChange={(event) => form.setData('max_points', Number(event.target.value))}
                                            className="w-full rounded-xl border border-border bg-surface px-4 py-2.5 text-sm disabled:opacity-60"
                                        />
                                        {form.data.assignment_type === 'worksheet' && (
                                            <p className="mt-1 text-xs text-text-muted">
                                                Dihitung otomatis dari total poin seluruh pertanyaan.
                                            </p>
                                        )}
                                    </div>

                                    <div>
                                        <div className="flex items-center justify-between mb-1.5">
                                            <label className="block text-sm font-medium text-text-muted">
                                                Batas Tuntas KKTP <span className="text-rose-400">*</span>
                                            </label>
                                            <span className="text-[11px] text-primary-400 font-semibold">Standar: 75</span>
                                        </div>
                                        <input
                                            type="number"
                                            min={0}
                                            max={100}
                                            value={form.data.kktp}
                                            onChange={(event) => form.setData('kktp', Number(event.target.value))}
                                            className="w-full rounded-xl border border-border bg-surface px-4 py-2.5 text-sm focus:border-primary-500"
                                            placeholder="75"
                                        />
                                        <p className="mt-1 text-xs text-text-muted">
                                            Nilai &lt; {form.data.kktp} otomatis terindikasi butuh tindak lanjut <strong className="text-amber-400">Remedial</strong>.
                                        </p>
                                    </div>
                                </div>
                                <label className="flex items-center gap-2 text-sm text-text-light pt-1">
                                    <input
                                        type="checkbox"
                                        checked={form.data.allow_resubmit}
                                        onChange={(event) => form.setData('allow_resubmit', event.target.checked)}
                                    />{' '}
                                    Izinkan submit ulang setelah guru meminta revisi
                                </label>
                            </section>

                            {/* Ringkasan Konfirmasi */}
                            <section className="glass rounded-2xl p-6 space-y-4 border border-border/80">
                                <h3 className="text-base font-bold text-text-light flex items-center gap-2">
                                    <CheckCircle className="h-4 w-4 text-primary-400" />
                                    Ringkasan Penugasan
                                </h3>
                                <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 text-xs">
                                    <div className="rounded-xl border border-border/40 bg-surface/50 p-3.5">
                                        <span className="text-text-muted block text-[11px]">Judul Tugas:</span>
                                        <strong className="text-text-light text-sm mt-0.5 block truncate">
                                            {form.data.title || '(Belum diisi)'}
                                        </strong>
                                    </div>
                                    <div className="rounded-xl border border-border/40 bg-surface/50 p-3.5">
                                        <span className="text-text-muted block text-[11px]">Kategori Asesmen:</span>
                                        <div className="mt-1 flex items-center gap-2">
                                            <span className={cn('px-2 py-0.5 rounded text-xs font-bold', getCategoryInfo(form.data.category).badgeClass)}>
                                                {getCategoryInfo(form.data.category).label}
                                            </span>
                                        </div>
                                    </div>
                                    <div className="rounded-xl border border-border/40 bg-surface/50 p-3.5">
                                        <span className="text-text-muted block text-[11px]">Tipe Instrumen:</span>
                                        <strong className="text-primary-300 text-sm mt-0.5 block uppercase tracking-wide">
                                            {form.data.assignment_type === 'worksheet'
                                                ? `Worksheet (${form.data.worksheet_items.length} Soal)`
                                                : form.data.assignment_type === 'quiz'
                                                    ? `Quiz (${form.data.quiz_questions.length} Soal)`
                                                    : 'Tugas Biasa'}
                                        </strong>
                                    </div>
                                    <div className="rounded-xl border border-border/40 bg-surface/50 p-3.5">
                                        <span className="text-text-muted block text-[11px]">Target Kelas:</span>
                                        <strong className="text-text-light text-sm mt-0.5 block truncate">
                                            {availableClasses
                                                .filter((c) => form.data.synced_class_ids.includes(c.id))
                                                .map((c) => c.name)
                                                .join(', ') || 'Semua Kelas'}
                                        </strong>
                                    </div>
                                    <div className="rounded-xl border border-border/40 bg-surface/50 p-3.5">
                                        <span className="text-text-muted block text-[11px]">Total Poin Maksimal:</span>
                                        <strong className="text-emerald-400 text-sm mt-0.5 block">
                                            {form.data.assignment_type === 'worksheet'
                                                ? worksheetTotal
                                                : form.data.max_points}{' '}
                                            Poin
                                        </strong>
                                    </div>
                                    <div className="rounded-xl border border-border/40 bg-surface/50 p-3.5">
                                        <span className="text-text-muted block text-[11px]">Batas Tuntas KKTP:</span>
                                        <strong className="text-cyan-400 text-sm mt-0.5 block">
                                            &ge; {form.data.kktp} (Tuntas)
                                        </strong>
                                    </div>
                                </div>
                            </section>
                        </div>
                    )}

                    {/* Alert jika ada error backend */}
                    {Object.keys(errors).length > 0 && (
                        <div className="rounded-2xl bg-rose-500/10 p-4 text-sm font-medium text-rose-400 border border-rose-500/20 flex items-start gap-3">
                            <AlertCircle className="h-5 w-5 shrink-0 mt-0.5" />
                            <div>
                                <p className="font-bold">Penyimpanan belum berhasil!</p>
                                <p className="text-xs mt-0.5 opacity-90">
                                    Terdapat {Object.keys(errors).length} isian yang belum lengkap atau perlu diperiksa.
                                    Periksa tab yang memiliki titik indikator merah.
                                </p>
                            </div>
                        </div>
                    )}

                    {/* ================= STICKY BOTTOM NAVIGATION BAR ================= */}
                    <div className="glass sticky bottom-4 z-20 mt-8 rounded-2xl border border-border/80 p-4 shadow-xl backdrop-blur-md flex flex-wrap items-center justify-between gap-4">
                        <div className="flex items-center gap-3">
                            <Link
                                href={`/materials/${material.id}`}
                                className="rounded-xl border border-border bg-surface px-4 py-2.5 text-sm font-semibold text-text-muted hover:bg-surface-hover hover:text-text transition-colors"
                            >
                                Batal
                            </Link>
                            {!editing && (
                                <span className="text-xs text-text-muted hidden sm:flex items-center gap-1.5">
                                    <span className="h-2 w-2 rounded-full bg-emerald-400 animate-pulse" />
                                    Draf tersimpan di browser
                                </span>
                            )}
                        </div>

                        <div className="flex items-center gap-2">
                            {currentStep > 1 && (
                                <button
                                    type="button"
                                    onClick={handleBack}
                                    className="inline-flex items-center gap-1.5 rounded-xl border border-border bg-surface px-4 py-2.5 text-sm font-semibold text-text hover:bg-surface-hover transition-colors"
                                >
                                    <ChevronLeft className="h-4 w-4" />
                                    Kembali
                                </button>
                            )}

                            {currentStep < 3 ? (
                                <button
                                    key="next-step"
                                    type="button"
                                    onClick={handleNext}
                                    className="inline-flex items-center gap-1.5 rounded-xl bg-primary-500 px-5 py-2.5 text-sm font-bold text-white shadow-sm hover:bg-primary-600 transition-colors"
                                >
                                    Lanjut ke {currentStep === 1 ? 'Soal' : 'Jadwal'}
                                    <ChevronRight className="h-4 w-4" />
                                </button>
                            ) : (
                                <button
                                    key="save-assignment"
                                    type="submit"
                                    disabled={form.processing}
                                    className="inline-flex items-center gap-2 rounded-xl bg-primary-500 px-6 py-2.5 text-sm font-bold text-white shadow-md hover:bg-primary-600 transition-colors disabled:opacity-50"
                                >
                                    <CheckCircle className="h-4 w-4" />
                                    {editing ? 'Perbarui Penugasan' : 'Simpan Penugasan'}
                                </button>
                            )}
                        </div>
                    </div>
                </form>
            </div>
        </AuthenticatedLayout>
    );
}
