import { AppShellWithMenu } from '../FitzStudio/Appshell/Appshell';
import { Card, Grid, Title, Loader } from '@mantine/core';
import { useEffect, useState } from 'react';
import ReactECharts from 'echarts-for-react';

type ChartOption = any;

function useChartOption(endpoint: string) {
  const [option, setOption] = useState<ChartOption | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/v1/charts/${endpoint}`)
      .then((res) => res.json())
      .then((json) => setOption(json))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [endpoint]);

  return { option, loading };
}

export function VisualizacionesRandom() {
  const charts = [
    { title: 'Gráfico de barras', endpoint: 'bar' },
    { title: 'Gráfico de líneas', endpoint: 'line' },
    { title: 'Gráfico de pastel', endpoint: 'pie' },
    { title: 'Scatter plot', endpoint: 'scatter' },
  ];

  return (
    <AppShellWithMenu>
      <Grid>
        {charts.map(({ title, endpoint }, idx) => {
          const { option, loading } = useChartOption(endpoint);

          return (
            <Grid.Col span={{ base: 12, sm: 6, md: 6, lg: 3 }} key={idx}>
              <Card shadow="sm" padding="lg" radius="md" withBorder>
                <Title order={4}>{title}</Title>
                {loading || !option ? (
                  <Loader mt="md" />
                ) : (
                  <ReactECharts option={option} style={{ height: 250, marginTop: 16 }} />
                )}
              </Card>
            </Grid.Col>
          );
        })}
      </Grid>
    </AppShellWithMenu>
  );
}
