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

const Item = styled(Paper)(({ theme }) => ({
    backgroundColor: '#fff',
    ...theme.typography.body2,
    padding: theme.spacing(1),
    textAlign: 'center',
  }));

const steps = ['Review Items', 'Shipping Details', 'Payment', 'Order Summary'];

export default function Payment() {
    const navigator = useNavigate();
    const { basket, clearBasket } = useBasket();
    const [activeStep, setActiveStep] = useState(0);
    const [shippingDetails, setShippingDetails] = useState({
        name: '',
        address: '',
        city: '',
        postalCode: '',
    });
    const [orderNumber, setOrderNumber] = useState<string | null>(null);

    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();
    };

    const renderStepContent = (step: number) => {
        switch (step) {
            case 0:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            Review Items
                        </Typography>
                        <List>
                            {basket.map((item) => (
                                <ListItem key={item.itemId}>
                                    <ListItemText
                                        primary={`Item ID: ${item.itemId}`}
                                        secondary={`Quantity: ${item.quantity}`}
                                    />
                                </ListItem>
                            ))}
                        </List>
                        <Divider sx={{ my: 2 }} />
                        <Button variant="outlined" color="error" onClick={handleClearBasket}>
                            Clear Basket
                        </Button>
                    </Box>
                );
            case 1:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            Shipping Details
                        </Typography>
                        <Grid container spacing={2}>
                            <Item>
                                <TextField
                                    fullWidth
                                    label="Name"
                                    name="name"
                                    value={shippingDetails.name}
                                    onChange={handleInputChange}
                                />
                            </Item>
                            <Item>
                                <TextField
                                    fullWidth
                                    label="Address"
                                    name="address"
                                    value={shippingDetails.address}
                                    onChange={handleInputChange}
                                />
                            </Item>
                            <Item>
                                <TextField
                                    fullWidth
                                    label="City"
                                    name="city"
                                    value={shippingDetails.city}
                                    onChange={handleInputChange}
                                />
                            </Item>
                            <Item>
                                <TextField
                                    fullWidth
                                    label="Postal Code"
                                    name="postalCode"
                                    value={shippingDetails.postalCode}
                                    onChange={handleInputChange}
                                />
                            </Item>
                        </Grid>
                    </Box>
                );
            case 2:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            Payment
                        </Typography>
                        <Typography variant="body1">
                            Payment method not implemented yet.
                        </Typography>
                    </Box>
                );
            case 3:
                return (
                    <Box>
                        <Typography variant="h6" gutterBottom>
                            Order Summary
                        </Typography>
                        <Typography variant="body1" gutterBottom>
                            Thank you for your order!
                        </Typography>
                        <Typography variant="body2" gutterBottom>
                            Your order number is: <strong>{orderNumber}</strong>
                        </Typography>
                        <Divider sx={{ my: 2 }} />
                        <Typography variant="h6">Shipping Details:</Typography>
                        <Typography variant="body2">
                            {shippingDetails.name}, {shippingDetails.address}, {shippingDetails.city},{' '}
                            {shippingDetails.postalCode}
                        </Typography>
                        <Divider sx={{ my: 2 }} />
                        <Typography variant="h6">Ordered Items:</Typography>
                        <List>
                            {basket.map((item) => (
                                <ListItem key={item.itemId}>
                                    <ListItemText
                                        primary={`Item ID: ${item.itemId}`}
                                        secondary={`Quantity: ${item.quantity}`}
                                    />
                                </ListItem>
                            ))}
                        </List>
                    </Box>
                );
            default:
                return <div>Unknown step</div>;
        }
    };

    return (
        <Container maxWidth="md" sx={{ py: 4 }}>
            <Paper elevation={3} sx={{ p: 4 }}>
                <Typography variant="h4" align="center" gutterBottom>
                    Checkout
                </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"
                    >
                        Back
                    </Button>
                    {activeStep === steps.length - 1 ? (
                        <Button
                            variant="contained"
                            color="primary"
                            onClick={() => {
                                navigator('/');
                            }}
                        >
                            Finish
                        </Button>
                    ) : (
                        <Button variant="contained" color="primary" onClick={handleNext}>
                            {activeStep === steps.length - 2 ? 'Place Order' : 'Next'}
                        </Button>
                    )}
                </Box>
            </Paper>
        </Container>
    );
}