import React from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Typography,
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} from '@mui/material';
import { useTranslation } from 'react-i18next';

const OrderDetailsDialog = ({ open, onClose, order }) => {
  const { t } = useTranslation();
  
  if (!order) {
    return null;
  }

  const currencyFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });

  // Helper function to translate payment methods
  const getPaymentMethodDisplay = (paymentMethod) => {
    if (!paymentMethod) return t('orders.details.notSpecified');
    
    switch (paymentMethod.toLowerCase()) {
      case 'wire':
        return t('payment.methods.bankTransfer');
      default:
        return paymentMethod;
    }
  };

  const handleCancelOrder = () => {
    // Implement order cancellation logic here
    console.log(`Cancel order: ${order.orderId}`);
    onClose(); // Close the dialog after action
  };
  
  const total = order.items.reduce((acc, item) => acc + item.price * item.quantity_ordered, 0);

  // Calculate VAT breakdown similar to CartDropdown
  const vatCalculations = order.items.reduce((acc, item) => {
    const totalItemPrice = item.price * item.quantity_ordered;
    const netPrice = totalItemPrice / (1 + item.vat / 100);
    const vatAmount = totalItemPrice - netPrice;
    
    acc.totalGross += totalItemPrice;
    acc.totalNet += netPrice;
    
    if (item.vat === 7) {
      acc.vat7 += vatAmount;
    } else if (item.vat === 19) {
      acc.vat19 += vatAmount;
    }
    
    return acc;
  }, { totalGross: 0, totalNet: 0, vat7: 0, vat19: 0 });

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>{t('orders.details.title', { orderId: order.orderId })}</DialogTitle>
      <DialogContent>
        <Box sx={{ mb: 2 }}>
          <Typography variant="h6">{t('orders.details.deliveryAddress')}</Typography>
          <Typography>{order.shipping_address_name}</Typography>
          <Typography>{order.shipping_address_street} {order.shipping_address_house_number}</Typography>
          <Typography>{order.shipping_address_postal_code} {order.shipping_address_city}</Typography>
          <Typography>{order.shipping_address_country}</Typography>
        </Box>

        <Box sx={{ mb: 2 }}>
          <Typography variant="h6">{t('orders.details.invoiceAddress')}</Typography>
          <Typography>{order.invoice_address_name}</Typography>
          <Typography>{order.invoice_address_street} {order.invoice_address_house_number}</Typography>
          <Typography>{order.invoice_address_postal_code} {order.invoice_address_city}</Typography>
          <Typography>{order.invoice_address_country}</Typography>
        </Box>

        {/* Order Details Section */}
        <Box sx={{ mb: 2 }}>
          <Typography variant="h6" gutterBottom>{t('orders.details.orderDetails')}</Typography>
          <Box sx={{ display: 'flex', gap: 4 }}>
            <Box>
              <Typography variant="body2" color="text.secondary">{t('orders.details.deliveryMethod')}</Typography>
              <Typography variant="body1">{order.deliveryMethod || order.delivery_method || t('orders.details.notSpecified')}</Typography>
            </Box>
            <Box>
              <Typography variant="body2" color="text.secondary">{t('orders.details.paymentMethod')}</Typography>
              <Typography variant="body1">{getPaymentMethodDisplay(order.paymentMethod || order.payment_method)}</Typography>
            </Box>
          </Box>
        </Box>

        <Typography variant="h6" gutterBottom>{t('orders.details.orderedItems')}</Typography>
        <TableContainer component={Paper}>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>{t('orders.details.item')}</TableCell>
                <TableCell align="right">{t('orders.details.quantity')}</TableCell>
                <TableCell align="right">{t('orders.details.price')}</TableCell>
                <TableCell align="right">{t('product.vatShort')}</TableCell>
                <TableCell align="right">{t('orders.details.total')}</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {order.items.map((item) => (
                <TableRow key={item.id}>
                  <TableCell>{item.name}</TableCell>
                  <TableCell align="right">{item.quantity_ordered}</TableCell>
                  <TableCell align="right">{currencyFormatter.format(item.price)}</TableCell>
                  <TableCell align="right">{item.vat}%</TableCell>
                  <TableCell align="right">{currencyFormatter.format(item.price * item.quantity_ordered)}</TableCell>
                </TableRow>
              ))}
              <TableRow>
                <TableCell colSpan={4} align="right">
                  <Typography fontWeight="bold">{t ? t('tax.totalNet') : 'Gesamtnettopreis'}</Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontWeight="bold">{currencyFormatter.format(vatCalculations.totalNet)}</Typography>
                </TableCell>
              </TableRow>
              {vatCalculations.vat7 > 0 && (
                <TableRow>
                  <TableCell colSpan={4} align="right">{t ? t('tax.vat7') : '7% Mehrwertsteuer'}</TableCell>
                  <TableCell align="right">{currencyFormatter.format(vatCalculations.vat7)}</TableCell>
                </TableRow>
              )}
              {vatCalculations.vat19 > 0 && (
                <TableRow>
                  <TableCell colSpan={4} align="right">{t ? t('tax.vat19') : '19% Mehrwertsteuer'}</TableCell>
                  <TableCell align="right">{currencyFormatter.format(vatCalculations.vat19)}</TableCell>
                </TableRow>
              )}
              <TableRow>
                <TableCell colSpan={4} align="right">
                  <Typography fontWeight="bold">{t ? t('cart.summary.total') : 'Gesamtsumme'}</Typography>
                </TableCell>
                <TableCell align="right">
                  <Typography fontWeight="bold">{currencyFormatter.format(total)}</Typography>
                </TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </TableContainer>

      </DialogContent>
      <DialogActions>
        {order.status === 'new' && (
          <Button onClick={handleCancelOrder} color="error">
            {t('orders.details.cancelOrder')}
          </Button>
        )}
        <Button onClick={onClose}>{t ? t('common.close') : 'Schließen'}</Button>
      </DialogActions>
    </Dialog>
  );
};

export default OrderDetailsDialog; 