const { useState, useEffect } = React;

window.CurriculumIngestion = function CurriculumIngestion({ currentUser }) {
  const [file, setFile] = useState(null);
  const [isParsing, setIsParsing] = useState(false);
  const [parsedData, setParsedData] = useState(null);
  const [scheme, setScheme] = useState('K Scheme');
  const [isSaving, setIsSaving] = useState(false);
  const [successMsg, setSuccessMsg] = useState('');
  const [apiKey, setApiKey] = useState('');
  const [showApiKeyInput, setShowApiKeyInput] = useState(false);
  
  // Dynamic course list from institute
  const [courses, setCourses] = useState([]);
  const [selectedCourseId, setSelectedCourseId] = useState('');

  const instituteId = currentUser?.institute_id || window.currentInstituteId || 1;

  useEffect(() => {
    fetchCourses();
  }, [instituteId]);

  const fetchCourses = async () => {
    try {
      const res = await fetch(`/api/courses?institute_id=${instituteId}`);
      if (res.ok) {
        const data = await res.json();
        // Unique courses by code and name
        const unique = [];
        const seen = new Set();
        (data || []).forEach(c => {
          const key = `${c.code}_${c.name}`;
          if (!seen.has(key)) {
            seen.add(key);
            unique.push(c);
          }
        });
        unique.sort((a, b) => (a.semester - b.semester) || (a.code || '').localeCompare(b.code || ''));
        setCourses(unique);
      }
    } catch (err) {
      console.warn('Failed to fetch courses:', err);
    }
  };

  const handleFileChange = (e) => {
    setFile(e.target.files[0]);
    setParsedData(null);
    setSuccessMsg('');
  };

  const handleParse = async () => {
    if (!file) return alert('Please select a PDF file first.');
    setIsParsing(true);
    setSuccessMsg('');
    
    const formData = new FormData();
    formData.append('syllabus', file);
    if (selectedCourseId) {
      formData.append('target_course_id', selectedCourseId);
    }

    try {
      const url = `/api/curriculum/parse-pdf?institute_id=${instituteId}${selectedCourseId ? `&target_course_id=${selectedCourseId}` : ''}`;
      const res = await fetch(url, {
        method: 'POST',
        body: formData
      });
      const data = await res.json();
      if (res.ok) {
        setParsedData(data);
        // If course was auto-detected or matched, reflect it in selectedCourseId
        if (data?.courseMeta?.course_id) {
          setSelectedCourseId(String(data.courseMeta.course_id));
        }
      } else {
        if (data.error === 'GEMINI_API_KEY_MISSING') {
          setShowApiKeyInput(true);
        } else {
          alert((data.details ? `${data.error}: ${data.details}` : data.error) || 'Parsing failed');
        }
      }
    } catch (err) {
      alert('Error connecting to server.');
    } finally {
      setIsParsing(false);
    }
  };

  const handleSave = async () => {
    if (!scheme) return alert('Please select a scheme.');
    if (!parsedData || !parsedData.courseMeta) return alert('No parsed curriculum data to save.');
    
    setIsSaving(true);
    try {
      const dataToSave = { 
        ...parsedData, 
        courseMeta: { ...(parsedData?.courseMeta || {}), scheme },
        institute_id: instituteId,
        course_id: selectedCourseId || parsedData?.courseMeta?.course_id || null
      };
      
      const res = await fetch(`/api/curriculum/save?institute_id=${instituteId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(dataToSave)
      });
      const data = await res.json();
      if (res.ok) {
        const branchMsg = data.updatedBranchesCount > 1 ? ` across ${data.updatedBranchesCount} branches` : '';
        const courseName = data.course_name ? ` "${data.course_name}"` : '';
        setSuccessMsg(`Subject${courseName} Successfully ${data.isNew ? 'Added (New)' : 'Updated'}${branchMsg}!`);
        setParsedData(null);
        setFile(null);
        setSelectedCourseId('');
        const fileInput = document.getElementById('syllabusUpload');
        if (fileInput) fileInput.value = '';
      } else {
        alert(data.error || 'Saving failed');
      }
    } catch (err) {
      alert('Error saving data.');
    } finally {
      setIsSaving(false);
    }
  };

  const handleSaveApiKey = async () => {
    if(!apiKey.trim()) return alert("Please enter a valid key");
    try {
       const res = await fetch(`/api/curriculum/config?institute_id=${instituteId}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ gemini_api_key: apiKey.trim() })
       });
       if(res.ok) {
          setShowApiKeyInput(false);
          alert('API Key saved successfully! You can now parse the PDF.');
       } else {
          alert('Failed to save API key');
       }
    } catch(err) {
        alert('Error saving API key');
    }
  };

  const safeStr = (val) => {
    if (val === null || val === undefined) return '';
    if (typeof val === 'object') return JSON.stringify(val);
    return String(val);
  };

  return (
    <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-100 max-w-5xl mx-auto animate-fade-in-up">
      <h2 className="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
        <svg className="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
        AI Curriculum Ingestion Engine
      </h2>

      {/* Success Popup / Banner */}
      {successMsg && (
        <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-green-100 text-green-600 rounded-full flex items-center justify-center shrink-0">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path></svg>
            </div>
            <div>
              <h4 className="font-bold text-green-800">Success</h4>
              <p className="text-sm text-green-700">{successMsg}</p>
            </div>
          </div>
          <button onClick={() => setSuccessMsg('')} className="text-green-500 hover:text-green-700">
             <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12"></path></svg>
          </button>
        </div>
      )}

      {showApiKeyInput && (
        <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
          <h4 className="font-bold text-yellow-800 mb-2">Gemini API Key Required</h4>
          <p className="text-sm text-yellow-700 mb-4">
            The AI Curriculum Extractor requires a Google Gemini API Key. You can generate a free key at <a href="https://aistudio.google.com/app/apikey" target="_blank" rel="noopener noreferrer" className="text-blue-600 underline hover:text-blue-800">Google AI Studio</a>.
          </p>
          <div className="flex gap-2 max-w-lg">
            <input 
              type="password" 
              placeholder="Enter GEMINI_API_KEY" 
              className="flex-1 px-3 py-2 border rounded-md focus:ring-yellow-500 focus:border-yellow-500"
              value={apiKey}
              onChange={e => setApiKey(e.target.value)}
            />
            <button 
              onClick={handleSaveApiKey}
              className="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded-md font-semibold"
            >
              Save Key
            </button>
            <button 
              onClick={() => setShowApiKeyInput(false)}
              className="bg-gray-200 hover:bg-gray-300 text-gray-800 px-4 py-2 rounded-md font-semibold"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      <div className="mb-8 grid grid-cols-1 md:grid-cols-3 gap-4 items-end bg-gray-50 p-4 rounded-lg border border-gray-200">
        <div>
           <label className="block text-sm font-semibold text-gray-700 mb-2">Target Subject (Optional)</label>
           <select 
             className="w-full px-3 py-2 border rounded-md focus:ring-blue-500 focus:border-blue-500 bg-white text-sm"
             value={selectedCourseId}
             onChange={e => {
               const val = e.target.value;
               setSelectedCourseId(val);
               if (val && parsedData) {
                 const c = courses.find(item => String(item.id) === String(val));
                 if (c) {
                   setParsedData({
                     ...parsedData,
                     courseMeta: {
                       ...parsedData.courseMeta,
                       name: c.name,
                       code: c.code,
                       semester: c.semester,
                       course_id: c.id
                     }
                   });
                 }
               }
             }}
           >
             <option value="">Auto-Detect from Syllabus PDF</option>
             {courses.map(c => (
               <option key={c.id} value={c.id}>
                 {c.code} - {c.name} (Sem {c.semester})
               </option>
             ))}
           </select>
        </div>
        <div>
           <label className="block text-sm font-semibold text-gray-700 mb-2">Target Scheme</label>
           <select 
             className="w-full px-3 py-2 border rounded-md focus:ring-blue-500 focus:border-blue-500 bg-white text-sm"
             value={scheme}
             onChange={e => setScheme(e.target.value)}
           >
             <option value="K Scheme">K Scheme</option>
             <option value="I Scheme">I Scheme</option>
             <option value="G Scheme">G Scheme</option>
             <option value="E Scheme">E Scheme</option>
           </select>
        </div>
        <div>
           <label className="block text-sm font-semibold text-gray-700 mb-2">Upload Syllabus PDF</label>
           <div className="flex gap-2">
             <input 
               type="file" 
               accept="application/pdf"
               id="syllabusUpload"
               onChange={handleFileChange}
               className="flex-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 border rounded-md bg-white cursor-pointer"
             />
             <button 
               onClick={handleParse}
               disabled={!file || isParsing}
               className="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-md font-semibold disabled:opacity-50 flex items-center gap-2 whitespace-nowrap shadow-sm"
             >
               {isParsing ? (
                 <>
                   <svg className="animate-spin h-4 w-4 text-white" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                   Extracting AI...
                 </>
               ) : 'Parse & Extract'}
             </button>
           </div>
        </div>
      </div>

      {parsedData && (
        <div className="space-y-6 animate-fade-in-up">
          <div className="flex justify-between items-center border-b pb-3">
             <div>
               <h3 className="text-xl font-bold text-gray-800">Extracted Curriculum Review</h3>
               <p className="text-xs text-gray-500 mt-0.5">Review and verify the subject details, units, and practicals before saving to Subject Master.</p>
             </div>
             <button 
               onClick={handleSave}
               disabled={isSaving}
               className="bg-green-600 hover:bg-green-700 text-white px-6 py-2.5 rounded-lg font-bold shadow-md disabled:opacity-50 flex items-center gap-2 transition"
             >
               <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path></svg>
               {isSaving ? 'Saving Master...' : 'Save to Subject Master'}
             </button>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Course Meta Info (Editable) */}
            <div className="bg-blue-50/50 border border-blue-200 rounded-lg p-4 shadow-sm">
              <h4 className="font-bold text-blue-800 mb-3 border-b border-blue-200 pb-1 flex justify-between items-center">
                <span>Course Details</span>
                <span className="text-xs font-normal text-blue-600">Editable fields</span>
              </h4>
              <div className="space-y-2.5 text-sm">
                <div>
                  <label className="text-xs text-gray-600 font-semibold block mb-0.5">Subject Name:</label>
                  <input 
                    type="text" 
                    className="w-full px-2.5 py-1.5 border border-gray-300 rounded text-sm font-semibold text-gray-900 bg-white focus:ring-1 focus:ring-blue-500" 
                    value={parsedData?.courseMeta?.name || ''} 
                    onChange={e => setParsedData({ ...parsedData, courseMeta: { ...parsedData.courseMeta, name: e.target.value } })}
                  />
                </div>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-xs text-gray-600 font-semibold block mb-0.5">Course Code:</label>
                    <input 
                      type="text" 
                      className="w-full px-2.5 py-1.5 border border-gray-300 rounded text-sm font-semibold text-gray-900 bg-white focus:ring-1 focus:ring-blue-500" 
                      value={parsedData?.courseMeta?.code || ''} 
                      onChange={e => setParsedData({ ...parsedData, courseMeta: { ...parsedData.courseMeta, code: e.target.value } })}
                    />
                  </div>
                  <div>
                    <label className="text-xs text-gray-600 font-semibold block mb-0.5">Semester:</label>
                    <input 
                      type="number" 
                      min="1" 
                      max="8" 
                      className="w-full px-2.5 py-1.5 border border-gray-300 rounded text-sm font-semibold text-gray-900 bg-white focus:ring-1 focus:ring-blue-500" 
                      value={parsedData?.courseMeta?.semester || 1} 
                      onChange={e => setParsedData({ ...parsedData, courseMeta: { ...parsedData.courseMeta, semester: parseInt(e.target.value) || 1 } })}
                    />
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-2 pt-1 border-t border-blue-100 text-xs">
                  <div>
                    <span className="text-gray-500">L-T-P: </span>
                    <span className="font-bold text-gray-800">{parsedData?.courseMeta?.cl ?? 0}-{parsedData?.courseMeta?.tl ?? 0}-{parsedData?.courseMeta?.ll ?? 0}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">Credits: </span>
                    <span className="font-bold text-gray-800">{parsedData?.courseMeta?.credits ?? 0}</span>
                  </div>
                  <div>
                    <span className="text-gray-500">Total Marks: </span>
                    <span className="font-bold text-gray-800">{parsedData?.courseMeta?.total_marks ?? 0}</span>
                  </div>
                </div>
              </div>
            </div>

            {/* Course Outcomes */}
            <div className="bg-emerald-50/50 border border-emerald-200 rounded-lg p-4 h-64 overflow-y-auto style-scrollbar shadow-sm">
              <h4 className="font-bold text-emerald-800 mb-3 border-b border-emerald-200 pb-1 flex justify-between items-center">
                <span>Course Outcomes (COs)</span>
                <span className="text-xs bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded-full font-semibold">
                  {parsedData.courseOutcomes?.length || 0} COs
                </span>
              </h4>
              <ul className="space-y-2 text-sm">
                {(parsedData.courseOutcomes || []).map((co, i) => (
                  <li key={i} className="flex gap-2">
                    <span className="font-bold text-emerald-700 min-w-10">{safeStr(co.co_number)}</span>
                    <span className="text-gray-700">{safeStr(co.description)}</span>
                  </li>
                ))}
              </ul>
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Lesson Plans (K1) */}
            <div className="bg-purple-50/50 border border-purple-200 rounded-lg p-4 max-h-80 overflow-y-auto style-scrollbar shadow-sm">
              <h4 className="font-bold text-purple-800 mb-3 border-b border-purple-200 pb-1 flex justify-between items-center">
                <span>Extracted Units / Lesson Plan</span>
                <span className="text-xs bg-purple-100 text-purple-800 px-2 py-0.5 rounded-full font-semibold">
                  {parsedData.lessonPlans?.length || 0} Units
                </span>
              </h4>
              <table className="w-full text-sm text-left">
                <thead className="bg-purple-100 text-purple-800 sticky top-0">
                  <tr>
                    <th className="p-2">Unit</th>
                    <th className="p-2">Topic</th>
                    <th className="p-2">Hrs</th>
                    <th className="p-2">CO</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-purple-100">
                  {(parsedData.lessonPlans || []).map((lp, i) => (
                    <tr key={i} className="hover:bg-purple-100/50">
                      <td className="p-2 font-medium">{safeStr(lp.unit_no)}</td>
                      <td className="p-2 truncate max-w-[150px]" title={safeStr(lp.topic_title)}>{safeStr(lp.topic_title)}</td>
                      <td className="p-2">{safeStr(lp.allocated_hrs)}</td>
                      <td className="p-2">{safeStr(lp.co_mapped)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Lab Plans (K2) */}
            <div className="bg-amber-50/50 border border-amber-200 rounded-lg p-4 max-h-80 overflow-y-auto style-scrollbar shadow-sm">
              <h4 className="font-bold text-amber-800 mb-3 border-b border-amber-200 pb-1 flex justify-between items-center">
                <span>Extracted Lab Plan (Practicals)</span>
                <span className="text-xs bg-amber-100 text-amber-800 px-2 py-0.5 rounded-full font-semibold">
                  {parsedData.labPlans?.length || 0} Practicals
                </span>
              </h4>
              <table className="w-full text-sm text-left">
                <thead className="bg-amber-100 text-amber-800 sticky top-0">
                  <tr>
                    <th className="p-2">Pr #</th>
                    <th className="p-2">Title</th>
                    <th className="p-2">Hrs</th>
                    <th className="p-2">CO</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-amber-100">
                  {(parsedData.labPlans || []).map((lp, i) => (
                    <tr key={i} className="hover:bg-amber-100/50">
                      <td className="p-2 font-medium">{safeStr(lp.practical_no)}</td>
                      <td className="p-2 truncate max-w-[150px]" title={safeStr(lp.title)}>{safeStr(lp.title)}</td>
                      <td className="p-2">{safeStr(lp.allocated_hrs)}</td>
                      <td className="p-2">{safeStr(lp.related_co || lp.co_mapped)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
