"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { updateLesson } from "@/app/(protected)/teacher/actions";
import VideoUpload from "@/components/teacher/VideoUpload"; // The component you created earlier
import { getClientLocale } from "@/lib/i18n/clientLocale";
import { getLessonContentTypeLabel, lessonContentTypes, type LessonContentType } from "@/lib/courses/lessonContent";

interface LessonEditorFormProps {
    lesson: {
        id: string;
        title: string;
        description?: string | null;
        videoUrl?: string | null;
        youtubeUrl?: string | null;
        isFreePreview?: boolean;
        contentType: LessonContentType;
        materialUrl?: string | null;
        estimatedDurationMinutes: number;
    };
    courseSlug: string;
}

export function LessonEditorForm({ lesson, courseSlug }: LessonEditorFormProps) {
    const router = useRouter();
    const [loading, setLoading] = useState(false);
    const [title, setTitle] = useState(lesson.title);
    const [description, setDescription] = useState(lesson.description ?? "");
    const [youtubeUrl, setYoutubeUrl] = useState(lesson.youtubeUrl ?? "");
    const [isFreePreview, setIsFreePreview] = useState(lesson.isFreePreview ?? false);
    const [contentType, setContentType] = useState<LessonContentType>(lesson.contentType);
    const [materialUrl, setMaterialUrl] = useState(lesson.materialUrl ?? "");
    const [durationMinutes, setDurationMinutes] = useState(lesson.estimatedDurationMinutes);

    const showSavedToast = () => {
        const isSpanish = getClientLocale() === "es";
        toast.success(isSpanish ? "Cambios guardados" : "Changes saved", {
            description: isSpanish
                ? "Puedes seguir editando o volver al panel de cursos."
                : "You can keep editing or go back to the courses dashboard.",
            action: {
                label: isSpanish ? "Volver a cursos" : "Back to courses",
                onClick: () => router.push("/teacher"),
            },
            cancel: {
                label: isSpanish ? "Seguir editando" : "Keep editing",
                onClick: () => {},
            },
            duration: 7000,
        });
    };

    // 1. Auto-save Video URL when upload finishes
    const handleVideoUploaded = async (url: string) => {
        toast.loading("Guardando video...");
        const res = await updateLesson(lesson.id, { videoUrl: url });

        if (res.success) {
            toast.dismiss();
            toast.success("Video guardado correctamente");
            router.refresh(); // Update the UI to show the new video player
        } else {
            toast.error("Error al guardar el video en la base de datos");
        }
    };

    // 2. Save Text Changes (Title/Desc/YouTube/Preview)
    const handleSave = async () => {
        setLoading(true);
        const res = await updateLesson(lesson.id, {
            title,
            description,
            youtubeUrl: youtubeUrl.trim() || undefined,
            materialUrl: materialUrl.trim() || undefined,
            contentType,
            estimatedDurationMinutes: durationMinutes,
            isPreview: isFreePreview,
        });
        if (res.success) {
            showSavedToast();
            router.refresh();
        } else {
            toast.error("Error al guardar cambios");
        }
        setLoading(false);
    };

    return (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">

            {/* LEFT: Video & Content */}
            <div className="lg:col-span-2 space-y-6">

                {/* Video Upload Section */}
                <section className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
                    <div className="p-6 border-b border-slate-100">
                        <h2 className="font-semibold text-slate-900">Video del Curso</h2>
                        <p className="text-sm text-slate-500">Sube el video principal de esta lección.</p>
                    </div>
                    <div className="p-6 bg-slate-50/50">
                        <VideoUpload
                            lessonId={lesson.id}
                            currentVideoUrl={lesson.videoUrl}
                            onUploadComplete={handleVideoUploaded}
                        />
                    </div>
                    <div className="border-t border-slate-100 p-6">
                        <label className="block text-sm font-medium text-slate-700 mb-1">YouTube URL</label>
                        <input
                            type="url"
                            value={youtubeUrl}
                            onChange={(e) => setYoutubeUrl(e.target.value)}
                            placeholder="https://www.youtube.com/watch?v=..."
                            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
                        />
                        <p className="mt-1 text-xs text-slate-500">Si se proporciona, se usará en lugar del video subido en la lección.</p>
                    </div>
                </section>

                {/* Text Content */}
                <section className="bg-white rounded-xl border border-slate-200 shadow-sm p-6 space-y-4">
                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Título de la Lección</label>
                        <input
                            value={title}
                            onChange={(e) => setTitle(e.target.value)}
                            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">Descripción / Notas</label>
                        <textarea
                            rows={6}
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
                            placeholder="Escribe aquí el contenido de la lección..."
                        />
                    </div>

                    <div>
                        <label className="block text-sm font-medium text-slate-700 mb-1">URL de material (PDF / actividad / lectura)</label>
                        <input
                            type="url"
                            value={materialUrl}
                            onChange={(e) => setMaterialUrl(e.target.value)}
                            placeholder="https://.../material.pdf"
                            className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
                        />
                        <p className="mt-1 text-xs text-slate-500">Se usará en la vista del alumno como lectura o actividad descargable.</p>
                    </div>
                </section>
            </div>

            {/* RIGHT: Settings / Actions */}
            <div className="space-y-6">
                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
                    <h3 className="font-semibold text-slate-900 mb-4">Tipo de contenido</h3>
                    <label className="block text-sm text-slate-700 mb-2">Formato de la lección</label>
                    <select
                        value={contentType}
                        onChange={(e) => setContentType(e.target.value as LessonContentType)}
                        className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
                    >
                        {lessonContentTypes.map((type) => (
                            <option key={type} value={type}>
                                {getLessonContentTypeLabel(type)}
                            </option>
                        ))}
                    </select>
                    <p className="mt-2 text-xs text-slate-500">
                        Usa “Evaluación final” para marcar el examen obligatorio del curso.
                    </p>

                    <label className="block text-sm text-slate-700 mb-1 mt-4">Duración estimada (minutos)</label>
                    <input
                        type="number"
                        min={0}
                        value={durationMinutes}
                        onChange={(e) => setDurationMinutes(Math.max(0, Number(e.target.value)))}
                        className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
                    />
                </div>

                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
                    <h3 className="font-semibold text-slate-900 mb-4">Vista previa gratuita</h3>
                    <label className="flex cursor-pointer items-center gap-2">
                        <input
                            type="checkbox"
                            checked={isFreePreview}
                            onChange={(e) => setIsFreePreview(e.target.checked)}
                            className="h-4 w-4 rounded border-slate-300"
                        />
                        <span className="text-sm text-slate-700">Accesible sin inscripción (teaser)</span>
                    </label>
                    <p className="mt-2 text-xs text-slate-500">Los no inscritos podrán ver esta lección sin comprar el curso.</p>
                </div>
                <div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
                    <h3 className="font-semibold text-slate-900 mb-4">Acciones</h3>
                    <button
                        onClick={handleSave}
                        disabled={loading}
                        className="w-full bg-black text-white rounded-lg py-2.5 font-medium hover:bg-slate-800 disabled:opacity-50 transition-colors"
                    >
                        {loading ? "Guardando..." : "Guardar Cambios"}
                    </button>

                    <button
                        onClick={() => router.push(`/teacher/courses/${courseSlug}/edit`)}
                        className="w-full mt-3 bg-white border border-slate-300 text-slate-700 rounded-lg py-2.5 font-medium hover:bg-slate-50 transition-colors"
                    >
                        Volver al Curso
                    </button>
                </div>
            </div>

        </div>
    );
}
