'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 { useCuttingItems } from '../../hooks/useCuttingItems';
import { createCuttingPanelColumns } from './CuttingPanelColumns';
import { dataGridStylesSimple } from '../../utils/dataGridStyles';

interface CuttingPanelProps {
  orderId: number;
}

export const CuttingPanel = ({ orderId }: CuttingPanelProps) => {
  const { data: items, isLoading, error } = useCuttingItems(orderId);

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

  const rows = useMemo(() => {
    if (!items || items.length === 0) return [];
    return items.map((item) => ({
      id: item.productId,
      ...item,
    }));
  }, [items]);

  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 itens de corte.</Alert>
      </Box>
    );
  }

  if (!items || items.length === 0) {
    return (
      <Box sx={{ p: 2 }}>
        <Alert severity="info">Nenhum item de corte encontrado para este pedido.</Alert>
      </Box>
    );
  }

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