import React, { useEffect, useState, useRef, useCallback } from 'react';
import { StudentStreamImage } from './StudentStreamImage';

interface ProctorStreamPanelsProps {
  studentId: number;
  layout?: 'default' | 'focus';
}

const ZOOM_STEPS = [0.5, 0.75, 1, 1.25, 1.5, 2, 2.5, 3];

export const ProctorStreamPanels: React.FC<ProctorStreamPanelsProps> = ({
  studentId,
  layout = 'focus',
}) => {
  const [showWebcam, setShowWebcam] = useState(true);
  const [screenZoomIdx, setScreenZoomIdx] = useState(2); // 1x
  const [webcamZoomIdx, setWebcamZoomIdx] = useState(2);
  const [isFullscreen, setIsFullscreen] = useState(false);

  const screenPanelRef = useRef<HTMLDivElement>(null);

  const screenZoom = ZOOM_STEPS[screenZoomIdx];
  const webcamZoom = ZOOM_STEPS[webcamZoomIdx];

  useEffect(() => {
    const onFsChange = () => {
      setIsFullscreen(document.fullscreenElement === screenPanelRef.current);
    };
    document.addEventListener('fullscreenchange', onFsChange);
    return () => document.removeEventListener('fullscreenchange', onFsChange);
  }, []);

  const toggleFullscreen = useCallback(async () => {
    const el = screenPanelRef.current;
    if (!el) return;
    try {
      if (document.fullscreenElement === el) {
        await document.exitFullscreen();
      } else {
        await el.requestFullscreen();
      }
    } catch (e) {
      console.error('Fullscreen error', e);
    }
  }, []);

  const zoomIn = (target: 'screen' | 'webcam') => {
    const setter = target === 'screen' ? setScreenZoomIdx : setWebcamZoomIdx;
    setter(i => Math.min(i + 1, ZOOM_STEPS.length - 1));
  };

  const zoomOut = (target: 'screen' | 'webcam') => {
    const setter = target === 'screen' ? setScreenZoomIdx : setWebcamZoomIdx;
    setter(i => Math.max(i - 1, 0));
  };

  const zoomReset = (target: 'screen' | 'webcam') => {
    if (target === 'screen') setScreenZoomIdx(2);
    else setWebcamZoomIdx(2);
  };

  const renderZoomToolbar = (target: 'screen' | 'webcam', zoom: number, onFs?: () => void) => (
    <div className="panel-toolbar">
      <button type="button" className="proctor-tool-btn" title="Thu nhỏ" onClick={() => zoomOut(target)}>−</button>
      <span className="proctor-zoom-label">{Math.round(zoom * 100)}%</span>
      <button type="button" className="proctor-tool-btn" title="Phóng to" onClick={() => zoomIn(target)}>+</button>
      <button type="button" className="proctor-tool-btn" title="Về 100%" onClick={() => zoomReset(target)}>1:1</button>
      {onFs && (
        <button type="button" className="proctor-tool-btn proctor-tool-btn-wide" title="Toàn màn hình" onClick={onFs}>
          {isFullscreen ? 'Thu nhỏ' : 'Phóng to'}
        </button>
      )}
    </div>
  );

  return (
    <div className="proctor-stream-wrap">
      <div className="proctor-stream-toolbar">
        <span className="status-pill connected">
          ● Đang phát (HTTP)
        </span>
        <div className="proctor-stream-actions">
          <button
            type="button"
            className={`btn btn-secondary proctor-action-btn ${showWebcam ? '' : 'active'}`}
            onClick={() => setShowWebcam(v => !v)}
          >
            {showWebcam ? 'Ẩn webcam' : 'Hiện webcam'}
          </button>
        </div>
      </div>

      <div className={`proctor-grid proctor-grid-${layout} ${!showWebcam ? 'proctor-grid--no-webcam' : ''}`}>
        <div
          className={`proctor-panel screen-panel ${isFullscreen ? 'screen-panel--fullscreen' : ''}`}
          ref={screenPanelRef}
        >
          <div className="panel-title-row">
            <span className="panel-title-text">Màn hình sinh viên</span>
            {renderZoomToolbar('screen', screenZoom, toggleFullscreen)}
          </div>
          <div className="panel-body screen-body" onDoubleClick={toggleFullscreen} title="Double-click để phóng to">
            <div className="proctor-zoom-viewport">
              <StudentStreamImage
                studentId={studentId}
                kind="screen"
                className="live-frame screen-img"
                style={{ transform: `scale(${screenZoom})` }}
              />
            </div>
          </div>
        </div>

        {showWebcam && (
          <div className="proctor-panel webcam-panel">
            <div className="panel-title-row">
              <span className="panel-title-text">Webcam</span>
              {renderZoomToolbar('webcam', webcamZoom)}
            </div>
            <div className="panel-body webcam-body">
              <div className="proctor-zoom-viewport proctor-zoom-viewport--webcam">
                <StudentStreamImage
                  studentId={studentId}
                  kind="webcam"
                  className="live-frame webcam-img"
                  style={{ transform: `scale(${webcamZoom})` }}
                />
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
