import { useEffect, useState, useMemo } from 'react';
import { MaterialReactTable, MRT_ColumnDef, MRT_Row, useMaterialReactTable } from 'material-react-table';
import styles from "../styles/stat.module.css";
import { Box, Button } from '@mui/material';
import FileDownloadIcon from '@mui/icons-material/FileDownload';
import { mkConfig, generateCsv, download } from 'export-to-csv';

function formatCurrency(amount: number) {
  return amount?.toLocaleString("ru-RU", {
    style: "currency",
    currency: "RUB",
    minimumFractionDigits: 0,
  }) ?? "";
}

export default function AgentsTable({ filters, reloadKey }: { filters: { dateStart: string, dateEnd: string }, reloadKey: number }) {
  const [data, setData] = useState<any[]>([]);

  useEffect(() => {
    const params = new URLSearchParams();
    if (filters.dateStart) params.append('date_start', filters.dateStart);
    if (filters.dateEnd) params.append('date_end', filters.dateEnd);
    fetch(`/api/stat/agents?${params.toString()}`)
      .then(res => res.json())
      .then(setData)
      .catch(() => setData([]));
  }, [filters.dateStart, filters.dateEnd, reloadKey]);

  const columns = useMemo<MRT_ColumnDef<any>[]>(
    () => [
      { accessorKey: 'name', header: 'Имя' },
      { accessorKey: 'refCount', header: 'Кол-во рефов' },
      { accessorKey: 'salesCount', header: 'Кол-во продаж' },
      { accessorKey: 'salesSum', header: 'Сумма продаж',
        Cell: ({ cell }) => formatCurrency(cell.getValue() as number) },
      { accessorKey: 'crediting', header: 'Начислено',
        Cell: ({ cell }) => formatCurrency(cell.getValue() as number) },
    ],
    []
  );

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

  const table = useMaterialReactTable({
    columns,
    data,
    enableRowSelection: false,
    renderTopToolbarCustomActions: ({ table }) => (
      <Box sx={{ display: 'flex', gap: 2, p: 1, flexWrap: 'wrap' }}>
        <Button onClick={() => handleExportData()} startIcon={<FileDownloadIcon />}>
          Экспорт всех данных
        </Button>
        <Button onClick={() => handleExportRows(table.getPrePaginationRowModel().rows)} startIcon={<FileDownloadIcon />} disabled={table.getPrePaginationRowModel().rows.length === 0}>
          Экспорт всех строк
        </Button>
        <Button onClick={() => handleExportRows(table.getRowModel().rows)} startIcon={<FileDownloadIcon />} disabled={table.getRowModel().rows.length === 0}>
          Экспорт текущей страницы
        </Button>
      </Box>
    ),
    muiTableBodyCellProps: { sx: { fontSize: 14 } },
    muiTableHeadCellProps: { sx: { fontWeight: 700 } },
    initialState: { pagination: { pageSize: 10, pageIndex: 0 } },
  });

  const handleExportRows = (rows: MRT_Row<any>[]) => {
    const rowData = rows.map((row) => row.original);
    const csv = generateCsv(csvConfig)(rowData);
    download(csvConfig)(csv);
  };

  const handleExportData = () => {
    const csv = generateCsv(csvConfig)(data);
    download(csvConfig)(csv);
  };

  return <MaterialReactTable table={table} />;
} 