'use client';

import { useMemo, useState, useEffect } from 'react';
import { SearchBar } from './SearchBar';
import Box from '@mui/material/Box';

import Alert from '@mui/material/Alert';

import Paper from '@mui/material/Paper';
import {
  DataGridPremium,
  GridCellSelectionModel,
} from '@mui/x-data-grid-premium';
import { useOrders } from '../hooks/useOrders';
import { useStores } from '../store/useStores';
import { createOrderColumns } from './OrderTableColumns';
import { calculateTableHeight } from '../utils/tableHelpers';
import { normalizeOrder } from '../utils/orderNormalizer';
import { Order } from '../types';
import { OrderDetailsTabs } from './OrderDetailsTabs';

export const OrderTable = () => {
  const { data: orders, isLoading, error } = useOrders();
  const { data: stores } = useStores();
  const [cellSelectionModel, setCellSelectionModel] =
    useState<GridCellSelectionModel>({});
  const [selectedOrderId, setSelectedOrderId] = useState<number | null>(null);

  useEffect(() => {
    if (!orders || orders.length === 0) {
      setSelectedOrderId(null);
      return;
    }
    
    setSelectedOrderId((current) => {
      if (!current) return null;
      const exists = orders.some((order: Order) => order.orderId === current);
      return exists ? current : null;
    });
  }, [orders]);

  // Cria mapa de storeId -> storeName
  const storesMap = useMemo(() => {
    if (!stores) return new Map<string, string>();
    return new Map(
      stores.map((store) => [String(store.id), store.store || store.name || String(store.id)])
    );
  }, [stores]);

  const rows = useMemo(() => {
    if (!Array.isArray(orders) || orders.length === 0) return [];

    return orders.map((order: Order, index: number) =>
      normalizeOrder(order, index)
    );
  }, [orders]);

  const columns = useMemo(() => createOrderColumns({ storesMap }), [storesMap]);

  if (error) {
    return (
      <Box sx={{ mt: 2 }}>
        <Alert severity="error">
          {error instanceof Error
            ? `Erro ao carregar pedidos: ${error.message}`
            : 'Erro ao carregar pedidos. Verifique os filtros e tente novamente.'}
        </Alert>
      </Box>
    );
  }

  const tableHeight = calculateTableHeight(rows.length, 10);

  const mobileTableHeight = calculateTableHeight(rows.length, 5, {
    minHeight: 300,
    rowHeight: 40,
  });

  return (
    <Box>
      <SearchBar />

      <Paper
        sx={{
          mt: { xs: 2, md: 3 },
          boxShadow: 'none',
          border: 'none',
          backgroundColor: 'transparent',
          overflow: 'hidden',
        }}
      >
        <DataGridPremium
          rows={rows}
          columns={columns}
          loading={isLoading}
          density="compact"
          autoHeight={false}
          onRowClick={(params) => {
            const orderId = params.row.orderId;
            setSelectedOrderId(orderId === selectedOrderId ? null : orderId);
          }}
          initialState={{
            pagination: {
              paginationModel: {
                pageSize: 10,
                page: 0,
              },
            },
            sorting: {
              sortModel: [{ field: 'createDate', sort: 'desc' }],
            },
            pinnedColumns: {
            ///  left: ['orderId', 'customerName'],
            },
          }}
          pageSizeOptions={[10, 25, 50]}
          paginationMode="client"
          pagination
          cellSelection
          cellSelectionModel={cellSelectionModel}
          onCellSelectionModelChange={(newModel) => {
            setCellSelectionModel(newModel);
          }}
          getRowClassName={(params) =>
            params.row.orderId === selectedOrderId ? 'Mui-selected' : ''
          }
          sx={{
            height: { xs: mobileTableHeight, md: tableHeight },
            border: '1px solid',
            borderColor: 'divider',
            fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
            backgroundColor: 'background.paper',
            '& .MuiDataGrid-root': {
              fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
              border: 'none',
            },
            '& .MuiDataGrid-columnHeaders': {
              backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'grey.900' : 'grey.50',
              fontWeight: 600,
              fontSize: '0.75rem',
              borderBottom: '2px solid',
              borderColor: 'divider',
              fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
              minHeight: '40px !important',
              maxHeight: '40px !important',
            },
            '& .MuiDataGrid-columnHeader': {
              borderRight: '1px solid',
              borderColor: 'divider',
              paddingLeft: '12px',
              paddingRight: '12px',
              '&:focus': {
                outline: 'none',
              },
              '&:focus-within': {
                outline: 'none',
              },
              '&:last-of-type': {
                borderRight: 'none',
              },
            },
            '& .MuiDataGrid-row': {
              borderBottom: '1px solid',
              borderColor: 'divider',
              backgroundColor: 'background.paper',
              minHeight: '36px !important',
              maxHeight: '36px !important',
              cursor: 'pointer',
              '&:hover': {
                backgroundColor: 'action.hover',
              },
              '&:last-child': {
                borderBottom: 'none',
              },
            },
            '& .MuiDataGrid-row.Mui-selected': {
              backgroundColor: 'primary.light',
              '&:hover': {
                backgroundColor: 'primary.light',
              },
            },
            '& .MuiDataGrid-row:nth-of-type(even)': {
              backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'grey.800' : 'grey.50',
              '&:hover': {
                backgroundColor: 'action.hover',
              },
            },
            '& .MuiDataGrid-cell': {
              borderRight: '1px solid',
              borderColor: 'divider',
              borderBottom: 'none',
              paddingLeft: '12px',
              paddingRight: '12px',
              fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
              fontSize: '0.75rem',
              lineHeight: 1.2,
              cursor: 'cell',
              '&:focus': {
                outline: '2px solid',
                outlineColor: 'primary.main',
                outlineOffset: '-2px',
              },
              '&:focus-within': {
                outline: '2px solid',
                outlineColor: 'primary.main',
                outlineOffset: '-2px',
              },
              '&.Mui-selected': {
                backgroundColor: 'primary.light',
                color: 'primary.contrastText',
                fontWeight: 500,
                '&:focus': {
                  backgroundColor: 'primary.main',
                  outline: '2px solid',
                  outlineColor: 'primary.dark',
                  outlineOffset: '-2px',
                },
              },
              '&:last-of-type': {
                borderRight: 'none',
              },
            },
            '& .MuiDataGrid-footerContainer': {
              borderTop: '2px solid',
              borderColor: 'divider',
              fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
              minHeight: '48px !important',
              fontSize: '0.75rem',
              backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'grey.900' : 'grey.50',
            },
            '& .MuiDataGrid-aggregationColumnHeader': {
              backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'grey.800' : 'grey.100',
              fontWeight: 600,
              fontSize: '0.75rem',
              borderBottom: '2px solid',
              borderColor: 'divider',
            },
            '& .MuiDataGrid-aggregationColumnHeaderLabel': {
              fontWeight: 600,
            },
            '& .MuiDataGrid-aggregationRow': {
              backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'grey.800' : 'grey.100',
              borderTop: '2px solid',
              borderColor: 'divider',
              minHeight: '40px !important',
              maxHeight: '40px !important',
            },
            '& .MuiDataGrid-aggregationCell': {
              borderRight: '1px solid',
              borderColor: 'divider',
              paddingLeft: '12px',
              paddingRight: '12px',
              fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
              fontSize: '0.75rem',
              fontWeight: 600,
              '&:last-of-type': {
                borderRight: 'none',
              },
            },
            '& .MuiDataGrid-toolbarContainer': {
              fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
            },
            '& .MuiDataGrid-iconButtonContainer': {
              visibility: 'visible',
            },
            '& .MuiDataGrid-sortIcon': {
              opacity: 1,
            },
            '& .MuiDataGrid-pinnedColumnHeaders': {
              backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'grey.900' : 'grey.50',
            },
            '& .MuiDataGrid-pinnedColumns': {
              backgroundColor: 'background.paper',
            },
            '& .MuiDataGrid-pinnedColumnHeader': {
              backgroundColor: (theme) => theme.palette.mode === 'dark' ? 'grey.900' : 'grey.50',
              fontWeight: 600,
              fontSize: '0.75rem',
              borderBottom: '2px solid',
              borderColor: 'divider',
            },
            '& .MuiDataGrid-pinnedColumn': {
              backgroundColor: 'background.paper',
            },
            '& .MuiDataGrid-pinnedColumn--left': {
              boxShadow: '2px 0px 4px rgba(0, 0, 0, 0.08)',
            },
            '& .MuiDataGrid-pinnedColumn--right': {
              boxShadow: '-2px 0px 4px rgba(0, 0, 0, 0.08)',
            },
          }}
          localeText={{
            noRowsLabel:
              'Nenhum pedido encontrado para os filtros selecionados.',
            noResultsOverlayLabel: 'Nenhum resultado encontrado.',
            footerTotalRows: 'Total de registros:',
            footerTotalVisibleRows: (visibleCount, totalCount) =>
              `${visibleCount.toLocaleString()} de ${totalCount.toLocaleString()}`,
            footerRowSelected: (count) =>
              count === 1
                ? `${count.toLocaleString()} linha selecionada`
                : `${count.toLocaleString()} linhas selecionadas`,
          }}
          slotProps={{
            pagination: {
              labelRowsPerPage: 'Pedidos por página:',
              labelDisplayedRows: ({
                from,
                to,
                count,
              }: {
                from: number;
                to: number;
                count: number;
              }) => {
                const pageSize = to >= from ? to - from + 1 : 10;
                const currentPage = Math.floor((from - 1) / pageSize) + 1;
                const totalPages = Math.ceil(count / pageSize);
                return `${from}–${to} de ${count} | Página ${currentPage} de ${totalPages}`;
              },
            },
          }}
        />
      </Paper>

      {selectedOrderId && <OrderDetailsTabs orderId={selectedOrderId} />}
    </Box>
  );
};
