import React, { useEffect, useMemo, useState } from 'react';
import { apiExam, type ExamRoomItem } from '../api';
import { openExam } from './NavHistoryBar';
import { useAuth } from '../auth/AuthContext';

function fmtTime(iso: string) {
  try {
    return new Date(iso).toLocaleString('vi-VN');
  } catch {
    return iso;
  }
}

function statusLabel(st: string) {
  if (st === 'draft') return { text: 'Tạm thời', cls: 'badge-muted' };
  if (st === 'ready') return { text: 'Sẵn sàng', cls: 'badge-info' };
  if (st === 'active') return { text: 'Đang thi', cls: 'badge-success' };
  if (st === 'cancelled') return { text: 'Đã hủy', cls: 'badge-warning' };
  if (st === 'ended') return { text: 'Đã kết thúc', cls: 'badge-muted' };
  return { text: st, cls: 'badge-muted' };
}

function toLocalInput(iso?: string) {
  if (!iso) return '';
  const d = new Date(iso);
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

function localInputToISO(v: string) {
  if (!v) return '';
  return new Date(v).toISOString();
}

export const ExamsTab: React.FC = () => {
  const { staff } = useAuth();
  const isSuperAdmin = staff?.email === 'phuocntb@rikkeiacademy.com';

  const [rooms, setRooms] = useState<ExamRoomItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreate, setShowCreate] = useState(false);
  const [name, setName] = useState('');
  const [start, setStart] = useState('');
  const [end, setEnd] = useState('');
  const [busy, setBusy] = useState(false);
  const [search, setSearch] = useState('');

  const load = async () => {
    setLoading(true);
    try {
      const res = await apiExam.list();
      setRooms(res.data);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

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

  const stats = useMemo(() => {
    const active = rooms.filter((r) => (r.displayStatus || r.status) === 'active').length;
    const upcoming = rooms.filter((r) => {
      const st = r.displayStatus || r.status;
      return st === 'ready' || st === 'draft';
    }).length;
    return { total: rooms.length, active, upcoming };
  }, [rooms]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return rooms;
    return rooms.filter((r) => r.name.toLowerCase().includes(q));
  }, [rooms, search]);

  const create = async () => {
    if (!name.trim() || !start || !end) return;
    setBusy(true);
    try {
      const room = await apiExam.create({
        name: name.trim(),
        startTime: localInputToISO(start),
        endTime: localInputToISO(end),
      });
      setShowCreate(false);
      setName('');
      setStart('');
      setEnd('');
      await load();
      openExam(room.id, room.name);
    } catch (e: any) {
      alert(e?.message || 'Lỗi');
    } finally {
      setBusy(false);
    }
  };

  const handleDeleteRoom = async (roomId: number, roomName: string) => {
    if (window.confirm(`Bạn có chắc chắn muốn xóa hoàn toàn phòng thi "${roomName}" không? Hành động này sẽ xóa sạch dữ liệu phòng thi, các bài nộp, và không thể khôi phục.`)) {
      try {
        await apiExam.remove(roomId);
        alert('Đã xóa phòng thi thành công!');
        await load();
      } catch (err: any) {
        alert(err.message || 'Xóa phòng thi thất bại');
      }
    }
  };

  return (
    <div className="tab-page exams-page">
      <header className="page-header page-header--row">
        <div>
          <h1 className="page-title">Danh sách phòng thi</h1>
          <p className="page-desc">Tạo phòng, chia đề ngẫu nhiên, gửi đề và thu bài từ sinh viên.</p>
        </div>
        <button type="button" className="btn btn-primary" onClick={() => setShowCreate(true)}>
          + Tạo phòng thi
        </button>
      </header>

      <div className="exams-stats-row">
        <div className="learning-stat">
          <span className="learning-stat-value">{stats.total}</span>
          <span className="learning-stat-label">Tổng phòng</span>
        </div>
        <div className="learning-stat learning-stat--accent">
          <span className="learning-stat-value">{stats.active}</span>
          <span className="learning-stat-label">Đang thi</span>
        </div>
        <div className="learning-stat">
          <span className="learning-stat-value">{stats.upcoming}</span>
          <span className="learning-stat-label">Sắp / tạm</span>
        </div>
      </div>

      <div className="exams-toolbar">
        <input
          type="search"
          className="app-pool-search exams-search"
          placeholder="Tìm theo tên phòng thi..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {showCreate && (
        <div className="modal-overlay" onClick={() => setShowCreate(false)}>
          <div className="modal-container" style={{ maxWidth: '500px' }} onClick={e => e.stopPropagation()}>
            <div className="modal-header">
              <h2 className="modal-title">Tạo phòng thi mới</h2>
              <button className="modal-close-btn" onClick={() => setShowCreate(false)} aria-label="Đóng">&times;</button>
            </div>
            <div className="modal-body" style={{ padding: '1.5rem', display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
              <label className="login-field" style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
                <span style={{ fontWeight: 600, fontSize: '0.85rem', color: 'var(--text-secondary)' }}>Tên phòng thi</span>
                <input
                  className="search-input"
                  style={{ width: '100%', boxSizing: 'border-box' }}
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="VD: Thi cuối kỳ Java"
                />
              </label>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
                <label className="login-field" style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
                  <span style={{ fontWeight: 600, fontSize: '0.85rem', color: 'var(--text-secondary)' }}>Bắt đầu</span>
                  <input
                    type="datetime-local"
                    className="search-input"
                    style={{ width: '100%', boxSizing: 'border-box', padding: '0.5rem 0.75rem' }}
                    value={start}
                    onChange={(e) => setStart(e.target.value)}
                  />
                </label>
                <label className="login-field" style={{ display: 'flex', flexDirection: 'column', gap: '0.35rem' }}>
                  <span style={{ fontWeight: 600, fontSize: '0.85rem', color: 'var(--text-secondary)' }}>Kết thúc</span>
                  <input
                    type="datetime-local"
                    className="search-input"
                    style={{ width: '100%', boxSizing: 'border-box', padding: '0.5rem 0.75rem' }}
                    value={end}
                    onChange={(e) => setEnd(e.target.value)}
                  />
                </label>
              </div>
            </div>
            <div className="modal-footer" style={{ gap: '0.65rem' }}>
              <button type="button" className="btn btn-secondary" onClick={() => setShowCreate(false)}>
                Hủy
              </button>
              <button type="button" className="btn btn-primary" disabled={busy} onClick={create}>
                {busy ? 'Đang tạo...' : 'Tạo & mở phòng'}
              </button>
            </div>
          </div>
        </div>
      )}

      {loading ? (
        <div className="system-empty">Đang tải...</div>
      ) : filtered.length === 0 ? (
        <div className="system-empty">
          {search.trim() ? 'Không tìm thấy phòng thi phù hợp.' : 'Chưa có phòng thi — bấm Tạo phòng thi để bắt đầu.'}
        </div>
      ) : (
        <div className="exams-card-grid">
          {filtered.map((r) => {
            const st = statusLabel(r.displayStatus || r.status);
            return (
              <article key={r.id} className="exam-list-card">
                <div className="exam-list-card-head">
                  <h3>{r.name}</h3>
                  <span className={`badge ${st.cls}`}>{st.text}</span>
                </div>
                <div className="exam-list-card-meta">
                  <div>
                    <span className="exam-list-card-label">Thời gian</span>
                    <span>{fmtTime(r.startTime)}</span>
                    <span className="exam-list-card-sep">→</span>
                    <span>{fmtTime(r.endTime)}</span>
                  </div>
                  <div>
                    <span className="exam-list-card-label">Quy mô</span>
                    <span>{r.studentCount} sinh viên · {r.paperCount} đề</span>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '8px', marginTop: '1.25rem' }}>
                  <button type="button" className="btn btn-primary btn-sm exam-list-card-open" onClick={() => openExam(r.id, r.name)} style={{ flex: 1, margin: 0 }}>
                    Mở phòng thi
                  </button>
                  {isSuperAdmin && (
                    <button
                      type="button"
                      className="btn btn-secondary btn-sm"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDeleteRoom(r.id, r.name);
                      }}
                      style={{
                        borderColor: 'var(--danger)',
                        color: 'var(--danger)',
                        backgroundColor: 'transparent',
                        padding: '0.5rem 0.75rem',
                        fontWeight: 600,
                        transition: 'var(--transition)',
                        margin: 0
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'var(--danger)';
                        e.currentTarget.style.color = '#fff';
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'transparent';
                        e.currentTarget.style.color = 'var(--danger)';
                      }}
                    >
                      Xóa
                    </button>
                  )}
                </div>
              </article>
            );
          })}
        </div>
      )}
    </div>
  );
};

export { toLocalInput, localInputToISO, fmtTime };
