import * as React from "react";
import {
  Box,
  Container,
  Grid,
  ToggleButton,
  ToggleButtonGroup,
  Button
} from "@mui/material";
import { useTheme, alpha } from "@mui/material/styles";
import { DashboardViewProps } from "./Dashboard.models";

export default function DashboardView({
  config,
  data,
  state,
  stateSetters,
  isFetching,
}: DashboardViewProps) {
  const theme = useTheme();

  const {
    flow,
    selectedGroupKey,
  } = state;

  const colorScheme = flow === "outflows" ? theme.palette.flows.outflows : theme.palette.flows.inflows;

  return (
    <Container
      sx={{
        mt: 4,
        mb: 4,
        background: `linear-gradient(180deg, ${alpha(colorScheme.primary, theme.palette.mode === "dark" ? 0.06 : 0.04)} 0%, transparent 100%)`,
        borderRadius: 4,
        p: 2,
        transition: "background 0.3s ease",
      }}
    >
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          mb: 3,
        }}
      >
        <ToggleButtonGroup
          value={flow}
          exclusive
          onChange={stateSetters.toggleFlow}
          sx={{
            borderRadius: 3,
            overflow: "hidden",
            "& .MuiToggleButton-root": {
              px: 3,
              textTransform: "none",
              color: "text.secondary",
            },
            "&.Mui-selected": {
              bgcolor: colorScheme.primary,
              color: "white",
              borderColor: colorScheme.primary,
            },
          }}
        >
          <ToggleButton value="outflows">Outflows</ToggleButton>
          <ToggleButton value="inflows">Inflows</ToggleButton>
        </ToggleButtonGroup>

        {selectedGroupKey && Object.keys(selectedGroupKey).length > 0 && (
          <Button
            size="small"
            sx={{ mt: 1, textTransform: "none" }}
            onClick={() => stateSetters.setSelectedGroupKey(null)}
          >
            Clear Drill-down
          </Button>
        )}
      </Box>

      <Grid container spacing={4}>
        {config.sections.map((section) => {
          const Component = section.component;

          return (
            <Grid key={section.id} size={12}>
              <Component
                {...section}

                reportData={data}

                state={state}
                stateSetters={stateSetters}
                isFetching={isFetching}

                colorScheme={colorScheme}
              />
            </Grid>
          );
        })}
      </Grid>
    </Container>
  );
}
