const { useState, useEffect } = React;

const LECTURE_TYPES = ['Theory', 'Practical', 'Tutorial'];

const TeacherDashboard = ({ faculty, onSessionCreated, onViewRegister, onLogout }) => {
  const [exams, setExams] = useState([]);
  const [allocations, setAllocations] = useState([]);
  const [recentSessions, setRecentSessions] = useState([]);
  const [loading, setLoading] = useState(true);

  // ── Shared selectors ────────────────────────────────────────────────────────
  const [selectedExamId, setSelectedExamId] = useState('');
  const [selectedAllocId, setSelectedAllocId] = useState('');
  const [lectureType, setLectureType] = useState('Theory');
  const [selectedBatchId, setSelectedBatchId] = useState('');
  const [date, setDate] = useState(new Date().toISOString().split('T')[0]);
  const [startTime, setStartTime] = useState(() => {
    const now = new Date();
    return `${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;
  });
  const [duration, setDuration] = useState(1);
  const [topic, setTopic] = useState('');
  const [creating, setCreating] = useState(false);
  const [createError, setCreateError] = useState('');

  // Derived: selected allocation object
  const selectedAlloc = allocations.find(a => String(a.id) === String(selectedAllocId));
  const selectedCourse = selectedAlloc?.Course;

  // Filter allocations by lecture type
  const filteredAllocs = allocations.filter(a => {
    const type = (a.allocation_type || 'Theory');
    return type === lectureType;
  });

  const fetchRecentSessions = async () => {
    try {
      const res = await fetch(`/api/attendance/recent-sessions/${faculty.id}`);
      if (res.ok) {
        const data = await res.json();
        setRecentSessions(data.sessions || []);
      }
    } catch (err) {
      console.error('Failed to load recent sessions', err);
    }
  };

  useEffect(() => {
    const init = async () => {
      setLoading(true);
      try {
        const examRes = await fetch('/api/exams');
        const examData = await examRes.json();
        const examList = Array.isArray(examData) ? examData : [];
        setExams(examList);
        if (examList.length > 0) setSelectedExamId(String(examList[0].id));
      } catch (err) {
        console.error('Failed to load exams', err);
      }

      try {
        const allocRes = await fetch(`/api/attendance/my-allocations/${faculty.id}`);
        const allocData = await allocRes.json();
        const allocList = allocData.allocations || [];
        setAllocations(allocList);
        if (allocList.length > 0) setSelectedAllocId(String(allocList[0].id));
      } catch (err) {
        console.error('Failed to load allocations', err);
      }

      await fetchRecentSessions();
      setLoading(false);
    };
    init();
  }, [faculty.id]);

  // Auto-pick batch when allocation changes
  useEffect(() => {
    if (selectedAlloc?.Batch) {
      setSelectedBatchId(String(selectedAlloc.Batch.id));
    } else {
      setSelectedBatchId('');
    }
  }, [selectedAllocId]);

  // Auto-set lecture type from allocation type
  useEffect(() => {
    if (selectedAlloc?.allocation_type) {
      setLectureType(selectedAlloc.allocation_type);
    }
  }, [selectedAllocId]);

  const getSessionPayload = () => {
    if (!selectedCourse || !selectedExamId) return null;
    return {
      faculty_id: faculty.id,
      course_id: selectedCourse.id,
      exam_id: selectedExamId,
      lecture_type: lectureType,
      batch_id: lectureType !== 'Theory' ? (selectedBatchId || null) : null,
      dept_id: selectedCourse.dept_id,
      class_sem: selectedCourse.semester,
      date,
      start_time: startTime,
      duration,
      topic
    };
  };

  const handleCreateSession = async () => {
    if (!topic.trim()) { setCreateError('Please enter a topic.'); return; }
    const payload = getSessionPayload();
    if (!payload) { setCreateError('Please select a subject.'); return; }
    setCreateError('');
    setCreating(true);
    try {
      const res = await fetch('/api/attendance/session/get-or-create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const data = await res.json();
      if (res.ok) {
        // Refresh recent sessions instead of auto-launching scanner
        await fetchRecentSessions();
        setTopic(''); // Clear topic for next one
        alert('Session created successfully. Use the "Recent Sessions" list below to start attendance.');
      } else {
        setCreateError(data.error || 'Failed to create session.');
      }
    } catch (err) {
      setCreateError('Network error. Is the server running?');
    } finally {
      setCreating(false);
    }
  };

  const handleViewRegister = () => {
    if (!selectedCourse || !selectedExamId) { setCreateError('Please select an exam term and subject.'); return; }
    setCreateError('');
    onViewRegister({
      allocation: selectedAlloc,
      course: selectedCourse,
      exam_id: selectedExamId,
      lecture_type: lectureType,
      batch_id: lectureType !== 'Theory' ? (selectedBatchId || null) : null,
      dept_id: selectedCourse.dept_id,
      sem: selectedCourse.semester
    });
  };

  const handleManualMarkFromSession = (sess) => {
    onViewRegister({
      allocation: null, // We don't have the full allocation object here, but it's optional
      course: sess.Course || { id: sess.course_id },
      exam_id: sess.exam_id,
      lecture_type: sess.lecture_type,
      batch_id: sess.batch_id,
      dept_id: sess.dept_id,
      sem: sess.class_sem
    });
  };

  const handleDeleteSession = async (sess) => {
    const msg = `⚠️ WARNING: Deleting this session will PERMANENTLY remove all ${sess.AttendanceRecords?.length || 0} attendance records marked for it.\n\nAre you sure you want to delete the session: "${sess.topic || 'Untitled'}"?`;
    if (!window.confirm(msg)) return;

    try {
      const res = await fetch(`/api/attendance/session/${sess.id}`, { method: 'DELETE' });
      if (res.ok) {
        await fetchRecentSessions();
      } else {
        const data = await res.json();
        alert(data.error || 'Failed to delete session.');
      }
    } catch (err) {
      alert('Network error.');
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-gray-50">
        <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mb-4"></div>
        <p className="text-gray-500 font-medium">Loading Dashboard...</p>
      </div>
    );
  }

  const inputCls = "w-full px-4 py-3 rounded-xl bg-gray-50 border border-gray-200 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none font-medium text-sm transition-all";
  const labelCls = "block text-[10px] font-black text-gray-400 uppercase tracking-widest mb-1.5 ml-0.5";

  const typeColors = {
    Theory: 'bg-blue-100 text-blue-700 border-blue-200',
    Practical: 'bg-emerald-100 text-emerald-700 border-emerald-200',
    Tutorial: 'bg-violet-100 text-violet-700 border-violet-200'
  };

  const formatDate = (d) => {
    if (!d) return '';
    return new Date(d + 'T00:00:00').toLocaleDateString('en-IN', { day: '2-digit', month: 'short' });
  };

  const formatTime = (t) => {
    if (!t) return '';
    const [h, m] = t.split(':');
    const hr = parseInt(h);
    return `${hr > 12 ? hr - 12 : hr}:${m} ${hr >= 12 ? 'PM' : 'AM'}`;
  };

  return (
    <div className="min-h-screen bg-gray-50 p-4 pb-20 font-sans">
      <div className="max-w-lg mx-auto space-y-6">

        {/* Header */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-5 flex justify-between items-center">
          <div className="flex items-center gap-3">
            <div className="w-11 h-11 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center font-black text-white text-lg shadow-lg shadow-blue-200">
              {faculty.name ? faculty.name.charAt(0).toUpperCase() : 'F'}
            </div>
            <div>
              <h2 className="font-bold text-gray-900 leading-tight">{faculty.name}</h2>
              <p className="text-[10px] text-gray-400 font-bold uppercase tracking-widest">Faculty Member</p>
            </div>
          </div>
          <button onClick={onLogout} className="text-xs font-bold text-red-500 bg-red-50 hover:bg-red-100 px-4 py-2 rounded-xl transition-all active:scale-95">
            Logout
          </button>
        </div>

        {/* Main Control Card */}
        <div className="bg-white rounded-2xl shadow-xl shadow-gray-200/60 border border-gray-100 overflow-hidden">
          <div className="bg-gradient-to-r from-gray-900 to-gray-800 px-6 py-5">
            <h3 className="text-white font-black text-lg">Create Attendance Session</h3>
            <p className="text-gray-400 text-xs mt-0.5">Initialize a session for scanning or manual marking</p>
          </div>

          <div className="p-6 space-y-4">
            {/* Exam Term */}
            <div>
              <label className={labelCls}>Exam Term</label>
              <select value={selectedExamId} onChange={e => setSelectedExamId(e.target.value)} className={inputCls}>
                <option value="">— Select Term —</option>
                {exams.map(ex => (
                  <option key={ex.id} value={ex.id}>{ex.year} {ex.season}</option>
                ))}
              </select>
            </div>

            {/* Lecture Type */}
            <div>
              <label className={labelCls}>Lecture Type</label>
              <div className="flex gap-2">
                {LECTURE_TYPES.map(t => (
                  <button key={t} onClick={() => setLectureType(t)}
                    className={`flex-1 py-2.5 rounded-xl text-xs font-black uppercase tracking-wide border transition-all ${lectureType === t ? 'bg-blue-600 text-white border-blue-600 shadow-lg shadow-blue-200' : 'bg-gray-50 text-gray-500 border-gray-200 hover:border-blue-300'}`}>
                    {t}
                  </button>
                ))}
              </div>
            </div>

            {/* Subject */}
            <div>
              <label className={labelCls}>Subject</label>
              <select value={selectedAllocId} onChange={e => setSelectedAllocId(e.target.value)} className={inputCls}>
                <option value="">— Select Subject —</option>
                {filteredAllocs.map(a => (
                  <option key={a.id} value={a.id}>
                    {a.Course?.code} — {a.Course?.name}
                    {a.Batch ? ` (${a.Batch.batch_name})` : ''}
                  </option>
                ))}
              </select>
            </div>

            {/* Date + Time + Duration */}
            <div className="grid grid-cols-3 gap-3">
              <div>
                <label className={labelCls}>Date</label>
                <input type="date" value={date} onChange={e => setDate(e.target.value)} className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>Time</label>
                <input type="time" value={startTime} onChange={e => setStartTime(e.target.value)} className={inputCls} />
              </div>
              <div>
                <label className={labelCls}>Hrs</label>
                <select value={duration} onChange={e => setDuration(parseInt(e.target.value))} className={inputCls}>
                  {[1, 2, 3, 4].map(h => <option key={h} value={h}>{h}</option>)}
                </select>
              </div>
            </div>

            {/* Topic */}
            <div>
              <label className={labelCls}>Topic / Title</label>
              <input type="text" value={topic} onChange={e => setTopic(e.target.value)}
                placeholder="e.g. Unit 2 – Linked Lists"
                className={inputCls} />
            </div>

            {createError && (
              <div className="bg-red-50 border border-red-200 text-red-700 text-xs font-semibold px-4 py-3 rounded-xl">
                {createError}
              </div>
            )}

            <div className="flex gap-3 pt-2">
              <button onClick={handleCreateSession} disabled={creating}
                className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-4 rounded-xl font-black text-sm shadow-lg shadow-blue-200 active:scale-95 transition-all disabled:opacity-60 flex items-center justify-center gap-2">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                {creating ? 'Creating...' : 'Create Session'}
              </button>
              <button onClick={handleViewRegister}
                className="bg-gray-100 hover:bg-gray-200 text-gray-700 px-6 py-4 rounded-xl font-black text-xs active:scale-95 transition-all">
                Full Register
              </button>
            </div>
          </div>
        </div>

        {/* Recent Sessions List */}
        <div className="space-y-3">
          <h3 className="text-[10px] font-black text-gray-400 uppercase tracking-widest ml-1">Recent Sessions</h3>
          {recentSessions.length === 0 ? (
            <div className="bg-white rounded-2xl border border-gray-100 p-8 text-center text-gray-400 text-sm">
              No sessions created yet.
            </div>
          ) : (
            <div className="space-y-3">
              {recentSessions.map(sess => (
                <div key={sess.id} className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100 flex flex-col gap-3">
                  <div className="flex justify-between items-start">
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className={`text-[9px] font-black px-2 py-0.5 rounded-full uppercase ${typeColors[sess.lecture_type] || typeColors.Theory}`}>
                          {sess.lecture_type}
                        </span>
                        <span className="text-gray-400 font-bold text-[10px] truncate">{sess.Course?.code}</span>
                      </div>
                      <h4 className="font-bold text-gray-900 truncate">{sess.topic || 'Untitled Session'}</h4>
                      <div className="text-[10px] text-gray-500 font-medium flex items-center gap-2 mt-1">
                        <span>{formatDate(sess.date)}</span>
                        <span>•</span>
                        <span>{formatTime(sess.start_time)}</span>
                        <span>•</span>
                        <span>{sess.duration} Hr{sess.duration > 1 ? 's' : ''}</span>
                      </div>
                    </div>
                    <div className="flex flex-col items-end gap-2 shrink-0">
                       <button
                         onClick={() => handleDeleteSession(sess)}
                         className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
                         title="Delete Session">
                         <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                           <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                         </svg>
                       </button>
                       <div className="text-right">
                          <div className={`text-xs font-black ${sess.is_locked ? 'text-red-500' : 'text-green-500'}`}>
                             {sess.AttendanceRecords?.length || 0} Present
                          </div>
                          {sess.is_locked && (
                            <div className="text-[9px] text-red-400 font-bold uppercase mt-0.5">Locked</div>
                          )}
                       </div>
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <button
                      onClick={() => onSessionCreated(sess)}
                      className={`flex-1 py-2.5 rounded-xl text-xs font-black uppercase tracking-wide flex items-center justify-center gap-1.5 transition-all ${sess.is_locked ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-blue-50 text-blue-600 hover:bg-blue-100'}`}
                      disabled={sess.is_locked}>
                      <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 3.5V16M3 3l18 18" />
                      </svg>
                      Scan QR
                    </button>
                    <button
                      onClick={() => handleManualMarkFromSession(sess)}
                      className="flex-1 bg-gray-50 text-gray-600 hover:bg-gray-100 py-2.5 rounded-xl text-xs font-black uppercase tracking-wide flex items-center justify-center gap-1.5 transition-all">
                      <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                      </svg>
                      Manual
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

      </div>
    </div>
  );
};

window.TeacherDashboard = TeacherDashboard;
