'use client';

import { useMemo } from 'react';
import Box from '@mui/material/Box';
import CircularProgress from '@mui/material/CircularProgress';
import Alert from '@mui/material/Alert';
import { DataGridPremium } from '@mui/x-data-grid-premium';
import { useCargoMovement } from '../../hooks/useCargoMovement';
import { createCargoMovementColumns } from './CargoMovementPanelColumns';
import { dataGridStylesSimple } from '../../utils/dataGridStyles';

interface CargoMovementPanelProps {
  orderId: number;
}

export const CargoMovementPanel = ({ orderId }: CargoMovementPanelProps) => {
  const { data: movements, isLoading, error } = useCargoMovement(orderId);

  const columns = useMemo(() => createCargoMovementColumns(), []);

  const rows = useMemo(() => {
    if (!movements || movements.length === 0) return [];
    return movements.map((movement, index) => ({
      id: `${movement.transactionId}-${index}`,
      ...movement,
    }));
  }, [movements]);

  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress size={30} />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ p: 2 }}>
        <Alert severity="error">Erro ao carregar movimentação de carga.</Alert>
      </Box>
    );
  }

  if (!movements || movements.length === 0) {
    return (
      <Box sx={{ p: 2 }}>
        <Alert severity="info">Nenhuma movimentação de carga encontrada para este pedido.</Alert>
      </Box>
    );
  }

  return (
    <DataGridPremium
      rows={rows}
      columns={columns}
      density="compact"
      autoHeight
      hideFooter
      sx={dataGridStylesSimple}
    />
  );
};
