import { useEffect, useRef, useState } from 'react';
import './WebcamRecorder.css';

export default function WebcamRecorder({ onRecordingComplete, onRecordingStart, onRecordingStop, onReRecord, onDiscard }) {
  const videoRef = useRef(null);
  const previewRef = useRef(null);
  const mediaRecorderRef = useRef(null);
  const chunksRef = useRef([]);
  const [stream, setStream] = useState(null);
  const [isRecording, setIsRecording] = useState(false);
  const [recordedBlob, setRecordedBlob] = useState(null);
  const [previewUrl, setPreviewUrl] = useState(null);
  const [error, setError] = useState(null);
  const [recordingTime, setRecordingTime] = useState(0);
  const timerRef = useRef(null);

  useEffect(() => {
    startWebcam();
    return () => {
      stopWebcam();
      if (timerRef.current) {
        clearInterval(timerRef.current);
      }
    };
  }, []);

  const startWebcam = async () => {
    try {
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { width: 640, height: 480 },
        audio: true
      });
      setStream(mediaStream);
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream;
      }
      setError(null);
    } catch (err) {
      console.error('Error accessing webcam:', err);
      setError('Unable to access webcam. Please ensure camera permissions are granted.');
    }
  };

  const stopWebcam = () => {
    if (stream) {
      stream.getTracks().forEach(track => track.stop());
      setStream(null);
    }
  };

  const startRecording = () => {
    if (!stream) {
      setError('No webcam stream available');
      return;
    }

    chunksRef.current = [];
    setRecordedBlob(null);
    setRecordingTime(0);

    // Use webm format for recording (better browser support)
    const mimeType = MediaRecorder.isTypeSupported('video/webm;codecs=vp9')
      ? 'video/webm;codecs=vp9'
      : 'video/webm';

    try {
      const mediaRecorder = new MediaRecorder(stream, { mimeType });

      mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          chunksRef.current.push(event.data);
        }
      };

      mediaRecorder.onstop = () => {
        const blob = new Blob(chunksRef.current, { type: 'video/webm' });
        setRecordedBlob(blob);
        // Create preview URL
        const url = URL.createObjectURL(blob);
        setPreviewUrl(url);
        if (onRecordingComplete) {
          onRecordingComplete(blob);
        }
      };

      mediaRecorder.start(1000); // Collect data every second
      mediaRecorderRef.current = mediaRecorder;
      setIsRecording(true);

      // Notify parent that recording started
      if (onRecordingStart) {
        onRecordingStart();
      }

      // Start timer
      timerRef.current = setInterval(() => {
        setRecordingTime(prev => prev + 1);
      }, 1000);

    } catch (err) {
      console.error('Error starting recording:', err);
      setError('Failed to start recording');
    }
  };

  const stopRecording = () => {
    if (mediaRecorderRef.current && isRecording) {
      mediaRecorderRef.current.stop();
      setIsRecording(false);

      // Notify parent that recording stopped
      if (onRecordingStop) {
        onRecordingStop();
      }

      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    }
  };

  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  const discardRecording = (skipCallback = false) => {
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
      setPreviewUrl(null);
    }
    setRecordedBlob(null);
    setRecordingTime(0);
    if (onRecordingComplete) {
      onRecordingComplete(null);
    }
    if (!skipCallback && onDiscard) {
      onDiscard();
    }
  };

  return (
    <div className="webcam-recorder">
      <h2 className="webcam-title">Record Your Interpretation</h2>

      {error && <p className="webcam-error">{error}</p>}

      <div className="webcam-preview">
        {/* Live webcam feed - hidden when showing preview */}
        <video
          ref={videoRef}
          autoPlay
          muted
          playsInline
          className="webcam-video"
          style={{ display: previewUrl && !isRecording ? 'none' : 'block' }}
        />
        {/* Preview of recorded video */}
        {previewUrl && !isRecording && (
          <video
            ref={previewRef}
            src={previewUrl}
            controls
            playsInline
            className="webcam-video preview-video"
          />
        )}
        {isRecording && (
          <div className="recording-indicator">
            <span className="recording-dot"></span>
            <span className="recording-time">{formatTime(recordingTime)}</span>
          </div>
        )}
      </div>

      <div className="webcam-controls">
        {!isRecording && !recordedBlob && (
          <button
            className="webcam-btn record-btn"
            onClick={startRecording}
            disabled={!stream}
          >
            ⏺ Start Recording
          </button>
        )}

        {isRecording && (
          <button
            className="webcam-btn stop-btn"
            onClick={stopRecording}
          >
            ⏹ Stop Recording
          </button>
        )}

        {recordedBlob && !isRecording && (
          <div className="recording-actions">
            <p className="recording-ready">Review your recording ({formatTime(recordingTime)})</p>
            <div className="recording-buttons">
              <button
                className="webcam-btn discard-btn"
                onClick={() => discardRecording(false)}
              >
                🗑 Discard
              </button>
              <button
                className="webcam-btn rerecord-btn"
                onClick={() => {
                  discardRecording(true); // Skip discard callback, use rerecord instead
                  if (onReRecord) {
                    onReRecord();
                  }
                  startRecording();
                }}
              >
                🔄 Re-record
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
