import { useState } from 'react';
import { Plus, GripVertical, Edit2, Trash2, Video, FileText, ChevronDown, ChevronRight, Clock, Eye, Save, X } from 'lucide-react';
import { router } from '@inertiajs/react';
import { Button } from '@/Components/ui/button';
import { Input } from '@/Components/ui/input';
import { Textarea } from '@/Components/ui/textarea';
import { Switch } from '@/Components/ui/switch';
import { Label } from '@/Components/ui/label';

interface Lesson {
    id: number;
    title: string;
    slug: string;
    content: string | null;
    video_url: string | null;
    duration: number | null;
    is_preview: boolean;
    order: number;
}

interface Module {
    id: number;
    title: string;
    description: string | null;
    order: number;
    lessons: Lesson[];
}

interface Props {
    productId: number;
    modules: Module[];
}

export default function CurriculumBuilder({ productId, modules }: Props) {
    const [expandedModules, setExpandedModules] = useState<number[]>(modules.map(m => m.id));
    
    // Inline Form states
    const [isAddingModule, setIsAddingModule] = useState(false);
    const [editingModuleId, setEditingModuleId] = useState<number | null>(null);
    const [addingLessonToModule, setAddingLessonToModule] = useState<number | null>(null);
    const [editingLessonId, setEditingLessonId] = useState<number | null>(null);
    
    // Data states
    const [moduleData, setModuleData] = useState({title: '', description: ''});
    const [lessonData, setLessonData] = useState({
        title: '', 
        content: '', 
        video_url: '', 
        duration: 0, 
        is_preview: false
    });

    const toggleModule = (id: number) => {
        setExpandedModules(prev => 
            prev.includes(id) ? prev.filter(mid => mid !== id) : [...prev, id]
        );
    };

    const resetModuleForm = () => {
        setModuleData({title: '', description: ''});
        setIsAddingModule(false);
        setEditingModuleId(null);
    };

    const resetLessonForm = () => {
        setLessonData({title: '', content: '', video_url: '', duration: 0, is_preview: false});
        setAddingLessonToModule(null);
        setEditingLessonId(null);
    };

    const handleSaveModule = () => {
        if (editingModuleId) {
            router.put(route('admin.modules.update', editingModuleId), moduleData, {
                onSuccess: () => resetModuleForm()
            });
        } else {
            router.post(route('admin.modules.store', productId), moduleData, {
                onSuccess: () => resetModuleForm()
            });
        }
    };

    const handleSaveLesson = (moduleId: number) => {
        if (editingLessonId) {
            router.put(route('admin.lessons.update', editingLessonId), lessonData, {
                onSuccess: () => resetLessonForm()
            });
        } else {
            router.post(route('admin.lessons.store', moduleId), lessonData, {
                onSuccess: () => resetLessonForm()
            });
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <h2 className="text-[20px] font-display text-ink">Course Curriculum</h2>
                {!isAddingModule && (
                    <Button 
                        onClick={() => { resetModuleForm(); setIsAddingModule(true); }}
                        variant="outline"
                        className="h-10 gap-2 rounded-xl border-[#E8E6DF] text-ink font-bold text-[12px] hover:bg-[#F5F3EF] px-5"
                    >
                        <Plus className="h-4 w-4" /> Add Module
                    </Button>
                )}
            </div>

            <div className="space-y-6">
                {modules.map((module) => (
                    <div key={module.id} className="group">
                        {editingModuleId === module.id ? (
                            <div className="bg-white border-2 border-primary/20 rounded-[2rem] p-8 shadow-xl shadow-primary/5 animate-in fade-in slide-in-from-top-2">
                                <div className="space-y-6">
                                    <div className="flex items-center justify-between">
                                        <h3 className="text-lg font-display text-ink">Edit Module</h3>
                                        <button onClick={resetModuleForm} className="text-[#8C92AC] hover:text-ink"><X className="h-5 w-5" /></button>
                                    </div>
                                    <div className="grid gap-6">
                                        <div className="space-y-2">
                                            <Label className="text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] ml-1">Module Title</Label>
                                            <Input 
                                                value={moduleData.title}
                                                onChange={e => setModuleData(prev => ({...prev, title: e.target.value}))}
                                                className="h-12 rounded-2xl border-[#E8E6DF] bg-[#FAFAF8] focus:bg-white focus:border-primary focus:ring-0 text-[14px]"
                                            />
                                        </div>
                                        <div className="space-y-2">
                                            <Label className="text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] ml-1">Description</Label>
                                            <Textarea 
                                                value={moduleData.description}
                                                onChange={e => setModuleData(prev => ({...prev, description: e.target.value}))}
                                                className="rounded-2xl border-[#E8E6DF] bg-[#FAFAF8] focus:bg-white focus:border-primary focus:ring-0 min-h-[100px] text-[14px]"
                                            />
                                        </div>
                                    </div>
                                    <div className="flex justify-end gap-3 pt-2">
                                        <Button variant="ghost" onClick={resetModuleForm} className="rounded-xl font-bold text-[12px]">Cancel</Button>
                                        <Button onClick={handleSaveModule} className="rounded-xl font-bold bg-ink text-white px-8 h-10 text-[12px]">Update Module</Button>
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="bg-white border border-[#E8E6DF] rounded-[2rem] overflow-hidden hover:border-primary/30 transition-all">
                                <div className="flex items-center justify-between p-6 bg-[#FAFAF8] border-b border-[#E8E6DF]">
                                    <div className="flex items-center gap-4">
                                        <button 
                                            onClick={() => toggleModule(module.id)}
                                            className="p-1 hover:bg-[#F0EDE8] rounded-lg transition-colors"
                                        >
                                            {expandedModules.includes(module.id) ? (
                                                <ChevronDown className="h-5 w-5 text-ink" />
                                            ) : (
                                                <ChevronRight className="h-5 w-5 text-ink" />
                                            )}
                                        </button>
                                        <div>
                                            <h3 className="font-bold text-ink">{module.title}</h3>
                                            <p className="text-[11px] text-[#8C92AC] font-medium uppercase tracking-wider">
                                                {module.lessons.length} Lessons
                                            </p>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Button 
                                            variant="ghost" 
                                            size="icon" 
                                            onClick={() => {
                                                setModuleData({title: module.title, description: module.description || ''});
                                                setEditingModuleId(module.id);
                                            }}
                                            className="h-9 w-9 rounded-xl text-[#8C92AC] hover:text-primary hover:bg-primary/5"
                                        >
                                            <Edit2 className="h-4 w-4" />
                                        </Button>
                                        <Button 
                                            variant="ghost" 
                                            size="icon" 
                                            onClick={() => { if(confirm('Delete module?')) router.delete(route('admin.modules.destroy', module.id)) }}
                                            className="h-9 w-9 rounded-xl text-[#8C92AC] hover:text-red-500 hover:bg-red-50"
                                        >
                                            <Trash2 className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>

                                {expandedModules.includes(module.id) && (
                                    <div className="p-5 space-y-4 bg-white">
                                        {module.lessons.map((lesson) => (
                                            <div key={lesson.id}>
                                                {editingLessonId === lesson.id ? (
                                                    <div className="p-6 border-2 border-primary/20 rounded-[2rem] bg-primary/5 space-y-6 animate-in fade-in zoom-in-95">
                                                        <div className="grid gap-6">
                                                            <Input 
                                                                value={lessonData.title}
                                                                onChange={e => setLessonData(prev => ({...prev, title: e.target.value}))}
                                                                placeholder="Lesson Title"
                                                                className="h-12 rounded-xl border-[#E8E6DF] bg-white px-5 font-bold"
                                                            />
                                                            <div className="grid grid-cols-2 gap-4">
                                                                <Input 
                                                                    value={lessonData.video_url}
                                                                    onChange={e => setLessonData(prev => ({...prev, video_url: e.target.value}))}
                                                                    placeholder="Video URL"
                                                                    className="h-11 rounded-xl border-[#E8E6DF]"
                                                                />
                                                                <Input 
                                                                    type="number"
                                                                    value={lessonData.duration}
                                                                    onChange={e => setLessonData(prev => ({...prev, duration: parseInt(e.target.value)}))}
                                                                    placeholder="Duration"
                                                                    className="h-11 rounded-xl border-[#E8E6DF]"
                                                                />
                                                            </div>
                                                            <Textarea 
                                                                value={lessonData.content}
                                                                onChange={e => setLessonData(prev => ({...prev, content: e.target.value}))}
                                                                placeholder="Content..."
                                                                className="rounded-xl border-[#E8E6DF] min-h-[100px]"
                                                            />
                                                            <div className="flex items-center justify-between p-4 bg-white rounded-xl border border-[#E8E6DF]">
                                                                <Label className="text-[13px] font-bold">Free Preview</Label>
                                                                <Switch checked={lessonData.is_preview} onCheckedChange={c => setLessonData(prev => ({...prev, is_preview: c}))} />
                                                            </div>
                                                        </div>
                                                        <div className="flex justify-end gap-2">
                                                            <Button variant="ghost" onClick={resetLessonForm} className="rounded-lg text-[11px] font-bold">Cancel</Button>
                                                            <Button onClick={() => handleSaveLesson(module.id)} className="rounded-lg bg-ink text-white px-6 h-9 text-[11px] font-bold">Update Lesson</Button>
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <div className="flex items-center justify-between p-4 bg-[#FAFAF8] border border-[#E8E6DF] rounded-2xl group/lesson hover:border-primary/50 transition-all">
                                                        <div className="flex items-center gap-4">
                                                            <div className="h-10 w-10 flex items-center justify-center bg-white border border-[#E8E6DF] rounded-xl text-[#8C92AC]">
                                                                {lesson.video_url ? <Video className="h-5 w-5" /> : <FileText className="h-5 w-5" />}
                                                            </div>
                                                            <div>
                                                                <h4 className="text-[14px] font-bold text-ink">{lesson.title}</h4>
                                                                <div className="flex items-center gap-3 mt-0.5">
                                                                    {lesson.duration && (
                                                                        <span className="flex items-center gap-1 text-[10px] text-[#8C92AC] font-bold uppercase">
                                                                            <Clock className="h-3 w-3" /> {lesson.duration}m
                                                                        </span>
                                                                    )}
                                                                    {lesson.is_preview && (
                                                                        <span className="flex items-center gap-1 text-[10px] text-emerald-600 font-bold uppercase">
                                                                            <Eye className="h-3 w-3" /> Preview
                                                                        </span>
                                                                    )}
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div className="flex items-center gap-1 opacity-0 group-hover/lesson:opacity-100 transition-opacity">
                                                            <Button 
                                                                variant="ghost" 
                                                                size="icon" 
                                                                onClick={() => {
                                                                    setLessonData({
                                                                        title: lesson.title,
                                                                        content: lesson.content || '',
                                                                        video_url: lesson.video_url || '',
                                                                        duration: lesson.duration || 0,
                                                                        is_preview: lesson.is_preview
                                                                    });
                                                                    setEditingLessonId(lesson.id);
                                                                }}
                                                                className="h-8 w-8 rounded-lg text-[#8C92AC] hover:text-primary"
                                                            >
                                                                <Edit2 className="h-3.5 w-3.5" />
                                                            </Button>
                                                            <Button 
                                                                variant="ghost" 
                                                                size="icon" 
                                                                onClick={() => { if(confirm('Delete lesson?')) router.delete(route('admin.lessons.destroy', lesson.id)) }}
                                                                className="h-8 w-8 rounded-lg text-[#8C92AC] hover:text-red-500"
                                                            >
                                                                <Trash2 className="h-3.5 w-3.5" />
                                                            </Button>
                                                        </div>
                                                    </div>
                                                )}
                                            </div>
                                        ))}
                                        
                                        {addingLessonToModule === module.id ? (
                                            <div className="p-6 border-2 border-primary/20 rounded-[2rem] bg-primary/5 space-y-6 animate-in fade-in slide-in-from-top-4">
                                                <div className="grid gap-6">
                                                    <Input 
                                                        value={lessonData.title}
                                                        onChange={e => setLessonData(prev => ({...prev, title: e.target.value}))}
                                                        placeholder="Lesson Title"
                                                        className="h-12 rounded-xl border-[#E8E6DF] bg-white px-5 font-bold"
                                                    />
                                                    <div className="grid grid-cols-2 gap-4">
                                                        <Input 
                                                            value={lessonData.video_url}
                                                            onChange={e => setLessonData(prev => ({...prev, video_url: e.target.value}))}
                                                            placeholder="Video URL (YouTube/Vimeo)"
                                                            className="h-11 rounded-xl border-[#E8E6DF]"
                                                        />
                                                        <Input 
                                                            type="number"
                                                            value={lessonData.duration}
                                                            onChange={e => setLessonData(prev => ({...prev, duration: parseInt(e.target.value)}))}
                                                            placeholder="Duration (Min)"
                                                            className="h-11 rounded-xl border-[#E8E6DF]"
                                                        />
                                                    </div>
                                                    <Textarea 
                                                        value={lessonData.content}
                                                        onChange={e => setLessonData(prev => ({...prev, content: e.target.value}))}
                                                        placeholder="Add detailed text content for this lesson..."
                                                        className="rounded-xl border-[#E8E6DF] min-h-[100px]"
                                                    />
                                                    <div className="flex items-center justify-between p-4 bg-white rounded-xl border border-[#E8E6DF]">
                                                        <Label className="text-[13px] font-bold">Free Preview</Label>
                                                        <Switch checked={lessonData.is_preview} onCheckedChange={c => setLessonData(prev => ({...prev, is_preview: c}))} />
                                                    </div>
                                                </div>
                                                <div className="flex justify-end gap-2">
                                                    <Button variant="ghost" onClick={resetLessonForm} className="rounded-lg text-[11px] font-bold">Cancel</Button>
                                                    <Button onClick={() => handleSaveLesson(module.id)} className="rounded-lg bg-ink text-white px-6 h-9 text-[11px] font-bold">Create Lesson</Button>
                                                </div>
                                            </div>
                                        ) : (
                                            <button 
                                                onClick={() => { resetLessonForm(); setAddingLessonToModule(module.id); }}
                                                className="w-full py-4 flex items-center justify-center gap-2 border-2 border-dashed border-[#F0EDE8] rounded-2xl text-[12px] font-bold text-[#8C92AC] hover:border-primary/30 hover:text-primary hover:bg-primary/5 transition-all"
                                            >
                                                <Plus className="h-4 w-4" /> Add Lesson
                                            </button>
                                        )}
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                ))}

                {isAddingModule && (
                    <div className="bg-white border-2 border-primary/20 rounded-[2rem] p-10 shadow-xl shadow-primary/5 animate-in fade-in slide-in-from-top-4">
                        <div className="space-y-8">
                            <div className="flex items-center justify-between">
                                <h3 className="text-[24px] font-display text-ink">New Module</h3>
                                <button onClick={resetModuleForm} className="p-2 text-[#8C92AC] hover:text-ink"><X className="h-6 w-6" /></button>
                            </div>
                            <div className="grid gap-8">
                                <div className="space-y-3">
                                    <Label className="text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] ml-1">Module Title</Label>
                                    <Input 
                                        value={moduleData.title}
                                        onChange={e => setModuleData(prev => ({...prev, title: e.target.value}))}
                                        placeholder="e.g. Phase 1: Getting Started"
                                        className="h-14 rounded-2xl border-[#E8E6DF] bg-[#FAFAF8] focus:bg-white focus:border-primary focus:ring-0 text-[16px] font-bold px-6"
                                    />
                                </div>
                                <div className="space-y-3">
                                    <Label className="text-[11px] font-bold uppercase tracking-widest text-[#8C92AC] ml-1">Description (Optional)</Label>
                                    <Textarea 
                                        value={moduleData.description}
                                        onChange={e => setModuleData(prev => ({...prev, description: e.target.value}))}
                                        placeholder="Briefly describe what students will learn..."
                                        className="rounded-2xl border-[#E8E6DF] bg-[#FAFAF8] focus:bg-white focus:border-primary focus:ring-0 min-h-[120px] text-[14px] p-6 leading-relaxed"
                                    />
                                </div>
                            </div>
                            <div className="flex justify-end gap-4 pt-4">
                                <Button variant="ghost" onClick={resetModuleForm} className="rounded-xl font-bold h-12 px-6">Cancel</Button>
                                <Button onClick={handleSaveModule} className="rounded-xl font-bold bg-ink text-white px-10 h-12 shadow-lg shadow-ink/10 active:scale-95 transition-all">Create Module</Button>
                            </div>
                        </div>
                    </div>
                )}

                {modules.length === 0 && !isAddingModule && (
                    <div className="py-24 text-center bg-white border-2 border-dashed border-[#F0EDE8] rounded-[3rem]">
                        <div className="h-20 w-20 bg-[#F5F3EF] rounded-[2.5rem] flex items-center justify-center mx-auto mb-6">
                            <Plus className="h-10 w-10 text-[#C0BDBA]" />
                        </div>
                        <h3 className="text-[18px] font-display text-ink mb-2">Build your curriculum</h3>
                        <p className="text-[13px] text-[#8C92AC] mb-10 max-w-sm mx-auto">Start by adding your first module to organize your lessons and content.</p>
                        <Button 
                            onClick={() => setIsAddingModule(true)} 
                            className="rounded-2xl h-12 px-10 font-bold text-[13px] bg-ink text-white hover:bg-primary shadow-xl shadow-ink/10 active:scale-95 transition-all"
                        >
                            Create First Module
                        </Button>
                    </div>
                )}
            </div>
        </div>
    );
}
