import { useState } from 'react';
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { ArrowLeft, ExternalLink, Save, Upload } from 'lucide-react';
import RichEditor from '@/components/rich-editor';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Spinner } from '@/components/ui/spinner';
import AppLayout from '@/layouts/app-layout';

type Lesson = {
    id: number;
    title: string;
    type: 'video' | 'text' | 'pdf';
    video_url: string | null;
    content: string | null;
    file_path: string | null;
    duration_minutes: number;
    is_preview: boolean;
};

type Props = {
    course: { id: number; title: string; slug: string };
    chapter: { id: number; title: string };
    lesson: Lesson | null;
};

const selectCls =
    'border-input bg-background focus-visible:border-ring focus-visible:ring-ring/50 h-9 w-full rounded-md border px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px]';

export default function LessonEditor({ course, chapter, lesson }: Props) {
    const { auth } = usePage().props as { auth: { user: { role: string } } };
    const isAdmin = auth.user.role === 'admin';
    const courseBackUrl = isAdmin ? `/admin/courses/${course.id}` : `/instructor/courses/${course.slug}`;

    const isEdit = lesson !== null;

    const [pdfSource, setPdfSource] = useState<'link' | 'upload'>(lesson?.file_path ? 'upload' : 'link');

    const form = useForm({
        title: lesson?.title ?? '',
        type: lesson?.type ?? 'video',
        video_url: lesson?.video_url ?? '',
        content: lesson?.content ?? '',
        duration_minutes: lesson?.duration_minutes ?? 0,
        is_preview: lesson?.is_preview ?? false,
        pdf_file: null as File | null,
    });

    function submit(e: React.FormEvent) {
        e.preventDefault();
        if (isEdit) {
            form.patch(`/instructor/courses/${course.slug}/lessons/${lesson.id}`);
        } else {
            form.post(`/instructor/courses/${course.slug}/chapters/${chapter.id}/lessons`);
        }
    }

    return (
        <>
            <Head title={isEdit ? `Edit: ${lesson.title}` : 'Materi Baru'} />

            <div className="px-4 py-6 md:px-8">
                {/* Back */}
                <Link href={courseBackUrl} className="mb-5 flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
                    <ArrowLeft className="h-4 w-4" />
                    Kembali ke {course.title}
                </Link>

                <div className="grid gap-8 lg:grid-cols-[1fr_280px]">
                    {/* ── Main form ── */}
                    <form onSubmit={submit} className="flex flex-col gap-6">
                        {/* Title */}
                        <div className="grid gap-2">
                            <Label htmlFor="title" className="text-base font-semibold">
                                Judul Materi
                            </Label>
                            <Input
                                id="title"
                                value={form.data.title}
                                onChange={(e) => form.setData('title', e.target.value)}
                                placeholder="Judul materi..."
                                className="text-base"
                                required
                                autoFocus
                            />
                            <InputError message={form.errors.title} />
                        </div>

                        {/* Type + duration row */}
                        <div className="flex flex-wrap gap-4">
                            <div className="grid min-w-40 gap-1.5">
                                <Label>Tipe Konten</Label>
                                <select
                                    value={form.data.type}
                                    onChange={(e) => form.setData('type', e.target.value as Lesson['type'])}
                                    className={selectCls}
                                >
                                    <option value="video">Video</option>
                                    <option value="text">Teks / Artikel</option>
                                    <option value="pdf">PDF</option>
                                </select>
                            </div>
                            <div className="grid w-36 gap-1.5">
                                <Label>Durasi (menit)</Label>
                                <Input
                                    type="number"
                                    min="0"
                                    value={form.data.duration_minutes}
                                    onChange={(e) => form.setData('duration_minutes', Number(e.target.value))}
                                    placeholder="0"
                                />
                            </div>
                            <div className="flex items-end pb-0.5">
                                <label className="flex cursor-pointer items-center gap-2 text-sm">
                                    <input
                                        type="checkbox"
                                        checked={form.data.is_preview}
                                        onChange={(e) => form.setData('is_preview', e.target.checked)}
                                        className="h-4 w-4 rounded"
                                    />
                                    Bisa dipreview tanpa daftar
                                </label>
                            </div>
                        </div>

                        {/* Video URL */}
                        {form.data.type === 'video' && (
                            <div className="grid gap-2">
                                <Label>URL Video</Label>
                                <Input
                                    value={form.data.video_url}
                                    onChange={(e) => form.setData('video_url', e.target.value)}
                                    placeholder="https://youtube.com/watch?v=... atau https://vimeo.com/..."
                                />
                                <InputError message={form.errors.video_url} />
                                {form.data.video_url && (
                                    <p className="text-xs text-muted-foreground">Preview video akan ditampilkan saat siswa membuka materi.</p>
                                )}
                            </div>
                        )}

                        {/* PDF: toggle upload / link */}
                        {form.data.type === 'pdf' && (
                            <div className="grid gap-3">
                                <Label>File PDF</Label>

                                {/* Toggle */}
                                <div className="flex gap-2 rounded-lg border bg-muted/30 p-1 w-fit">
                                    <button
                                        type="button"
                                        onClick={() => setPdfSource('link')}
                                        className={`rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
                                            pdfSource === 'link'
                                                ? 'bg-background text-foreground shadow-xs'
                                                : 'text-muted-foreground hover:text-foreground'
                                        }`}
                                    >
                                        Link URL
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => setPdfSource('upload')}
                                        className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${
                                            pdfSource === 'upload'
                                                ? 'bg-background text-foreground shadow-xs'
                                                : 'text-muted-foreground hover:text-foreground'
                                        }`}
                                    >
                                        <Upload className="h-3.5 w-3.5" />
                                        Upload File
                                    </button>
                                </div>

                                {pdfSource === 'link' ? (
                                    <div className="grid gap-2">
                                        <Input
                                            value={form.data.video_url}
                                            onChange={(e) => form.setData('video_url', e.target.value)}
                                            placeholder="https://drive.google.com/file/d/..."
                                        />
                                        <InputError message={form.errors.video_url} />
                                    </div>
                                ) : (
                                    <div className="grid gap-2">
                                        <label className="flex cursor-pointer flex-col items-center gap-3 rounded-lg border-2 border-dashed border-border p-6 text-center transition-colors hover:border-primary/50 hover:bg-muted/30">
                                            <Upload className="h-8 w-8 text-muted-foreground" />
                                            <div>
                                                <p className="text-sm font-medium">
                                                    {form.data.pdf_file ? form.data.pdf_file.name : 'Klik untuk pilih file PDF'}
                                                </p>
                                                <p className="mt-0.5 text-xs text-muted-foreground">Maks. 20 MB</p>
                                            </div>
                                            <input
                                                type="file"
                                                accept=".pdf"
                                                className="hidden"
                                                onChange={(e) => form.setData('pdf_file', e.target.files?.[0] ?? null)}
                                            />
                                        </label>

                                        {/* Existing file in edit mode */}
                                        {isEdit && lesson.file_path && !form.data.pdf_file && (
                                            <div className="flex items-center gap-2 rounded-md bg-muted/40 px-3 py-2 text-sm">
                                                <span className="text-muted-foreground">File saat ini:</span>
                                                <a
                                                    href={`/storage/${lesson.file_path}`}
                                                    target="_blank"
                                                    rel="noreferrer"
                                                    className="flex items-center gap-1 font-medium text-primary underline-offset-2 hover:underline"
                                                >
                                                    Lihat PDF <ExternalLink className="h-3 w-3" />
                                                </a>
                                            </div>
                                        )}

                                        <InputError message={form.errors.pdf_file} />
                                    </div>
                                )}
                            </div>
                        )}

                        {/* Rich text editor */}
                        {form.data.type === 'text' && (
                            <div className="grid gap-2">
                                <Label className="text-sm font-medium">Konten Materi</Label>
                                <RichEditor
                                    value={form.data.content}
                                    onChange={(val) => form.setData('content', val)}
                                    placeholder="Tulis materi di sini... Gunakan toolbar untuk format teks, sisipkan gambar, video, atau PDF."
                                    minHeight={400}
                                />
                                <InputError message={form.errors.content} />
                            </div>
                        )}

                        <div className="flex items-center gap-3">
                            <Button type="submit" disabled={form.processing} className="gap-1.5">
                                {form.processing ? <Spinner /> : <Save className="h-4 w-4" />}
                                {isEdit ? 'Simpan Perubahan' : 'Tambah Materi'}
                            </Button>
                            {form.wasSuccessful && <span className="text-sm text-emerald-600">Tersimpan!</span>}
                        </div>
                    </form>

                    {/* ── Sidebar ── */}
                    <div className="flex flex-col gap-4">
                        {/* Info card */}
                        <div className="rounded-xl border bg-card p-4 shadow-xs">
                            <p className="mb-3 text-sm font-semibold">Info Materi</p>
                            <div className="flex flex-col gap-2 text-sm">
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">Kelas</span>
                                    <span className="max-w-32 truncate text-right font-medium">{course.title}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">Chapter</span>
                                    <span className="max-w-32 truncate text-right font-medium">{chapter.title}</span>
                                </div>
                                <div className="flex justify-between">
                                    <span className="text-muted-foreground">Tipe</span>
                                    <span className="font-medium capitalize">
                                        {form.data.type === 'video' ? 'Video' : form.data.type === 'text' ? 'Teks / Artikel' : 'PDF'}
                                    </span>
                                </div>
                            </div>
                        </div>

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

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