import { Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, Divider, List, ListItemButton, ListItemText, Paper, Stack, Tab, Tabs, Typography } from "@mui/material";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import OrderType, { OrderStatusEnum } from "../components/Order";
import "./pages.css";
import { useAccount } from "../helper/AccountProvider";
import { fetchOrders } from "../helper/query/Queries";

export default function Orders() {

    const {user} = useAccount();
    const [orders, setOrders] = useState<OrderType[]>([])

    const { data: accountOrders } = useQuery<OrderType[]>({
        queryKey: ['fetchOrders', user?.customerId], // Hier sollte die tatsächliche Kunden-ID verwendet werden
        queryFn: () => user ? fetchOrders(user.customerId) : Promise.resolve([]), // Simulierte API-Antwort
        enabled: !!user, // Nur ausführen, wenn user existiert
        retry: 3, // Versucht es 3-mal erneut
        retryDelay: 1000, // Wartezeit zwischen den Versuchen (in ms)
    });

    useEffect(() => {
        setOrders(accountOrders ?? []);
    }, [accountOrders]);

    const { t } = useTranslation();

    const [tab, setTab] = useState(0);
    const [selectedOrder, setSelectedOrder] = useState<OrderType | null>(null);

    const activeOrders = orders.filter(o => o.status === OrderStatusEnum.ISSUES || o.status === OrderStatusEnum.IN_PROGRESS || o.status === OrderStatusEnum.ORDERED);
    const inactiveOrders = orders.filter(o => o.status === OrderStatusEnum.CANCELLED || o.status === OrderStatusEnum.DELIVERED);

    const handleTabChange = (_: React.SyntheticEvent, newValue: number) => setTab(newValue);

    const handleCancelOrder = (orderId: string) => {
        // Hier API-Call zum Stornieren einbauen
        alert(`${t('orderCancelled')} #${orderId}`);
        setSelectedOrder(null);
    };

    return (
        <Box className="page-background page-background-center" sx={{ minHeight: "100vh", pt: 4 }}>
            <Paper elevation={3} sx={{ p: 4, maxWidth: 700, width: "100%", mx: "auto" }}>
                <Typography variant="h4" gutterBottom>
                    {t('myOrders')}
                </Typography>
                <Tabs value={tab} onChange={handleTabChange} sx={{ mb: 3 }}>
                    <Tab label={t('active')} />
                    <Tab label={t('previous')} />
                </Tabs>
                <Divider sx={{ mb: 2 }} />
                {tab === 0 ? (
                    activeOrders.length > 0 ? (
                        <List>
                            {activeOrders.map(order => (
                                <ListItemButton key={order.id} onClick={() => setSelectedOrder(order)}>
                                    <ListItemText
                                        primary={`${t('order')} #${order.id} • ${order.date}`}
                                        secondary={`${t('sum')}: ${order.total.toFixed(2)} € • ${order.items.length} ${t('items')}`}
                                    />
                                </ListItemButton>
                            ))}
                        </List>
                    ) : (
                        <Typography color="text.secondary">{t('noActiveOrders')}</Typography>
                    )
                ) : (
                    inactiveOrders.length > 0 ? (
                        <List>
                            {inactiveOrders.map(order => (
                                <ListItemButton key={order.id} onClick={() => setSelectedOrder(order)}>
                                    <ListItemText
                                        primary={`${t('order')} #${order.id} • ${order.date}`}
                                        secondary={`${t('sum')}: ${order.total.toFixed(2)} € • ${order.items.length} ${t('items')}`}
                                    />
                                </ListItemButton>
                            ))}
                        </List>
                    ) : (
                        <Typography color="text.secondary">{t('noPreviousOrders')}</Typography>
                    )
                )}

                <Dialog open={!!selectedOrder} onClose={() => setSelectedOrder(null)} maxWidth="sm" fullWidth>
                    <DialogTitle>
                        {`${selectedOrder?.status === OrderStatusEnum.IN_PROGRESS ? t('activeOrder') : t('previousOrder')} #${selectedOrder?.id}`}
                    </DialogTitle>
                    <DialogContent dividers>
                        {selectedOrder && (
                            <Stack spacing={2}>
                                <Typography variant="subtitle1">{`${t('orderDate')}: ${selectedOrder.date}`}</Typography>
                                <Typography variant="subtitle1">{`${t('shippingAddress')}: ${selectedOrder.address}`}</Typography>
                                <Divider />
                                <Typography variant="subtitle2">{t('orderedItems')}:</Typography>
                                <List dense>
                                    {selectedOrder.items.map((item, idx) => (
                                        <ListItemText
                                            key={idx}
                                            primary={`${item.name} x${item.quantity}`}
                                            secondary={`${t('pricePerItem')}: ${item.price.toFixed(2)} €`}
                                        />
                                    ))}
                                </List>
                                <Divider />
                                <Typography variant="h6">{`${t('sum')}: ${selectedOrder.total.toFixed(2)} €`}</Typography>
                            </Stack>
                        )}
                    </DialogContent>
                    <DialogActions>
                        {selectedOrder?.status === OrderStatusEnum.IN_PROGRESS && (
                            <Button color="error" onClick={() => handleCancelOrder(selectedOrder.id)}>
                                {t('cancelOrder')}
                            </Button>
                        )}
                        <Button onClick={() => setSelectedOrder(null)}>{t('close')}</Button>
                    </DialogActions>
                </Dialog>
            </Paper>
        </Box>
    );
}
