import {
    Alert,
    Box,
    Button,
    Container,
    Divider,
    Grid,
    List,
    ListItem,
    ListItemText,
    Paper,
    Step,
    StepLabel,
    Stepper,
    TextField,
    Typography
} from '@mui/material';
import { TFunction } from 'i18next';
import React, { useState } from 'react';
import { useTranslation } from "react-i18next";
import { useNavigate } from 'react-router-dom';
import Item from '../components/Item';
import { BasketItem, useBasket } from '../helper/BasketProvider';
import { OrderStatusEnum, ShippingDetails, SubmitOrder } from '../components/Order';
import { useAccount } from '../helper/AccountProvider';
import { useQuery, useMutation } from '@tanstack/react-query';
import { submitCustomer, submitOrder } from '../helper/query/Queries';
import { CustomerType } from '../components/Account';

function getDiscountedPrice(item: Item): number {
    return (item.price100 / 100 * (100-item.discount100)/100);
}

function generateBasket(t: TFunction<"translation", undefined>, basket: BasketItem[]) {
    return basket.length === 0 ? (
        <Typography color="error" sx={{ my: 2 }}>
            {t('basketEmpty')}
        </Typography>
    ) : (
        <List>
            {basket.map((item) => (
                <ListItem key={item.item.uuid}>
                    <ListItemText
                        primary={`${item.quantity}x ${item.item.name}`}
                        secondary={`Item ID: ${item.item.uuid}`}
                    />
                    
                    <div className="rightBound">
                        {`${(item.quantity * getDiscountedPrice(item.item)).toFixed(2)} €`}<br/>
                        {item.item.discount100 > 0 ? <a className='rightBound red'>{-item.item.discount100}%</a> : ""}
                    </div>
                </ListItem>
            ))}
        </List>
    )
}

function generateTotal(t: TFunction<"translation", undefined>, basket: BasketItem[]) {
    return basket.length === 0 ? "" :
        <div className='rightBound'>
            {t('total') + ": " + basket.map((item) => item.quantity * getDiscountedPrice(item.item))
            .reduce((prev: number, cur: number) => prev + cur, 0).toFixed(2) + ` €`}
        </div>
}

export default function Payment() {


    const { t } = useTranslation();
    const { basket, clearBasket } = useBasket();
    const navigator = useNavigate();
    const [activeStep, setActiveStep] = useState(0);
    const [shippingDetails, setShippingDetails] = useState<ShippingDetails>({
        firstName: '',
        lastName: '',
        telefon: '',
        address: '',
        postalCode: '',
        city: '',
        country: 'Deutschland',
    });
    const [orderNumber, setOrderNumber] = useState<string | null>(null);
    const steps = [t('reviewCart'), t('shippingDetails'), t('payment'), t('orderSummary')];
    const { user } = useAccount();
    const customerData: CustomerType = {
        id: 0,
        name: shippingDetails.firstName,
        surname: shippingDetails.lastName,
        address: shippingDetails.address,
        country: shippingDetails.country,
        zip: shippingDetails.postalCode,
    };

    const submitOrderData: SubmitOrder = {
        id: 0, // This will be set by the backend
        customerId: user ? user.customerId : 0, // Use user ID if logged in, otherwise 0
        time: Date.now(),
        status: OrderStatusEnum.ORDERED, // Initial status when order is placed
        orderItems: basket.map(item => ({
            id: item.item.id,
            amount: item.quantity,
            article: item.item.uuid, // Assuming UUID is the identifier for the item
        })),
    };

    const { refetch: refetchCustomer } = useQuery({
        queryKey: ["submitCustomer", customerData],
        queryFn: () => submitCustomer(customerData),
        retry: 0,
        retryDelay: 1000,
        enabled: false,
    });

    const showAlert = () => {
        return <Alert>
            //TODO:
        </Alert>
    };

    // Verwende useMutation statt useQuery für submitOrder
    const { mutateAsync: submitOrderMutation } = useMutation({
        mutationFn: (orderData: SubmitOrder) => submitOrder(orderData),
    });

    const handleNext = async () => {
        let next: boolean = true;

        if (activeStep === steps.length - 2) {
            // Simulate order placement and generate order number
            const generatedOrderNumber = `ORD-${Math.floor(Math.random() * 1000000)}`;
            setOrderNumber(generatedOrderNumber);

            let customerId = user ? user.customerId : 0;
            if (!customerId) {
                const customerResponse = await refetchCustomer();
                customerId = customerResponse.data.id;
            }

            // Erzeuge die Orderdaten mit der richtigen customerId
            const orderData: SubmitOrder = {
                ...submitOrderData,
                customerId,
            };

            try {
                await submitOrderMutation(orderData);
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            } catch (e) {
                next = false;
            }
        }
        if(next) {
            setActiveStep((prevStep) => prevStep + 1);
        } else {
            showAlert();
        }
    };

    const handleBack = () => {
        setActiveStep((prevStep) => prevStep - 1);
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setShippingDetails((prevDetails) => ({
            ...prevDetails,
            [name]: value,
        }));
    };
    const handleClearBasket = () => {
        clearBasket();
    };

    // Hilfsfunktion prüfen, ob alle Pflichtfelder ausgefüllt sind
    const isShippingDetailsValid = () => {
        return (
            shippingDetails.firstName.trim() !== '' &&
            shippingDetails.lastName.trim() !== '' &&
            shippingDetails.address.trim() !== '' &&
            shippingDetails.postalCode.trim() !== '' &&
            shippingDetails.city.trim() !== '' &&
            shippingDetails.country.trim() !== ''
        );
    };

    const renderStepContent = (step: number) => {
        switch (step) {
            case 0:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            {t('reviewCart')}
                        </Typography>
                        {generateBasket(t, basket)}
                        <Divider sx={{ my: 2 }} />
                        <Button variant="outlined" color="error" onClick={handleClearBasket} disabled={basket.length === 0}>
                            {t('clearCart')}
                        </Button>
                        {generateTotal(t,basket)}
                    </Box>
                );
            case 1:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            {t('shippingDetails')}
                        </Typography>
                        <Grid container spacing={2}>

                            <TextField
                                fullWidth
                                label={t('firstName')}
                                name="firstName"
                                value={shippingDetails.firstName}
                                onChange={handleInputChange}
                                required
                            />

                            <TextField
                                fullWidth
                                label={t('lastName')}
                                name="lastName"
                                value={shippingDetails.lastName}
                                onChange={handleInputChange}
                                required
                            />

                            <TextField
                                fullWidth
                                label={t('phone')}
                                name="telefon"
                                value={shippingDetails.telefon}
                                onChange={handleInputChange}
                                type='number'
                            />

                            <TextField
                                fullWidth
                                label={t('address')}
                                name="address"
                                value={shippingDetails.address}
                                onChange={handleInputChange}
                                required
                            />

                            <TextField
                                fullWidth
                                label={t('postalCode')}
                                name="postalCode"
                                value={shippingDetails.postalCode}
                                onChange={handleInputChange}
                                required
                                type='number'
                            />

                            <TextField
                                fullWidth
                                label={t('city')}
                                name="city"
                                value={shippingDetails.city}
                                onChange={handleInputChange}
                                required
                            />

                            <TextField
                                fullWidth
                                label={t('country')}
                                name="country"
                                value={shippingDetails.country}
                                onChange={handleInputChange}
                                required
                            />
                        </Grid>
                    </Box>
                );
            case 2:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            {t('payment')}
                        </Typography>
                        <Typography variant="body1">
                            {t('paymentNotAvailable')}
                        </Typography>
                    </Box>
                );
            case 3:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            {t('orderSummary')}
                        </Typography>
                        <Typography variant="body1" gutterBottom>
                            {t('thanksForOrder')}
                        </Typography>
                        <Typography variant="body2" gutterBottom>
                            {t('yourOrderNumber')}: <strong>{orderNumber}</strong>
                        </Typography>
                        <Divider sx={{ my: 2 }} />
                        <Typography variant="h6">{t('shippingDetails')}:</Typography>
                        <Typography variant="body2">
                            {shippingDetails.firstName} {shippingDetails.lastName}<br />
                            {shippingDetails.address}<br />
                            {shippingDetails.postalCode} {shippingDetails.city}<br />
                            {shippingDetails.country}
                        </Typography>
                        <Divider sx={{ my: 2 }} />
                        <Typography variant="h6">{t('orderedItems')}:</Typography>
                        {generateBasket(t, basket)}
                        <Divider sx={{my: 2}} />
                        {generateTotal(t, basket)}
                        <br/>
                    </Box>
                );
            default:
                return <div>Unknown step</div>;
        }
    };

    return (
        <div className="page-background">
            <Container
                maxWidth="md"
                sx={{
                    py: 4,
                    maxHeight: '90vh',
                    overflowY: 'auto'
                }}
            >
                <Paper elevation={3} sx={{ p: 4 }}>
                    <Typography variant="h4" align="center" gutterBottom>
                        {t('completeYourOrder')}
                    </Typography>
                    <Stepper activeStep={activeStep} alternativeLabel>
                        {steps.map((label) => (
                            <Step key={label}>
                                <StepLabel>{label}</StepLabel>
                            </Step>
                        ))}
                    </Stepper>
                    <Box sx={{ mt: 4 }}>{renderStepContent(activeStep)}</Box>
                    <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4 }}>
                        <Button
                            disabled={activeStep === 0}
                            onClick={handleBack}
                            variant="outlined"
                        >
                            {t('back')}
                        </Button>
                        {activeStep === steps.length - 1 ? (
                            <Button
                                variant="contained"
                                color="primary"
                                onClick={() => {
                                    handleClearBasket();
                                    navigator('/');
                                }}
                            >
                                {t('finish')}
                            </Button>
                        ) : (
                            <Button
                                variant="contained"
                                color="primary"
                                onClick={handleNext}
                                disabled={
                                    basket.length === 0 ||
                                    (activeStep === 1 && !isShippingDetailsValid())
                                }
                            >
                                {activeStep === steps.length - 2 ? t('placeOrder') : t('next')}
                            </Button>
                        )}
                    </Box>
                </Paper>
            </Container>
        </div>
    );
}