"use client";

import { useState, useEffect } from "react";
import { 
  BookOpen, 
  ChevronDown, 
  ChevronRight, 
  Plus, 
  Edit2, 
  Trash2, 
  Copy, 
  Target, 
  FileText, 
  Save, 
  X,
  AlertCircle,
  GripVertical,
  MoreVertical
} from "lucide-react";

export default function CurriculumAdminPage() {
  const [chapters, setChapters] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedChapters, setExpandedChapters] = useState<Record<string, boolean>>({});

  // Editing State
  const [editingChapter, setEditingChapter] = useState<any | null>(null);
  const [editingElement, setEditingElement] = useState<any | null>(null);
  const [isSaving, setIsSaving] = useState(false);

  useEffect(() => {
    fetchCurriculum();
  }, []);

  const fetchCurriculum = async () => {
    setLoading(true);
    const res = await fetch("/api/curriculum/chapters");
    const json = await res.json();
    if (json.success) setChapters(json.data);
    setLoading(false);
  };

  const toggleChapter = (id: string) => {
    setExpandedChapters(prev => ({ ...prev, [id]: !prev[id] }));
  };

  // Chapter Handlers
  const handleAddChapter = () => {
    setEditingChapter({ id: "", title: "", description: "", sortOrder: chapters.length + 1 });
  };

  const handleDuplicateChapter = async (id: string) => {
    const res = await fetch(`/api/curriculum/chapters/${id}`, { method: "POST" });
    if ((await res.json()).success) fetchCurriculum();
  };

  const handleDeleteChapter = async (id: string) => {
    if (!confirm("Are you sure? This will delete all assets in this chapter.")) return;
    const res = await fetch(`/api/curriculum/chapters/${id}`, { method: "DELETE" });
    if ((await res.json()).success) fetchCurriculum();
  };

  const saveChapter = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    const isNew = !chapters.find(c => c.id === editingChapter.id && editingChapter.id !== "");
    const url = isNew ? "/api/curriculum/chapters" : `/api/curriculum/chapters/${editingChapter.id}`;
    const method = isNew ? "POST" : "PATCH";

    const res = await fetch(url, {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(editingChapter)
    });

    if ((await res.json()).success) {
      setEditingChapter(null);
      fetchCurriculum();
    }
    setIsSaving(false);
  };

  // Element Handlers
  const handleAddElement = (chapterId: string) => {
    setEditingElement({ 
      id: "", 
      chapterId, 
      title: "", 
      description: "", 
      drillPrompt: "", 
      hasDrill: false, 
      masteryThreshold: 75,
      sortOrder: 0 
    });
  };

  const handleDuplicateElement = async (id: string) => {
    const res = await fetch(`/api/curriculum/elements/${id}`, { method: "POST" });
    if ((await res.json()).success) fetchCurriculum();
  };

  const handleDeleteElement = async (id: string) => {
    if (!confirm("Delete this mission asset?")) return;
    const res = await fetch(`/api/curriculum/elements/${id}`, { method: "DELETE" });
    if ((await res.json()).success) fetchCurriculum();
  };

  const saveElement = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    const isNew = editingElement.id === "";
    const url = isNew ? "/api/curriculum/elements" : `/api/curriculum/elements/${editingElement.id}`;
    const method = isNew ? "POST" : "PATCH";

    const res = await fetch(url, {
      method,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(editingElement)
    });

    if ((await res.json()).success) {
      setEditingElement(null);
      fetchCurriculum();
    }
    setIsSaving(false);
  };

  if (loading && chapters.length === 0) return (
    <div className="h-full flex items-center justify-center font-mono text-[#044f54] uppercase tracking-widest text-xs">
      Retrieving Curriculum Intel...
    </div>
  );

  return (
    <div className="space-y-8 max-w-5xl mx-auto pb-20 text-[#044f54]">
      <div className="flex justify-between items-end border-b border-[#044f54]/20 pb-6">
        <div>
          <h2 className="text-2xl font-serif italic">Curriculum & Mission Assets</h2>
          <p className="text-[#044f54]/40 text-[10px] font-mono uppercase tracking-[0.2em] mt-1">Authorized mastery pedagogy management</p>
        </div>
        <button 
          onClick={handleAddChapter}
          className="flex items-center gap-2 px-4 py-2 bg-[#044f54] text-white rounded border border-[#044f54] text-[10px] font-bold uppercase tracking-widest hover:bg-[#044f54]/90 transition-all shadow-lg shadow-[#044f54]/20"
        >
          <Plus size={14} /> Add Chapter
        </button>
      </div>

      <div className="space-y-4">
        {chapters.map((chapter) => {
          const isExpanded = expandedChapters[chapter.id];
          return (
            <div key={chapter.id} className="border border-[#044f54]/10 rounded overflow-hidden bg-white shadow-sm transition-all hover:shadow-md">
              <div 
                className={`p-4 flex items-center justify-between cursor-pointer group ${isExpanded ? 'bg-[#044f54]/5' : ''}`}
                onClick={() => toggleChapter(chapter.id)}
              >
                <div className="flex items-center gap-4 flex-1">
                  {isExpanded ? <ChevronDown size={18} className="text-[#044f54]/40" /> : <ChevronRight size={18} className="text-[#044f54]/40" />}
                  <div className="w-8 h-8 rounded bg-[#044f54] text-white flex items-center justify-center font-mono text-[10px] font-bold">
                    {chapter.id.replace('CH', '')}
                  </div>
                  <div>
                    <h3 className="font-bold text-sm uppercase tracking-wider">{chapter.title}</h3>
                    <p className="text-[10px] text-[#044f54]/40 font-mono uppercase truncate max-w-md">{chapter.description || 'No description provided'}</p>
                  </div>
                </div>
                
                <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button onClick={(e) => { e.stopPropagation(); handleDuplicateChapter(chapter.id); }} title="Duplicate Chapter" className="p-2 hover:bg-[#044f54]/10 rounded text-[#044f54]/60"><Copy size={14}/></button>
                  <button onClick={(e) => { e.stopPropagation(); setEditingChapter(chapter); }} title="Edit Chapter" className="p-2 hover:bg-[#044f54]/10 rounded text-[#044f54]/60"><Edit2 size={14}/></button>
                  <button onClick={(e) => { e.stopPropagation(); handleDeleteChapter(chapter.id); }} title="Delete Chapter" className="p-2 hover:bg-red-50 rounded text-red-400 hover:text-red-600"><Trash2 size={14}/></button>
                </div>
              </div>

              {isExpanded && (
                <div className="border-t border-[#044f54]/5 bg-slate-50/50 p-4 space-y-3">
                  <div className="flex justify-between items-center px-4 mb-2">
                    <span className="text-[9px] font-mono text-[#044f54]/40 uppercase tracking-widest">Chapter Assets ({chapter.elements.length})</span>
                    <button 
                      onClick={() => handleAddElement(chapter.id)}
                      className="text-[9px] font-bold text-[#044f54] uppercase tracking-widest flex items-center gap-1 hover:underline"
                    >
                      <Plus size={12} /> Add Mission Asset
                    </button>
                  </div>
                  
                  {chapter.elements.length === 0 ? (
                    <p className="text-center py-8 text-[10px] font-mono text-[#044f54]/30 uppercase italic">No assets recovered for this chapter</p>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3 px-2">
                      {chapter.elements.map((el: any) => (
                        <div key={el.id} className="bg-white p-4 rounded border border-[#044f54]/10 shadow-sm flex items-start justify-between group/el">
                          <div className="flex gap-3">
                             <div className="mt-1">{el.hasDrill ? <Target size={14} className="text-[#044f54]/40"/> : <FileText size={14} className="text-[#044f54]/40"/>}</div>
                             <div>
                                <h4 className="text-xs font-bold uppercase tracking-wider">{el.title}</h4>
                                <p className="text-[9px] text-[#044f54]/60 mt-1 line-clamp-1">{el.description}</p>
                             </div>
                          </div>
                          <div className="flex gap-1 opacity-0 group-hover/el:opacity-100 transition-opacity">
                            <button onClick={() => handleDuplicateElement(el.id)} className="p-1.5 hover:bg-[#044f54]/5 rounded text-[#044f54]/40"><Copy size={12}/></button>
                            <button onClick={() => setEditingElement(el)} className="p-1.5 hover:bg-[#044f54]/5 rounded text-[#044f54]/40"><Edit2 size={12}/></button>
                            <button onClick={() => handleDeleteElement(el.id)} className="p-1.5 hover:bg-red-50 rounded text-red-300 hover:text-red-500"><Trash2 size={12}/></button>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Chapter Edit Modal */}
      {editingChapter && (
        <div className="fixed inset-0 bg-[#044f54]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
          <div className="bg-slate-50 border border-[#044f54] shadow-[0_0_50px_rgba(4,79,84,0.2)] w-full max-w-md rounded overflow-hidden animate-in zoom-in-95 duration-200">
             <div className="border-b border-[#044f54]/30 bg-[#044f54]/10 p-4 flex justify-between items-center">
                <span className="text-[#044f54] font-bold text-xs tracking-widest uppercase">Chapter Profile Editor</span>
                <button onClick={() => setEditingChapter(null)} className="text-[#044f54]/60 hover:text-[#044f54]"><X size={18}/></button>
             </div>
             <form onSubmit={saveChapter} className="p-6 space-y-4">
                <div className="grid grid-cols-4 gap-4">
                  <div className="col-span-1 flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                    <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">ID</label>
                    <input required value={editingChapter.id} onChange={e => setEditingChapter({...editingChapter, id: e.target.value})} className="bg-transparent outline-none text-xs font-bold uppercase" placeholder="CH-00"/>
                  </div>
                  <div className="col-span-3 flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                    <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">Chapter Title</label>
                    <input required value={editingChapter.title} onChange={e => setEditingChapter({...editingChapter, title: e.target.value})} className="bg-transparent outline-none text-xs font-bold uppercase" placeholder="ENTER TITLE..."/>
                  </div>
                </div>
                <div className="flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                    <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">Pedagogy Description</label>
                    <textarea value={editingChapter.description || ''} onChange={e => setEditingChapter({...editingChapter, description: e.target.value})} className="bg-transparent outline-none text-xs font-medium h-24 resize-none" placeholder="ENTER MISSION DETAILS..."/>
                </div>
                <div className="flex justify-end gap-3 pt-4">
                   <button type="button" onClick={() => setEditingChapter(null)} className="px-4 py-2 text-[10px] font-bold uppercase tracking-widest">Cancel</button>
                   <button disabled={isSaving} className="bg-[#044f54] text-white px-8 py-2 rounded font-bold uppercase tracking-widest text-[10px] shadow-lg shadow-[#044f54]/20">
                     {isSaving ? "SAVING..." : "COMMIT CHANGES"}
                   </button>
                </div>
             </form>
          </div>
        </div>
      )}

      {/* Element Edit Modal */}
      {editingElement && (
        <div className="fixed inset-0 bg-[#044f54]/20 backdrop-blur-sm z-[100] flex items-center justify-center p-4">
          <div className="bg-slate-50 border border-[#044f54] shadow-[0_0_50px_rgba(4,79,84,0.2)] w-full max-w-2xl rounded overflow-hidden animate-in zoom-in-95 duration-200">
             <div className="border-b border-[#044f54]/30 bg-[#044f54]/10 p-4 flex justify-between items-center">
                <span className="text-[#044f54] font-bold text-xs tracking-widest uppercase">Mission Asset Editor</span>
                <button onClick={() => setEditingElement(null)} className="text-[#044f54]/60 hover:text-[#044f54]"><X size={18}/></button>
             </div>
             <form onSubmit={saveElement} className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
                <div className="grid grid-cols-2 gap-4">
                  <div className="flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                    <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">Asset ID</label>
                    <input required value={editingElement.id} onChange={e => setEditingElement({...editingElement, id: e.target.value})} className="bg-transparent outline-none text-xs font-bold uppercase" placeholder="EL-00"/>
                  </div>
                  <div className="flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                    <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">Asset Title</label>
                    <input required value={editingElement.title} onChange={e => setEditingElement({...editingElement, title: e.target.value})} className="bg-transparent outline-none text-xs font-bold uppercase" placeholder="ENTER ASSET NAME..."/>
                  </div>
                </div>
                
                <div className="flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-white">
                    <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">Intelligence Brief (Description)</label>
                    <textarea value={editingElement.description || ''} onChange={e => setEditingElement({...editingElement, description: e.target.value})} className="bg-transparent outline-none text-xs font-medium h-20 resize-none" placeholder="WHAT SHOULD THE OPERATIVE LEARN?"/>
                </div>

                <div className="flex items-center gap-6 p-4 border border-[#044f54]/10 rounded bg-[#044f54]/5">
                   <div className="flex items-center gap-2">
                     <input type="checkbox" checked={editingElement.hasDrill} onChange={e => setEditingElement({...editingElement, hasDrill: e.target.checked})} className="w-4 h-4 accent-[#044f54]"/>
                     <label className="text-[10px] font-bold uppercase tracking-widest">Enable Real-time Voice Drill</label>
                   </div>
                   {editingElement.hasDrill && (
                     <div className="flex items-center gap-3 ml-auto">
                        <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">Mastery Threshold</label>
                        <input type="number" value={editingElement.masteryThreshold} onChange={e => setEditingElement({...editingElement, masteryThreshold: parseInt(e.target.value)})} className="w-16 p-1 border border-[#044f54]/20 rounded text-xs font-bold text-center"/>
                        <span className="text-xs font-bold">%</span>
                     </div>
                   )}
                </div>

                {editingElement.hasDrill && (
                  <div className="flex flex-col gap-1 p-3 border border-[#044f54]/20 rounded bg-[#044f54]/5">
                    <div className="flex items-center justify-between mb-1">
                      <label className="text-[9px] font-mono text-[#044f54]/50 uppercase">AI Operative Prompt (Tactical Drill Logic)</label>
                      <AlertCircle size={12} className="text-[#044f54]/30" />
                    </div>
                    <textarea 
                      required={editingElement.hasDrill}
                      value={editingElement.drillPrompt || ''} 
                      onChange={e => setEditingElement({...editingElement, drillPrompt: e.target.value})} 
                      className="bg-white border border-[#044f54]/10 rounded p-3 outline-none text-[11px] font-mono leading-relaxed h-48 resize-none shadow-inner" 
                      placeholder="ENTER THE AI SYSTEM INSTRUCTIONS FOR THIS DRILL..."
                    />
                  </div>
                )}

                <div className="flex justify-end gap-3 pt-4">
                   <button type="button" onClick={() => setEditingElement(null)} className="px-4 py-2 text-[10px] font-bold uppercase tracking-widest">Cancel</button>
                   <button disabled={isSaving} className="bg-[#044f54] text-white px-12 py-3 rounded font-bold uppercase tracking-widest text-[10px] shadow-lg shadow-[#044f54]/20">
                     {isSaving ? "UPDATE ASSET" : "DEPLOY CHANGES"}
                   </button>
                </div>
             </form>
          </div>
        </div>
      )}
    </div>
  );
}
