import React, { useEffect, useState } from 'react';
import { 
  api, 
  apiSaveAllowedApps, 
  apiFetchClassStudents, 
  apiFetchOnlineStudents, 
  apiFetchClassSessionLogs,
  apiFetchClassSchedule,
  apiFetchAllowedApps,
  apiFetchAttendanceShifts,
} from '../api';
import type { 
  ClassItem, 
  StudentItem, 
  ClassScheduleItem, 
  StudentSessionLogItem,
} from '../api';
import { BASE_APP_SUGGESTIONS } from '../constants';
import { pushNav, type TabId } from '../navigation';
import { ScheduleEditor } from './ScheduleEditor';
import { AttendancePanel } from './AttendancePanel';
import { StudentAvatar } from './StudentAvatar';
import { StudentDetailModal } from './StudentDetailModal';
import { AppPoolModal } from './AppPoolModal';

interface ClassWorkspaceProps {
  classId: number;
  sourceTab?: TabId;
  onBack?: () => void;
  renderNavBar?: (className: string) => React.ReactNode;
}

export const ClassWorkspace: React.FC<ClassWorkspaceProps> = ({ classId, sourceTab = 'classes', renderNavBar }) => {
  const [classInfo, setClassInfo] = useState<ClassItem | null>(null);
  const [students, setStudents] = useState<StudentItem[]>([]);
  const [onlineIds, setOnlineIds] = useState<number[]>([]);
  const [allowedApps, setAllowedApps] = useState('');
  const [schedules, setSchedules] = useState<ClassScheduleItem[]>([]);
  const [sessionLogs, setSessionLogs] = useState<StudentSessionLogItem[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const today = new Date().toISOString().slice(0, 10);
  const [logDate, setLogDate] = useState(today);
  const [logPeriod, setLogPeriod] = useState(1);
  const [logShifts, setLogShifts] = useState<any[]>([]);
  const [selectedStudent, setSelectedStudent] = useState<StudentItem | null>(null);
  
  // Loading & tab states
  const [loading, setLoading] = useState(true);
  const [logsLoading, setLogsLoading] = useState(false);
  const [savingApps, setSavingApps] = useState(false);
  const [activeSubTab, setActiveSubTab] = useState<'roster' | 'logs' | 'attendance'>('roster');
  const [configOpen, setConfigOpen] = useState(false);
  const [configTab, setConfigTab] = useState<'apps' | 'schedule'>('schedule');
  const [appPoolOpen, setAppPoolOpen] = useState(false);

  const loadAllData = async () => {
    try {
      setLoading(true);
      
      // Fetch specific class detail directly
      const classData = await api.getClass(classId);
      setClassInfo(classData);
      pushNav({
        kind: 'class',
        tab: sourceTab,
        classId,
        label: classData.name || `Lớp ${classId}`,
      });

      // Fetch students roster
      const studentsRes = await apiFetchClassStudents(classId);
      setStudents(studentsRes.data);

      // Fetch allowed apps
      try {
        const appsRes = await apiFetchAllowedApps(classId);
        setAllowedApps(appsRes.keywords || '');
      } catch (e) {
        console.log("No allowed apps configured yet");
      }

      // Fetch schedules
      try {
        const schedRes = await apiFetchClassSchedule(classId);
        setSchedules(schedRes.data || []);
      } catch (e) {
        console.log("No schedule configured yet");
      }

      // Fetch online status
      await fetchOnlineStatus();

      // Fetch logs
      await fetchLogs();

    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const fetchOnlineStatus = async () => {
    try {
      const res = await apiFetchOnlineStudents(classId);
      setOnlineIds(res.onlineStudentIds || []);
    } catch (e) {
      console.error("Failed to load online students list", e);
    }
  };

  const fetchLogs = async (date = logDate, period = logPeriod) => {
    try {
      setLogsLoading(true);
      const res = await apiFetchClassSessionLogs(classId, date, period);
      setSessionLogs(res.data || []);
      if (res.period) setLogPeriod(res.period);
    } catch (e) {
      console.error("Failed to load session logs", e);
    } finally {
      setLogsLoading(false);
    }
  };

  const loadLogShifts = async (date = logDate) => {
    try {
      const res = await apiFetchAttendanceShifts(classId, date);
      setLogShifts(res.data || []);
    } catch {
      setLogShifts([]);
    }
  };

  useEffect(() => {
    loadAllData();
  }, [classId]);

  useEffect(() => {
    const interval = setInterval(() => {
      fetchOnlineStatus();
      fetchLogs(logDate, logPeriod);
    }, 5000);
    return () => clearInterval(interval);
  }, [classId, logDate, logPeriod]);

  useEffect(() => {
    loadLogShifts(logDate);
    if (activeSubTab === 'logs') {
      fetchLogs(logDate, logPeriod);
    }
  }, [activeSubTab, logDate, logPeriod, classId]);

  useEffect(() => {
    fetchLogs(logDate, logPeriod);
    loadLogShifts(logDate);
  }, [classId]);

  const handleToggleStudying = async () => {
    if (!classInfo) return;
    const nextVal = !classInfo.isStudying;
    try {
      setClassInfo(prev => prev ? { ...prev, isStudying: nextVal } : null);
      await api.updateClassStudying(classId, nextVal);
    } catch (err: any) {
      setClassInfo(prev => prev ? { ...prev, isStudying: !nextVal } : null);
      alert(err.message || 'Không thể cập nhật trạng thái lớp học');
    }
  };

  const addAppKeyword = (kw: string) => {
    const trimmed = kw.trim().toLowerCase();
    if (!trimmed) return;
    setAllowedApps(prev => {
      const parts = prev.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
      if (parts.includes(trimmed)) return prev;
      return prev ? `${prev}, ${trimmed}` : trimmed;
    });
  };

  const handleSaveAllowedApps = async () => {
    try {
      setSavingApps(true);
      await apiSaveAllowedApps(classId, allowedApps);
      alert('Đã lưu cấu hình ứng dụng được phép thành công!');
    } catch (e: any) {
      alert(e.message || 'Lỗi khi lưu cấu hình ứng dụng');
    } finally {
      setSavingApps(false);
    }
  };

  const reloadSchedules = async () => {
    try {
      const schedRes = await apiFetchClassSchedule(classId);
      setSchedules(schedRes.data || []);
    } catch {
      setSchedules([]);
    }
  };

  const filteredStudents = students.filter(st => {
    const term = searchQuery.toLowerCase().trim();
    if (!term) return true;
    return (
      st.fullName.toLowerCase().includes(term) ||
      st.studentCode.toLowerCase().includes(term) ||
      st.email.toLowerCase().includes(term) ||
      (st.phone && st.phone.includes(term))
    );
  });

  const formatDuration = (totalSeconds: number) => {
    const hrs = Math.floor(totalSeconds / 3600);
    const mins = Math.floor((totalSeconds % 3600) / 60);
    const secs = totalSeconds % 60;
    const pad = (num: number) => String(num).padStart(2, '0');
    return `${pad(hrs)}:${pad(mins)}:${pad(secs)}`;
  };

  if (loading) {
    return (
      <div className="loading-screen">
        <div className="sync-spinner" style={{ width: '36px', height: '36px', borderWidth: '3px' }}></div>
        <div style={{ fontWeight: 600, fontSize: '0.95rem', color: 'var(--text-secondary)' }}>Đang tải không gian làm việc của lớp...</div>
      </div>
    );
  }

  if (!classInfo) {
    return (
      <div className="loading-screen">
        <div className="empty-state-icon">🏫</div>
        <div style={{ fontWeight: 700, fontSize: '1.15rem', color: 'var(--danger)' }}>Không tìm thấy thông tin lớp học</div>
        <button className="btn btn-secondary" onClick={() => window.close()}>Đóng tab</button>
      </div>
    );
  }

  const onlineCount = students.filter(st => onlineIds.includes(st.rkId)).length;

  const getSessionLogForStudent = (rkId: number) =>
    sessionLogs.find(log => log.studentRkId === rkId) || null;

  return (
    <div className="workspace-layout workspace-embedded">
      {renderNavBar && classInfo && renderNavBar(classInfo.name)}

      {/* Header section */}
      <div className="workspace-header">
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: '0.75rem' }}>
            <div className="brand-logo" style={{ width: 44, height: 44, fontSize: '1.1rem' }}>🏫</div>
            <div>
              <h1 className="workspace-class-title">{classInfo.name}</h1>
              <div className="class-badge-container">
                <span className="badge badge-muted" style={{ fontFamily: 'monospace' }}>CODE: {classInfo.classCode}</span>
                <span className="badge badge-info">ID: {classInfo.rkId}</span>
                <span className="badge badge-muted">{classInfo.systemName || 'Hệ thống'}</span>
              </div>
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: '1.25rem', flexWrap: 'wrap' }}>
          <div className="status-panel">
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <span style={{ fontSize: '0.72rem', color: 'var(--text-muted)', fontWeight: 600, textTransform: 'uppercase' }}>Trạng thái dạy</span>
              <span style={{ fontSize: '0.875rem', fontWeight: 700, color: classInfo.isStudying ? 'var(--success)' : 'var(--text-muted)' }}>
                {classInfo.isStudying ? 'Đang học' : 'Tạm dừng'}
              </span>
            </div>
            <label className="switch">
              <input type="checkbox" checked={classInfo.isStudying} onChange={handleToggleStudying} />
              <span className="slider"></span>
            </label>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
            <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', fontWeight: 600, textTransform: 'uppercase' }}>Online / Sĩ số</div>
            <div className="workspace-stat-value">
              <span style={{ color: 'var(--success)' }}>{onlineCount}</span>
              <span style={{ color: 'var(--text-muted)', fontSize: '0.9rem', fontWeight: 500 }}> / {students.length} SV</span>
            </div>
          </div>
        </div>
      </div>

      {/* Main area */}
      <div className="workspace-main">
        {configOpen && (
          <div className="workspace-drawer-backdrop" onClick={() => setConfigOpen(false)} aria-hidden />
        )}

        <aside className={`workspace-config-drawer ${configOpen ? 'open' : ''}`}>
          <div className="workspace-drawer-header">
            <strong>Cấu hình lớp</strong>
            <button type="button" className="btn btn-secondary workspace-drawer-close" onClick={() => setConfigOpen(false)} aria-label="Đóng">×</button>
          </div>
          <div className="workspace-drawer-tabs">
            <button type="button" className={`workspace-drawer-tab ${configTab === 'apps' ? 'active' : ''}`} onClick={() => setConfigTab('apps')}>
              Ứng dụng
            </button>
            <button type="button" className={`workspace-drawer-tab ${configTab === 'schedule' ? 'active' : ''}`} onClick={() => setConfigTab('schedule')}>
              Lịch học
            </button>
          </div>
          <div className="workspace-drawer-body">
            {configTab === 'apps' ? (
              <div className="config-card config-card-flat">
                <div className="card-header-title">Ứng dụng được phép</div>
                <p className="config-card-desc">
                  Từ khóa tiến trình hoặc tiêu đề được phép (ngăn cách bằng dấu phẩy).
                </p>
                <textarea
                  className="app-textarea"
                  placeholder="chrome, vscode, cursor, goland, client, zoom"
                  value={allowedApps}
                  onChange={e => setAllowedApps(e.target.value)}
                />
                <div className="config-suggestions">
                  <span className="config-suggestions-label">Gợi ý nhanh:</span>
                  <div className="config-suggestions-list">
                    {BASE_APP_SUGGESTIONS.map(kw => (
                      <span key={kw} className="app-suggestion-badge" onClick={() => addAppKeyword(kw)}>
                        + {kw}
                      </span>
                    ))}
                  </div>
                </div>
                <div className="app-pool-open-row">
                  <div>
                    <span className="config-suggestions-label">Kho ứng dụng (toàn hệ thống)</span>
                    <p className="discovered-apps-hint" style={{ margin: '0.25rem 0 0' }}>
                      App bị chặn từ mọi lớp — mở kho để tìm và thêm nhanh.
                    </p>
                  </div>
                  <button
                    type="button"
                    className="btn btn-secondary app-pool-open-btn"
                    onClick={() => setAppPoolOpen(true)}
                  >
                    Mở kho & tìm kiếm
                  </button>
                </div>
                <button
                  className="btn btn-primary"
                  style={{ width: '100%', justifyContent: 'center' }}
                  onClick={handleSaveAllowedApps}
                  disabled={savingApps}
                >
                  {savingApps ? 'Đang lưu...' : 'Lưu cấu hình apps'}
                </button>
              </div>
            ) : (
              <div className="config-card config-card-flat">
                <div className="card-header-title">Lịch học trong tuần</div>
                <p className="config-card-desc">Tối đa 4 ca/ngày. Chọn môn từ QLĐT cho từng ca.</p>
                <ScheduleEditor classId={classId} schedules={schedules} onSaved={reloadSchedules} />
              </div>
            )}
          </div>
        </aside>

        <div className="right-panel workspace-content-panel">
          <div className="workspace-panel-toolbar">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '1rem' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.65rem', flexWrap: 'wrap' }}>
              <button
                type="button"
                className={`btn btn-secondary workspace-config-toggle ${configOpen ? 'active' : ''}`}
                onClick={() => setConfigOpen(v => !v)}
              >
                {configOpen ? 'Ẩn cấu hình' : 'Cấu hình lớp'}
              </button>
              <div className="tab-btn-group">
              <button 
                className={`tab-sub-btn ${activeSubTab === 'roster' ? 'active' : ''}`}
                onClick={() => setActiveSubTab('roster')}
              >
                Sơ đồ học viên
              </button>
              <button 
                className={`tab-sub-btn ${activeSubTab === 'logs' ? 'active' : ''}`}
                onClick={() => setActiveSubTab('logs')}
              >
                Nhật ký theo ca
              </button>
              <button 
                className={`tab-sub-btn ${activeSubTab === 'attendance' ? 'active' : ''}`}
                onClick={() => setActiveSubTab('attendance')}
              >
                Điểm danh theo ca
              </button>
              </div>
            </div>

            {/* Student Search */}
            {activeSubTab !== 'attendance' && <div className="search-input-wrapper">
              <input
                type="text"
                className="search-input"
                placeholder="Tìm học viên..."
                value={searchQuery}
                onChange={e => setSearchQuery(e.target.value)}
              />
              <span className="search-icon">🔍</span>
            </div>}
          </div>

          <div className="divider" style={{ opacity: 0.3, margin: '0.25rem 0' }}></div>
          </div>

          <div className={`workspace-panel-body ${activeSubTab === 'attendance' || activeSubTab === 'logs' ? 'workspace-panel-fill' : ''}`}>
          {activeSubTab === 'attendance' ? (
            <AttendancePanel classId={classId} />
          ) : activeSubTab === 'roster' ? (
            /* Student Roster Grid */
            filteredStudents.length === 0 ? (
              <div className="empty-state" style={{ minHeight: '300px' }}>
                <div className="empty-state-icon">👤</div>
                <h2>Không tìm thấy học viên nào</h2>
                <p>Hãy thử tìm kiếm với từ khóa khác hoặc kiểm tra lại danh sách lớp.</p>
              </div>
            ) : (
              <div className="student-status-grid">
                {filteredStudents.map(st => {
                  const isOnline = onlineIds.includes(st.rkId);
                  return (
                    <div
                      key={st.rkId}
                      className={`student-status-card student-status-card-clickable ${isOnline ? 'online' : 'offline'}`}
                      onClick={() => setSelectedStudent(st)}
                      role="button"
                      tabIndex={0}
                      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') setSelectedStudent(st); }}
                    >
                      <StudentAvatar fullName={st.fullName} avatar={st.avatar} isOnline={isOnline} size={52} />
                      <div style={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }}>
                        <span style={{ fontSize: '0.875rem', fontWeight: 600, color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                          {st.fullName}
                        </span>
                        <span style={{ fontSize: '0.78rem', color: 'var(--accent)', fontFamily: 'monospace', fontWeight: 600 }}>
                          {st.studentCode}
                        </span>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '0.35rem', marginTop: '0.4rem' }}>
                          <span className={isOnline ? 'pulse-dot-online' : 'status-badge-offline'}></span>
                          <span style={{ fontSize: '0.75rem', fontWeight: 700, color: isOnline ? 'var(--success)' : 'var(--text-muted)' }}>
                            {isOnline ? 'ONLINE' : 'OFFLINE'}
                          </span>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )
          ) : (
            <div className="session-logs-panel">
              <div className="attendance-toolbar" style={{ marginBottom: '0.5rem' }}>
                <label className="attendance-field">
                  <span>Ngày</span>
                  <input type="date" className="search-input" style={{ padding: '0.5rem 0.75rem' }} value={logDate} onChange={e => setLogDate(e.target.value)} />
                </label>
                <label className="attendance-field">
                  <span>Ca học</span>
                  <select className="select-filter" value={logPeriod} onChange={e => setLogPeriod(Number(e.target.value))}>
                    {(logShifts.length ? logShifts : [{ period: 1 }, { period: 2 }, { period: 3 }, { period: 4 }]).map((s: any) => (
                      <option key={s.period} value={s.period}>
                        Ca {s.period}{s.startTime ? ` (${s.startTime}–${s.endTime})` : ''}
                      </option>
                    ))}
                  </select>
                </label>
              </div>
              <div className="attendance-table-scroll table-wrapper" style={{ border: 'none' }}>
              {logsLoading ? (
                <div className="empty-state" style={{ minHeight: '300px' }}>
                  <div className="sync-spinner" style={{ width: '32px', height: '32px' }}></div>
                  <p style={{ marginTop: '0.5rem' }}>Đang tải nhật ký điểm danh học tập...</p>
                </div>
              ) : sessionLogs.length === 0 ? (
                <div className="empty-state" style={{ minHeight: '300px' }}>
                  <div className="empty-state-icon">📊</div>
                  <h2>Chưa có nhật ký Ca {logPeriod}</h2>
                  <p>Hệ thống ghi nhận theo từng ca khi học viên mở app trong khung giờ học.</p>
                </div>
              ) : (
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>Học viên</th>
                      <th>Thời gian Online</th>
                      <th>Thời gian Offline</th>
                      <th>WiFi SSID</th>
                      <th>Hoạt động cuối</th>
                    </tr>
                  </thead>
                  <tbody>
                    {sessionLogs.map(logItem => (
                      <tr key={logItem.studentRkId}>
                        <td>
                          <div style={{ fontWeight: 600, color: 'var(--text-primary)' }}>{logItem.fullName}</div>
                          <div style={{ fontSize: '0.75rem', color: 'var(--text-secondary)' }}>{logItem.studentCode} | {logItem.email}</div>
                        </td>
                        <td style={{ color: 'var(--success)', fontWeight: 700, fontFamily: 'monospace' }}>
                          {formatDuration(logItem.onlineSeconds)}
                        </td>
                        <td style={{ color: 'var(--danger)', fontWeight: 700, fontFamily: 'monospace' }}>
                          {formatDuration(logItem.offlineSeconds)}
                        </td>
                        <td style={{ fontSize: '0.85rem', fontFamily: 'monospace' }}>📶 {logItem.wifiSsids}</td>
                        <td style={{ fontSize: '0.8rem', color: 'var(--text-secondary)' }}>
                          {logItem.lastActiveAt ? new Date(logItem.lastActiveAt).toLocaleTimeString() : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              )}
              </div>
            </div>
          )}
          </div>
        </div>
      </div>

      {selectedStudent && (
        <StudentDetailModal
          student={selectedStudent}
          isOnline={onlineIds.includes(selectedStudent.rkId)}
          sessionLog={getSessionLogForStudent(selectedStudent.rkId)}
          onClose={() => setSelectedStudent(null)}
        />
      )}

      <AppPoolModal
        open={appPoolOpen}
        onClose={() => setAppPoolOpen(false)}
        onSelect={addAppKeyword}
        allowedApps={allowedApps}
      />
    </div>
  );
};
