import React, { useMemo } from 'react';
import { useOutletContext } from 'react-router-dom';
import {
  MaterialReactTable,
  useMaterialReactTable,
  type MRT_ColumnDef,
} from 'material-react-table';
import type { Guest } from '../models';
import { Button, createTheme, ThemeProvider, useTheme } from '@mui/material';
import { mkConfig, generateCsv, download } from 'export-to-csv';

function Dashboard() {
  const tableTheme = createTheme({
    ...useTheme(),
    typography: {
      fontFamily: ['Roboto', 'sans-serif'].join(','),
    },
  });

  const guests: Guest[] = useOutletContext();
  const columns = useMemo<MRT_ColumnDef<Guest>[]>(
    () => [
      {
        accessorKey: 'firstName',
        header: 'First Name',
        size: 50,
      },
      {
        accessorKey: 'lastName',
        header: 'Last Name',
        size: 50,
      },
      {
        accessorKey: 'attendance',
        header: 'Attendance',
        size: 50,
      },
      {
        accessorKey: 'email',
        header: 'Email',
        size: 150,
      },
      {
        accessorKey: 'message',
        header: 'Message',
        size: 200,
      },
      {
        accessorKey: 'partySize',
        header: 'Party Size',
        size: 50,
      },
    ],
    []
  );

  const csvConfig = mkConfig({
    fieldSeparator: ',',
    decimalSeparator: '.',
    useKeysAsHeaders: true,
  });

  const handleExportData = () => {
    let data = guests.map(({ id, partyList, ...guest }) => guest);
    guests.forEach((guest) => {
      const { attendance, partySize } = guest;
      guest?.partyList?.forEach((partyGuest) =>
        data.push({ ...partyGuest, attendance, partySize })
      );
    });
    download(csvConfig)(generateCsv(csvConfig)(data));
  };

  const table = useMaterialReactTable({
    columns,
    data: guests,
    renderTopToolbarCustomActions: () => (
      <div style={{ marginLeft: 'auto' }}>
        <Button variant="outlined" size="small" onClick={handleExportData}>
          Export
        </Button>
      </div>
    ),
    muiPaginationProps: {
      color: 'primary',
      shape: 'rounded',
      showRowsPerPage: false,
      variant: 'outlined',
    },
    paginationDisplayMode: 'pages',
    enableExpanding: true,
    filterFromLeafRows: true,
    paginateExpandedRows: false,
    getSubRows: (row) => row.partyList as Guest[],
  });

  return (
    <div
      style={{
        display: 'flex',
        justifyContent: 'center',
      }}
    >
      <div style={{ marginTop: 128, width: '90%' }}>
        <ThemeProvider theme={tableTheme}>
          <MaterialReactTable table={table} />
        </ThemeProvider>
      </div>
    </div>
  );
}

export default Dashboard;
