const { useEffect, useState, useRef } = React;

const ScannerView = ({ session, onFinish }) => {
  const [attendanceMap, setAttendanceMap] = useState({}); // enrollment_no -> true/false
  const [roster, setRoster] = useState([]);
  const [toasts, setToasts] = useState([]);
  const [error, setError] = useState(null);
  const [saving, setSaving] = useState(false);
  const [activeTab, setActiveTab] = useState('scanner'); // 'scanner' | 'list'
  const scannerRef = useRef(null);

  const [cameras, setCameras] = useState([]);
  const [currentCameraIndex, setCurrentCameraIndex] = useState(0);
  const [useSpecificCamera, setUseSpecificCamera] = useState(false);
  const [retryCount, setRetryCount] = useState(0);

  const [zoom, setZoom] = useState(1);
  const [maxZoom, setMaxZoom] = useState(5);
  const [canZoom, setCanZoom] = useState(true);
  const [torch, setTorch] = useState(false);
  const [canTorch, setCanTorch] = useState(false);

  const addToast = (name, ok = true) => {
    const id = Date.now();
    setToasts(prev => [{ id, name, ok }, ...prev].slice(0, 5));
    setTimeout(() => setToasts(prev => prev.filter(t => t.id !== id)), 3000);
  };

  // ── Load student roster + existing attendance ───────────────────────────────
  useEffect(() => {
    const load = async () => {
      try {
        // Fetch students for this session (use register endpoint)
        const params = new URLSearchParams({
          course_id: session.course_id,
          exam_id: session.exam_id,
          lecture_type: session.lecture_type || 'Theory',
          dept_id: session.dept_id,
          sem: session.class_sem
        });
        if (session.batch_id) params.set('batch_id', session.batch_id);

        const res = await fetch(`/api/attendance/register?${params}`);
        if (res.ok) {
          const data = await res.json();
          setRoster(data.students || []);
          // Pre-populate attendance from existing records for this session
          const existing = (data.records || {})[session.id] || {};
          setAttendanceMap(existing);
        }
      } catch (e) {
        console.error('Failed to load roster', e);
      }
    };
    load();
  }, [session.id]);

  // ── QR Scanner ──────────────────────────────────────────────────────────────
  const startScanner = async () => {
    if (!window.Html5Qrcode) { setError("Scanner library not loaded."); return; }
    
    // Check if browser allows camera access (requires HTTPS or localhost)
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      setError("Camera access is blocked by your browser's security policy. If you are accessing this on a mobile device via an IP address, you MUST use HTTPS or a secure tunnel like ngrok.");
      return;
    }

    try {
      if (scannerRef.current) {
        try { await scannerRef.current.stop(); } catch (e) {}
      }
      const html5Qrcode = new window.Html5Qrcode("qr-reader");
      try {
        const devices = await window.Html5Qrcode.getCameras();
        if (devices) setCameras(devices);
      } catch (e) {}

      const onScanSuccess = async (decodedText) => {
        if (!decodedText) return;
        const enrollmentNo = decodedText.trim();
        const student = roster.find(s => s.enrollment_no === enrollmentNo);
        if (!student) return;
        if (attendanceMap[enrollmentNo]) return; // already marked

        // Mark present
        const updated = { ...attendanceMap, [enrollmentNo]: true };
        setAttendanceMap(updated);
        addToast(`✅ ${student.full_name}`);

        // Auto-save this single record
        try {
          const res = await fetch('/api/attendance/records', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              session_id: session.id,
              records: [{ student_enrollment_no: enrollmentNo, is_present: true }]
            })
          });
          if (!res.ok) {
            const data = await res.json();
            addToast(`⚠️ ${data.error || 'Failed to save'}`, false);
            // Revert local state
            setAttendanceMap(prev => {
              const next = { ...prev };
              delete next[enrollmentNo];
              return next;
            });
          }
        } catch (e) {
          addToast('⚠️ Network error', false);
          setAttendanceMap(prev => {
            const next = { ...prev };
            delete next[enrollmentNo];
            return next;
          });
        }
      };

      const config = { fps: 30, qrbox: (vw, vh) => ({ width: vw * 0.9, height: vh * 0.7 }) };
      
      // Default to environment (back) camera. Only use specific index if user manually switched.
      const cameraId = (useSpecificCamera && cameras.length > 0 && cameras[currentCameraIndex])
        ? cameras[currentCameraIndex].id
        : { facingMode: "environment" };
        
      try {
        await html5Qrcode.start(cameraId, config, onScanSuccess, () => {});
      } catch (e) {
        if (!useSpecificCamera && cameraId.facingMode === "environment") {
          // Fallback to user camera (front camera) if environment (rear camera) fails
          await html5Qrcode.start({ facingMode: "user" }, config, onScanSuccess, () => {});
        } else {
          throw e;
        }
      }
      scannerRef.current = html5Qrcode;

      setTimeout(() => {
        try {
          const video = document.querySelector('#qr-reader video');
          const track = video?.srcObject?.getVideoTracks()[0];
          const caps = track?.getCapabilities?.();
          if (track && caps) {
            if (caps.zoom) { setMaxZoom(caps.zoom.max || 10); setCanZoom(true); track.applyConstraints({ advanced: [{ zoom: 1 }] }).catch(() => {}); }
            if (caps.torch) setCanTorch(true);
          }
        } catch (e) {}
      }, 1500);
      setError(null);
    } catch (err) { setError(err.toString()); }
  };

  useEffect(() => {
    if (activeTab === 'scanner') {
      startScanner();
    } else {
      // Stop scanner when switching to list
      if (scannerRef.current) scannerRef.current.stop().catch(() => {});
    }
    return () => { if (scannerRef.current) scannerRef.current.stop().catch(() => {}); };
  }, [retryCount, currentCameraIndex, activeTab, roster.length > 0]);

  const toggleTorch = async () => {
    const newTorch = !torch;
    setTorch(newTorch);
    try {
      const video = document.querySelector('#qr-reader video');
      const track = video?.srcObject?.getVideoTracks()[0];
      await track?.applyConstraints({ advanced: [{ torch: newTorch }] });
    } catch (e) {}
  };

  const handleZoomChange = async (e) => {
    const val = parseFloat(e.target.value);
    setZoom(val);
    try {
      const video = document.querySelector('#qr-reader video');
      const track = video?.srcObject?.getVideoTracks()[0];
      await track?.applyConstraints({ advanced: [{ zoom: val }] });
    } catch (e) {}
  };

  const switchCamera = () => {
    if (cameras.length > 1) { 
      setUseSpecificCamera(true);
      setCurrentCameraIndex(prev => (prev + 1) % cameras.length); 
      setRetryCount(p => p + 1); 
    }
  };

  // ── Manual Toggle (from list view) ─────────────────────────────────────────
  const handleManualToggle = async (student, newValue) => {
    const enrollmentNo = student.enrollment_no;
    setAttendanceMap(prev => ({ ...prev, [enrollmentNo]: newValue }));

    try {
      const res = await fetch('/api/attendance/records', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          session_id: session.id,
          records: [{ student_enrollment_no: enrollmentNo, is_present: newValue }]
        })
      });
      if (res.ok) {
        addToast(newValue ? `✅ ${student.full_name}` : `❌ ${student.full_name}`);
      } else {
        const data = await res.json();
        addToast(`⚠️ ${data.error || 'Save failed'}`, false);
        setAttendanceMap(prev => ({ ...prev, [enrollmentNo]: !newValue })); // Revert
      }
    } catch (e) {
      addToast('⚠️ Network error', false);
      setAttendanceMap(prev => ({ ...prev, [enrollmentNo]: !newValue })); // Revert
    }
  };

  const presentCount = Object.values(attendanceMap).filter(Boolean).length;
  const totalCount = roster.length;

  return (
    <div className="fixed inset-0 bg-black text-white flex flex-col font-sans overflow-hidden select-none">
      <style>{`
        #qr-reader video { width: 100% !important; height: 100% !important; object-fit: cover !important; }
        #qr-reader { width: 100% !important; height: 100% !important; }
        .p-slider {
          -webkit-appearance: none; width: 100%; height: 12px;
          background: rgba(255,255,255,0.15); border-radius: 10px; outline: none;
        }
        .p-slider::-webkit-slider-thumb {
          -webkit-appearance: none; width: 50px; height: 50px;
          background: #3b82f6; border: 5px solid #fff; border-radius: 50%;
          cursor: pointer; box-shadow: 0 0 20px rgba(59, 130, 246, 0.5);
        }
      `}</style>

      {/* Toasts */}
      <div className="fixed top-20 left-4 z-50 flex flex-col gap-2 pointer-events-none">
        {toasts.map(t => (
          <div key={t.id} className={`backdrop-blur-md border-l-4 p-3 rounded-r-xl shadow-2xl ${t.ok ? 'bg-gray-900/90 border-green-500' : 'bg-gray-900/90 border-red-500'}`}>
            <div className="text-sm font-black text-white truncate max-w-[220px]">{t.name}</div>
          </div>
        ))}
      </div>

      {/* Header */}
      <div className="p-4 bg-gray-900 border-b border-gray-800 flex justify-between items-center z-20 shrink-0">
        <div>
          <h2 className="font-bold text-base leading-tight">{session.topic || 'Attendance Session'}</h2>
          <p className="text-[10px] text-blue-400 uppercase font-bold tracking-widest">
            {session.lecture_type || 'Theory'} · {session.date}
          </p>
        </div>
        <div className="flex items-center gap-3">
          <div className="text-center">
            <div className="bg-blue-600 px-3 py-1 rounded-xl border border-blue-400">
              <span className="font-black text-xl">{presentCount}</span>
              <span className="text-blue-300 text-xs">/{totalCount}</span>
            </div>
            <p className="text-[9px] text-gray-500 mt-0.5 uppercase tracking-wider">Present</p>
          </div>
          <button onClick={onFinish} className="bg-gray-800 text-gray-300 hover:text-white px-3 py-2 rounded-xl text-xs font-bold border border-gray-700">
            Done
          </button>
        </div>
      </div>

      {/* Tab Bar */}
      <div className="flex bg-gray-950 border-b border-gray-800 shrink-0">
        <button onClick={() => setActiveTab('scanner')}
          className={`flex-1 py-3 text-xs font-black uppercase tracking-widest flex items-center justify-center gap-2 transition-all ${activeTab === 'scanner' ? 'text-blue-400 border-b-2 border-blue-500' : 'text-gray-600'}`}>
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 3.5V16M3 3l18 18" />
          </svg>
          QR Scanner
        </button>
        <button onClick={() => setActiveTab('list')}
          className={`flex-1 py-3 text-xs font-black uppercase tracking-widest flex items-center justify-center gap-2 transition-all ${activeTab === 'list' ? 'text-blue-400 border-b-2 border-blue-500' : 'text-gray-600'}`}>
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} 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>
          Student List
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-hidden flex flex-col">
        {/* ── SCANNER TAB ── */}
        {activeTab === 'scanner' && (
          <div className="flex-1 relative bg-black overflow-hidden flex flex-col items-center">
            
            {/* Always render the qr-reader so the library can find it */}
            <div className="w-full relative flex-1 flex flex-col items-center justify-center bg-black">
              <div id="qr-reader" className="w-full h-full"></div>

              {/* Controls - Only show if no error */}
              {!error && (
                <>
                  <div className="absolute bottom-8 left-0 right-0 px-8 z-30 flex flex-col items-center gap-6">
                    {canZoom && (
                      <div className="w-full flex flex-col items-center gap-3">
                        <div className="flex justify-between w-full px-2 text-[10px] font-black text-white/40 uppercase">
                          <span>1X</span>
                          <span className="text-blue-400 font-mono text-sm">{zoom.toFixed(1)}X</span>
                          <span>{maxZoom.toFixed(1)}X</span>
                        </div>
                        <input type="range" min="1" max={maxZoom} step="0.1" value={zoom} onChange={handleZoomChange} className="p-slider" />
                      </div>
                    )}
                    <div className="flex gap-10 items-center">
                      {canTorch && (
                        <button onClick={toggleTorch} className={`p-4 rounded-full border transition-all ${torch ? 'bg-yellow-500 text-black border-yellow-400' : 'bg-white/10 text-white border-white/20'}`}>
                          <svg className="w-6 h-6" fill={torch ? 'currentColor' : 'none'} stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14H11V21L20 10H13Z" />
                          </svg>
                        </button>
                      )}
                      {cameras.length > 1 && (
                        <button onClick={switchCamera} className="bg-white/10 p-4 rounded-full text-white border border-white/20">
                          <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                          </svg>
                        </button>
                      )}
                    </div>
                  </div>

                  {/* Corner viewfinder */}
                  <div className="absolute inset-0 pointer-events-none flex items-center justify-center p-8 z-20">
                    <div className="w-full h-[55vh] border-2 border-white/5 rounded-[50px] relative">
                      <div className="absolute -top-1 -left-1 w-20 h-20 border-t-[6px] border-l-[6px] border-green-500 rounded-tl-[50px]"></div>
                      <div className="absolute -top-1 -right-1 w-20 h-20 border-t-[6px] border-r-[6px] border-green-500 rounded-tr-[50px]"></div>
                      <div className="absolute -bottom-1 -left-1 w-20 h-20 border-b-[6px] border-l-[6px] border-green-500 rounded-bl-[50px]"></div>
                      <div className="absolute -bottom-1 -right-1 w-20 h-20 border-b-[6px] border-r-[6px] border-green-500 rounded-br-[50px]"></div>
                      <div className="w-full h-1 bg-green-500/20 absolute top-1/2 left-0 -translate-y-1/2 shadow-[0_0_30px_rgba(34,197,94,1)]"></div>
                    </div>
                  </div>
                </>
              )}
            </div>

            {/* Error Overlay */}
            {error && (
              <div className="absolute inset-0 flex flex-col items-center justify-center p-10 text-center gap-4 bg-black/90 z-50 backdrop-blur-sm">
                <div className="text-4xl">⚠️</div>
                <div className="text-yellow-500 font-bold uppercase">Camera Error</div>
                <div className="text-xs text-gray-500 font-mono mt-2 px-4 whitespace-pre-wrap break-all">{error}</div>
                <button onClick={() => { setError(null); setRetryCount(p => p + 1); }} className="bg-white text-black py-3 px-6 mt-4 rounded-xl font-bold shadow-xl active:scale-95 transition-transform">
                  Retry
                </button>
              </div>
            )}
          </div>
        )}

        {/* ── STUDENT LIST TAB ── */}
        {activeTab === 'list' && (
          <div className="flex-1 overflow-y-auto bg-gray-950">
            {/* Progress bar */}
            <div className="sticky top-0 z-10 bg-gray-950 border-b border-gray-800 px-4 py-2">
              <div className="flex justify-between text-[10px] font-black text-gray-500 uppercase mb-1.5">
                <span>Attendance Progress</span>
                <span className="text-blue-400">{presentCount} / {totalCount}</span>
              </div>
              <div className="h-1.5 bg-gray-800 rounded-full overflow-hidden">
                <div
                  className="h-full bg-green-500 rounded-full transition-all duration-300"
                  style={{ width: totalCount > 0 ? `${(presentCount / totalCount) * 100}%` : '0%' }}>
                </div>
              </div>
            </div>

            {roster.length === 0 ? (
              <div className="p-10 text-center text-gray-600 italic text-sm">No students found</div>
            ) : (
              <div className="divide-y divide-gray-800/60">
                {roster.map((student, idx) => {
                  const isPresent = !!attendanceMap[student.enrollment_no];
                  return (
                    <div key={student.id || student.enrollment_no}
                      className={`flex items-center gap-4 px-4 py-3 transition-colors ${isPresent ? 'bg-green-950/30' : ''}`}>
                      {/* Row number */}
                      <span className="text-gray-600 text-xs font-bold w-5 shrink-0 text-right">{idx + 1}</span>
                      {/* Student info */}
                      <div className="flex-1 min-w-0">
                        <div className="text-white font-bold text-sm truncate leading-tight">{student.full_name}</div>
                        <div className="flex gap-2 mt-0.5">
                          <span className="text-[10px] text-gray-500 font-mono">Roll: {student.roll_no}</span>
                          <span className="text-gray-700">·</span>
                          <span className="text-[10px] text-gray-500 font-mono">{student.enrollment_no}</span>
                        </div>
                      </div>
                      {/* Toggle */}
                      <button
                        onClick={() => handleManualToggle(student, !isPresent)}
                        className={`shrink-0 w-14 h-8 rounded-full border-2 flex items-center transition-all duration-200 ${isPresent ? 'bg-green-500 border-green-400 justify-end' : 'bg-gray-800 border-gray-700 justify-start'}`}>
                        <span className={`w-6 h-6 rounded-full mx-0.5 flex items-center justify-center shadow-md transition-all ${isPresent ? 'bg-white text-green-600' : 'bg-gray-600 text-gray-400'}`}>
                          {isPresent ? (
                            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                            </svg>
                          ) : (
                            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M6 18L18 6M6 6l12 12" />
                            </svg>
                          )}
                        </span>
                      </button>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

window.ScannerView = ScannerView;
