import { useMemo } from 'react';
import { MaterialReactTable, MRT_ColumnDef, MRT_Row, useMaterialReactTable } from 'material-react-table';
import mockData from '../data/mockData';
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,
  }) ?? '';
}

const statusColor: Record<string, string> = {
  'Завершена': '#4caf50',
  'Ожидается': '#ff9800',
  'Ошибка': '#f44336',
};

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

export default function BillingPayoutsTable() {
  const columns = useMemo<MRT_ColumnDef<any>[]>(
    () => [
      { accessorKey: 'id', header: 'ID' },
      { accessorKey: 'amount', header: 'Сумма',
        Cell: ({ cell }) => formatCurrency(cell.getValue() as number) },
      { accessorKey: 'date', header: 'Дата' },
      { accessorKey: 'status', header: 'Статус',
        Cell: ({ cell }) => (
          <span style={{ color: statusColor[cell.getValue() as string] || '#333', fontWeight: 600 }}>
            {cell.getValue() as string}
          </span>
        )
      },
      { accessorKey: 'method', header: 'Способ' },
    ],
    []
  );

  const table = useMaterialReactTable({
    columns,
    data: mockData.payouts,
    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)(mockData.payouts);
    download(csvConfig)(csv);
  };

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