// import AppDevice from '../components/dashboard/AppDevice';
import { useEffect, useState } from 'react';
import { Container, Spinner, Alert, Row, Col } from 'react-bootstrap';
import { fetchActiveDevices, fetchMetricsData } from '../services/api';
import MetricsTable from '../components/dashboard/MetricsTable';
import AppDevice from '../components/dashboard/AppDevice';


function DevicesPage({theme}) {

  const [metrics, setMetrics] = useState([]);
  const [devices, setDevices] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const loadData = async () => {
      try {
        const [metricsData, activeDevices] = await Promise.all([
          fetchMetricsData(),
          fetchActiveDevices()
        ]);

        setDevices(activeDevices);
        setMetrics(metricsData);
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

  if (loading) {
    return (
      <Container fluid className="text-center mt-5">
        <Spinner animation="border" variant="danger"/>
      </Container>
    );
  }

  if (error) {
    return (
      <Container className="mt-5">
        <Alert variant="danger">Error: {error}</Alert>
      </Container>
    );
  }

  return (
    <Container fluid className={`device-page flex {$theme}`} style={{ fontFamily: 'Poppins, sans-serif'}}>
        <Col className="p-3 ms-auto">
          <h4 className='my-3'>Devices Page</h4>
          <AppDevice devices={devices} theme={theme}/>
          <MetricsTable metrics={metrics} theme={theme}/>
        </Col>
    </Container>
  );
}

export default DevicesPage;