const { useState, useEffect } = React;

const RollNumberGenerator = ({ currentUser }) => {
  const [departments, setDepartments] = useState([]);
  const [deptCode, setDeptCode] = useState('CO');
  const [semester, setSemester] = useState(1);
  const [batchFilter, setBatchFilter] = useState('ALL');
  const [batches, setBatches] = useState([]);
  const [selectedStatuses, setSelectedStatuses] = useState(['Active']);
  const [selectedExamStatuses, setSelectedExamStatuses] = useState([]);
  
  const [students, setStudents] = useState([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  
  // Sequence Generator Controls
  const [startNum, setStartNum] = useState(1);
  const [sortBy, setSortBy] = useState('enrollment_asc'); // enrollment_asc, name_asc, current_roll

  // 1. Fetch departments and batches on mount
  useEffect(() => {
    fetch('/api/departments')
      .then(res => res.json())
      .then(data => {
        if (Array.isArray(data) && data.length > 0) {
          setDepartments(data);
          setDeptCode(data[0].dept_code);
        }
      })
      .catch(console.error);

    fetch('/api/batches')
      .then(res => res.json())
      .then(data => {
        if (Array.isArray(data)) setBatches(data);
      })
      .catch(console.error);
  }, []);

  // 2. Fetch students based on strict filters
  const handleFetchStudents = () => {
    setLoading(true);
    const statusParam = selectedStatuses.length > 0 ? encodeURIComponent(selectedStatuses.join(',')) : 'ALL';
    const examParam = selectedExamStatuses.length > 0 ? encodeURIComponent(selectedExamStatuses.join(',')) : 'ALL';

    fetch(`/api/students/filter?dept_code=${deptCode}&semester=${semester}&status=${statusParam}&last_exam_status=${examParam}`)
      .then(res => res.json())
      .then(data => {
        let list = Array.isArray(data) ? data : [];
        if (batchFilter !== 'ALL') {
          list = list.filter(s => s.Batch?.batch_name === batchFilter || String(s.batch_id) === String(batchFilter));
        }

        // Apply chosen sort order
        applySort(list, sortBy);
        setStudents(list.map(s => ({ ...s, _newRoll: s.roll_no || '' })));
        setLoading(false);
      })
      .catch(err => {
        console.error(err);
        setLoading(false);
        alert('Failed to load students.');
      });
  };

  const applySort = (list, sortMode) => {
    if (sortMode === 'enrollment_asc') {
      list.sort((a, b) => String(a.enrollment_no || '').localeCompare(String(b.enrollment_no || '')));
    } else if (sortMode === 'name_asc') {
      list.sort((a, b) => String(a.full_name || '').localeCompare(String(b.full_name || '')));
    } else if (sortMode === 'current_roll') {
      list.sort((a, b) => (Number(a.roll_no) || 999999) - (Number(b.roll_no) || 999999));
    }
  };

  const handleSortChange = (newSort) => {
    setSortBy(newSort);
    const list = [...students];
    applySort(list, newSort);
    setStudents(list);
  };

  // 3. Auto Generate Numbers 1..N
  const handleAutoSequence = () => {
    let current = parseInt(startNum) || 1;
    setStudents(prev => prev.map(s => ({ ...s, _newRoll: current++ })));
  };

  // 4. Save to Database
  const handleSave = () => {
    const assignments = students
      .filter(s => s._newRoll !== '' && String(s._newRoll) !== String(s.roll_no))
      .map(s => ({ student_id: s.id, roll_no: parseInt(s._newRoll) }));

    if (assignments.length === 0) {
      return alert('No roll number changes to save.');
    }

    setSaving(true);
    fetch('/api/students/bulk-assign-roll', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ assignments })
    })
      .then(res => res.json())
      .then(data => {
        setSaving(false);
        if (data.success) {
          alert(`Successfully assigned roll numbers to ${assignments.length} students!`);
          handleFetchStudents();
        } else {
          alert('Failed to save roll numbers');
        }
      })
      .catch(err => {
        setSaving(false);
        console.error(err);
        alert('Server error while saving roll numbers');
      });
  };

  // Move up/down manually in list
  const moveStudent = (index, direction) => {
    const newIdx = index + direction;
    if (newIdx < 0 || newIdx >= students.length) return;
    const newList = [...students];
    const temp = newList[index];
    newList[index] = newList[newIdx];
    newList[newIdx] = temp;
    setStudents(newList);
  };

  return (
    <div className="flex flex-col gap-6 animate-fade-in-up pb-12">
      {/* Header */}
      <div className="bg-gradient-to-r from-blue-700 to-indigo-800 p-6 rounded-3xl shadow-xl text-white flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <div className="flex items-center gap-3">
            <span className="text-3xl">🔢</span>
            <div>
              <h1 className="text-2xl font-black tracking-tight">Academic Roll Number Generator</h1>
              <p className="text-xs text-blue-200 mt-0.5">Filter by Department, Semester & Batch, order alphabetically or by enrollment, and generate sequential roll numbers.</p>
            </div>
          </div>
        </div>
        {students.length > 0 && (
          <button
            onClick={handleSave}
            disabled={saving}
            className="bg-emerald-500 hover:bg-emerald-600 text-white font-black px-6 py-3 rounded-2xl shadow-lg transition-all flex items-center gap-2 text-sm disabled:opacity-50 shrink-0"
          >
            <span>💾</span> {saving ? 'Saving...' : 'Save All Roll Numbers'}
          </button>
        )}
      </div>

      {/* Filter Matrix Card */}
      <div className="bg-white p-6 rounded-3xl shadow-sm border border-gray-200 flex flex-col gap-5">
        <h2 className="text-xs font-black text-gray-400 uppercase tracking-widest border-b border-gray-100 pb-2">Step 1: Select Target Class</h2>
        
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 items-end">
          <div>
            <label className="block text-[10px] font-bold text-gray-500 uppercase mb-1">Department</label>
            <select
              value={deptCode}
              onChange={e => setDeptCode(e.target.value)}
              className="w-full px-3 py-2 text-sm bg-gray-50 border border-gray-200 rounded-xl font-bold outline-none focus:border-blue-500"
            >
              {departments.map(d => (
                <option key={d.id} value={d.dept_code}>{d.dept_code} - {d.name}</option>
              ))}
              {departments.length === 0 && <option value="CO">CO - Computer Engineering</option>}
            </select>
          </div>

          <div>
            <label className="block text-[10px] font-bold text-gray-500 uppercase mb-1">Semester</label>
            <select
              value={semester}
              onChange={e => setSemester(parseInt(e.target.value))}
              className="w-full px-3 py-2 text-sm bg-gray-50 border border-gray-200 rounded-xl font-bold outline-none focus:border-blue-500"
            >
              {[1, 2, 3, 4, 5, 6].map(s => <option key={s} value={s}>Semester {s}</option>)}
            </select>
          </div>

          <div>
            <label className="block text-[10px] font-bold text-gray-500 uppercase mb-1">Practical Batch (Optional)</label>
            <select
              value={batchFilter}
              onChange={e => setBatchFilter(e.target.value)}
              className="w-full px-3 py-2 text-sm bg-gray-50 border border-gray-200 rounded-xl font-bold outline-none focus:border-blue-500"
            >
              <option value="ALL">All Batches (Whole Class)</option>
              {batches.map(b => (
                <option key={b.id} value={b.batch_name}>Batch {b.batch_name}</option>
              ))}
            </select>
          </div>

          <button
            onClick={handleFetchStudents}
            disabled={loading}
            className="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2.5 px-4 rounded-xl shadow-md transition disabled:opacity-50 text-sm flex items-center justify-center gap-2"
          >
            <span>🔍</span> {loading ? 'Fetching...' : 'Load Class Students'}
          </button>
        </div>

        {/* Filter Pills for Status & Exam Result */}
        <div className="pt-3 border-t border-gray-100">
          <label className="block text-[10px] font-bold text-gray-500 uppercase mb-2">Student Inclusion Filters:</label>
          {window.StudentStatusFilter && (
            <window.StudentStatusFilter
              selectedStatuses={selectedStatuses}
              selectedExamStatuses={selectedExamStatuses}
              onStatusChange={setSelectedStatuses}
              onExamStatusChange={setSelectedExamStatuses}
              showExamStatus={true}
            />
          )}
        </div>
      </div>

      {/* Generator & Sequence Control Card */}
      {students.length > 0 && (
        <div className="bg-white p-6 rounded-3xl shadow-sm border border-gray-200 flex flex-wrap justify-between items-center gap-4 animate-fade-in-up">
          <div className="flex flex-wrap items-center gap-4">
            <div>
              <label className="block text-[10px] font-bold text-gray-500 uppercase mb-1">Order Before Numbering</label>
              <select
                value={sortBy}
                onChange={e => handleSortChange(e.target.value)}
                className="px-3 py-2 bg-gray-50 border border-gray-200 rounded-xl text-xs font-bold outline-none"
              >
                <option value="enrollment_asc">Sort by Enrollment Number (Ascending)</option>
                <option value="name_asc">Sort by Student Name (A to Z)</option>
                <option value="current_roll">Sort by Existing Roll Number</option>
              </select>
            </div>

            <div>
              <label className="block text-[10px] font-bold text-gray-500 uppercase mb-1">Start Number</label>
              <input
                type="number"
                min="1"
                value={startNum}
                onChange={e => setStartNum(e.target.value)}
                className="w-24 px-3 py-2 text-center bg-gray-50 border border-gray-200 rounded-xl text-xs font-black outline-none"
              />
            </div>

            <button
              onClick={handleAutoSequence}
              className="mt-4 px-5 py-2 bg-blue-600 hover:bg-blue-700 text-white text-xs font-black rounded-xl shadow transition"
            >
              ⚡ Auto-Generate 1..{students.length}
            </button>
          </div>

          <div className="text-right">
            <span className="text-xs bg-indigo-50 text-indigo-700 font-bold px-3 py-1.5 rounded-full border border-indigo-100">
              {students.length} Students in Queue
            </span>
          </div>
        </div>
      )}

      {/* Student Sequence Table */}
      {loading ? (
        <div className="bg-white p-12 rounded-3xl shadow-sm border border-gray-200 text-center">
          <div className="w-10 h-10 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mx-auto mb-3"></div>
          <p className="text-xs font-bold text-gray-400 uppercase tracking-widest">Loading students...</p>
        </div>
      ) : students.length > 0 ? (
        <div className="bg-white rounded-3xl shadow-sm border border-gray-200 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs whitespace-nowrap">
              <thead className="bg-gray-50 border-b border-gray-200 text-[10px] font-black uppercase text-gray-500 tracking-wider">
                <tr>
                  <th className="px-4 py-3.5 text-center w-14">#</th>
                  <th className="px-4 py-3.5 text-center w-20">Reorder</th>
                  <th className="px-4 py-3.5 text-center bg-indigo-50 text-indigo-700 font-black w-32">New Roll No</th>
                  <th className="px-4 py-3.5 text-center w-24">Current Roll</th>
                  <th className="px-4 py-3.5">Enrollment No</th>
                  <th className="px-4 py-3.5">Student Full Name</th>
                  <th className="px-4 py-3.5 text-center">Batch</th>
                  <th className="px-4 py-3.5 text-center">Status</th>
                  <th className="px-4 py-3.5 text-center">Result</th>
                  <th className="px-4 py-3.5 text-center w-16">Remove</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                {students.map((s, idx) => (
                  <tr key={s.id} className="hover:bg-blue-50/20 transition">
                    <td className="px-4 py-2.5 text-center font-mono text-gray-400 font-bold">{idx + 1}</td>
                    
                    {/* Manual reorder buttons */}
                    <td className="px-2 py-2.5 text-center space-x-1">
                      <button
                        onClick={() => moveStudent(idx, -1)}
                        disabled={idx === 0}
                        title="Move Up"
                        className="px-1.5 py-0.5 bg-gray-100 hover:bg-gray-200 rounded text-gray-600 disabled:opacity-30 font-bold"
                      >
                        ▲
                      </button>
                      <button
                        onClick={() => moveStudent(idx, 1)}
                        disabled={idx === students.length - 1}
                        title="Move Down"
                        className="px-1.5 py-0.5 bg-gray-100 hover:bg-gray-200 rounded text-gray-600 disabled:opacity-30 font-bold"
                      >
                        ▼
                      </button>
                    </td>

                    {/* New Roll Number Input */}
                    <td className="px-4 py-2 text-center bg-indigo-50/40">
                      <input
                        type="number"
                        value={s._newRoll}
                        onChange={e => {
                          const val = e.target.value;
                          setStudents(prev => prev.map(item => item.id === s.id ? { ...item, _newRoll: val } : item));
                        }}
                        className="w-20 px-2 py-1 text-center font-black text-sm text-indigo-700 bg-white border border-indigo-300 rounded-lg outline-none focus:ring-2 focus:ring-indigo-400"
                        placeholder="Roll"
                      />
                    </td>

                    <td className="px-4 py-2.5 text-center text-gray-500 font-bold">{s.roll_no || '-'}</td>
                    <td className="px-4 py-2.5 font-mono font-bold text-gray-800">{s.enrollment_no}</td>
                    <td className="px-4 py-2.5 font-medium text-gray-900">{s.full_name}</td>
                    <td className="px-4 py-2.5 text-center">
                      <span className="bg-blue-50 text-blue-600 font-bold px-2 py-0.5 rounded">{s.Batch?.batch_name || '-'}</span>
                    </td>
                    <td className="px-4 py-2.5 text-center">
                      <span className={`px-2 py-0.5 rounded font-bold text-[10px] ${s.status === 'Active' ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'}`}>
                        {s.status || 'Active'}
                      </span>
                    </td>
                    <td className="px-4 py-2.5 text-center">
                      <span className={`px-2 py-0.5 rounded font-bold text-[10px] ${s.last_exam_status === 'Pass' ? 'bg-green-100 text-green-700' : s.last_exam_status === 'ATKT' ? 'bg-amber-100 text-amber-700' : 'bg-red-100 text-red-700'}`}>
                        {s.last_exam_status || 'Pass'}
                      </span>
                    </td>
                    <td className="px-4 py-2.5 text-center">
                      <button
                        onClick={() => {
                          if (confirm(`Exclude ${s.full_name} from roll number assignment?`)) {
                            setStudents(prev => prev.filter(item => item.id !== s.id));
                          }
                        }}
                        title="Remove student from list"
                        className="text-gray-300 hover:text-red-500 font-bold p-1 text-sm transition"
                      >
                        ✕
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : (
        <div className="bg-white p-12 rounded-3xl shadow-sm border border-gray-200 text-center">
          <div className="text-5xl mb-3 grayscale opacity-30">🔢</div>
          <h3 className="text-base font-bold text-gray-700">No Students Selected</h3>
          <p className="text-xs text-gray-400 mt-1">Select your Department and Semester in Step 1, then click "Load Class Students".</p>
        </div>
      )}
    </div>
  );
};

window.RollNumberGenerator = RollNumberGenerator;
