import React, { useEffect, useState } from 'react';
import axios from 'axios';
import './admin.css';

const RecordingsPage = () => {
  const [recordings, setRecordings] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const BACKEND_API_URL = process.env.REACT_APP_BACKEND_API_URL || 'http://localhost:5000';

  const fetchRecordings = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await axios.get(`${BACKEND_API_URL}/api/admin/recordings`);
      setRecordings(response.data);
    } catch (err) {
      console.error('Error fetching recordings:', err);
      setError('Failed to fetch recordings. Is backend running? ' + (err.response?.data?.msg || err.message));
    } finally {
      setLoading(false);
    }
  };

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

  // Handle Delete Recording
  const handleDeleteRecording = async (recordingId) => {
    if (window.confirm('Are you sure you want to delete this recording? This will also attempt to delete the file from S3!')) {
      setError(null);
      try {
        await axios.delete(`${BACKEND_API_URL}/api/admin/recordings/${recordingId}`);
        alert('Recording deleted successfully!');
        fetchRecordings(); // Refresh recording list
      } catch (err) {
        console.error('Error deleting recording:', err);
        setError('Failed to delete recording: ' + (err.response?.data?.msg || err.message));
      }
    }
  };

  if (loading) return <div className="loading">Loading recordings...</div>;
  if (error) return <div className="error">{error}</div>;

  return (
    <div className="admin-page">
      <h2>Recording Management</h2>
      <table className="admin-table">
        <thead>
          <tr>
            <th>Room Name</th>
            <th>Filename</th>
            <th>Duration (s)</th>
            <th>Status</th>
            <th>Started At</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          {recordings.map(rec => (
            <tr key={rec._id}>
              <td>{rec.roomName}</td>
              <td>{rec.filename}</td>
              <td>{rec.duration || 'N/A'}</td>
              <td>{rec.status}</td>
              <td>{new Date(rec.startedAt).toLocaleDateString()}</td>
              <td>
                {rec.s3Url && (
                  <a href={rec.s3Url} target="_blank" rel="noopener noreferrer" className="action-button view-button">View</a>
                )}
                <button className="action-button delete-button" onClick={() => handleDeleteRecording(rec._id)}>Delete</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default RecordingsPage;