import {
    Box,
    Button,
    Container,
    Divider,
    Grid,
    List,
    ListItem,
    ListItemText,
    Paper,
    Step,
    StepLabel,
    Stepper,
    TextField,
    Typography
} from '@mui/material';
import React, { useState } from 'react';
import { useTranslation } from "react-i18next";
import { useNavigate } from 'react-router-dom';
import { useBasket } from '../helper/BasketProvider';

type ShippingDetails = {
    firstName: string;
    lastName: string;
    telefon: string;
    address: string;
    postalCode: string;
    city: string;
    country: string;
};


export default function Payment() {

    const { t } = useTranslation();
    const navigator = useNavigate();
    const { basket, clearBasket } = useBasket();
    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 handleNext = () => {
        if (activeStep === steps.length - 2) {
            // Simulate order placement and generate order number
            const generatedOrderNumber = `ORD-${Math.floor(Math.random() * 1000000)}`;
            setOrderNumber(generatedOrderNumber);
            clearBasket(); // Clear the basket after placing the order
        }
        setActiveStep((prevStep) => prevStep + 1);
    };

    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>
                        {basket.length === 0 ? (
                            <Typography color="error" sx={{ my: 2 }}>
                                {t('basketEmpty')}
                            </Typography>
                        ) : (
                            <List>
                                {basket.map((item) => (
                                    <ListItem key={item.item.uuid}>
                                        <ListItemText
                                             primary={`${item.item.name} (${item.item.price100 / 100} €)`}
                                        secondary={`Item ID: ${item.item.uuid} \n Quantity: ${item.quantity} \n Price: ${(item.item.price100 * item.quantity) / 100} €`}
                                        />
                                    </ListItem>
                                ))}
                            </List>
                        )}
                        <Divider sx={{ my: 2 }} />
                        <Button variant="outlined" color="error" onClick={handleClearBasket} disabled={basket.length === 0}>
                            {t('clearCart')}
                        </Button>
                    </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('telephone')}
                                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>
                        <List>
                            {basket.map((item) => (
                                <ListItem key={item.item.uuid}>
                                    <ListItemText
                                        primary={`${item.item.name} (${item.item.price100 / 100} €)`}
                                        secondary={`Item ID: ${item.item.uuid} \n Quantity: ${item.quantity} \n Price: ${(item.item.price100 * item.quantity) / 100} €`}
                                    />
                                </ListItem>
                            ))}
                        </List>
                    </Box>
                );
            default:
                return <div>Unknown step</div>;
        }
    };

    return (
        <div className="page-background">
            <Container maxWidth="md" sx={{ py: 4 }}>
                <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={() => {
                                    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>
    );
}