'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 { useDelivery } from '../../hooks/useDelivery';
import { createDeliveryPanelColumns } from './DeliveryPanelColumns';
import { dataGridStylesSimple } from '../../utils/dataGridStyles';

interface DeliveryPanelProps {
  orderId: number;
}

export const DeliveryPanel = ({ orderId }: DeliveryPanelProps) => {
  const { data: deliveries, isLoading, error } = useDelivery(orderId);

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

  const rows = useMemo(() => {
    if (!deliveries || deliveries.length === 0) return [];
    return deliveries.map((delivery) => ({
      id: delivery.shippimentId,
      ...delivery,
    }));
  }, [deliveries]);

  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 entregas do pedido.</Alert>
      </Box>
    );
  }

  if (!deliveries || deliveries.length === 0) {
    return (
      <Box sx={{ p: 2 }}>
        <Alert severity="info">Nenhuma entrega encontrada para este pedido.</Alert>
      </Box>
    );
  }

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