import React, { useState, useEffect } from 'react';
import { API_BASE } from '../api';

interface StudentStreamImageProps {
  studentId: number;
  kind: 'screen' | 'webcam';
  className?: string;
  style?: React.CSSProperties;
}

export const StudentStreamImage: React.FC<StudentStreamImageProps> = ({
  studentId,
  kind,
  className,
  style,
}) => {
  const [url, setUrl] = useState('');
  const [error, setError] = useState(false);

  useEffect(() => {
    const token = localStorage.getItem('sc_staff_token') || '';
    const tokenParam = token ? `?token=${encodeURIComponent(token)}` : '';
    setUrl(`${API_BASE}/students/${studentId}/stream/${kind}${tokenParam}`);
    setError(false);
  }, [studentId, kind]);

  const handleError = () => {
    setError(true);
    setTimeout(() => {
      const token = localStorage.getItem('sc_staff_token') || '';
      const tokenParam = token ? `?token=${encodeURIComponent(token)}` : '';
      setUrl(`${API_BASE}/students/${studentId}/stream/${kind}${tokenParam}&t=${Date.now()}`);
      setError(false);
    }, 2000);
  };

  if (error || !url) {
    return (
      <div className="no-stream-placeholder">
        <p>Đang chờ {kind === 'screen' ? 'màn hình' : 'webcam'}...</p>
      </div>
    );
  }

  return (
    <img
      src={url}
      alt={`${kind === 'screen' ? 'Màn hình' : 'Webcam'} sinh viên`}
      className={className}
      style={style}
      onError={handleError}
      draggable={false}
    />
  );
};
