import React, { useState } from "react";
import {
  Box,
  Container,
  Typography,
  Button,
  Grid,
  Card,
  CardMedia,
  Divider,
  IconButton,
  Paper,
  Chip,
  useTheme,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
} from "@mui/material";
import { Link } from "react-router-dom";
import AddIcon from "@mui/icons-material/Add";
import RemoveIcon from "@mui/icons-material/Remove";
import DeleteIcon from "@mui/icons-material/Delete";
import ShoppingCartCheckoutIcon from "@mui/icons-material/ShoppingCartCheckout";
import chairone from "../images/chairone.png";
import chairtwo from "../images/chairtwo.png";
import chairthree from "../images/chairthree.png";

// Sample cart data
const cartItems = [
  {
    id: "ergo-luxe",
    name: "Ergo-Luxe Executive Chair",
    price: 499,
    image: chairone,
    quantity: 1,
  },
  {
    id: "cloud-comfort",
    name: "Cloud Comfort Chair",
    price: 349,
    image: chairtwo,
    quantity: 2,
  },
  {
    id: "velvet-throne",
    name: "Velvet Throne Armchair",
    price: 899,
    image: chairthree,
    quantity: 1,
  },
];

// Similar products data
const similarProducts = [
  {
    id: "modern-executive",
    name: "Modern Executive Chair",
    price: "$429",
    image: "/images/chair-similar1.jpg",
  },
  {
    id: "leather-lounge",
    name: "Leather Lounge Chair",
    price: "$599",
    image: "/images/chair-similar2.jpg",
  },
  {
    id: "contemporary-comfort",
    name: "Contemporary Comfort Chair",
    price: "$379",
    image: "/images/chair-similar3.jpg",
  },
];

const CartPage = () => {
  const theme = useTheme();
  const [items, setItems] = useState(cartItems);

  const updateQuantity = (id: string, newQuantity: number) => {
    if (newQuantity < 1) return;
    setItems(
      items.map((item) =>
        item.id === id ? { ...item, quantity: newQuantity } : item
      )
    );
  };

  const removeItem = (id: string) => {
    setItems(items.filter((item) => item.id !== id));
  };

  const subtotal = items.reduce(
    (sum, item) => sum + item.price * item.quantity,
    0
  );
  const shipping = subtotal > 1000 ? 0 : 49;
  const tax = subtotal * 0.08;
  const total = subtotal + shipping + tax;

  return (
    <Box sx={{ backgroundColor: "#f9f9f9", minHeight: "100vh", py: 8 }}>
      <Container maxWidth="lg">
        <Typography
          variant="h2"
          fontWeight="bold"
          sx={{ mb: 6, color: theme.palette.text.primary }}
        >
          Your Shopping Cart
        </Typography>

        {items.length === 0 ? (
          <Box sx={{ textAlign: "center", py: 10 }}>
            <Typography variant="h4" sx={{ mb: 3 }}>
              Your cart is empty
            </Typography>
            <Button
              component={Link}
              to="/products"
              variant="contained"
              size="large"
              sx={{
                backgroundColor: "#FF6D00",
                color: "#fff",
                py: 1.5,
                px: 4,
                fontSize: "1.1rem",
                fontWeight: 600,
                "&:hover": {
                  backgroundColor: "#FF5722",
                },
              }}
            >
              Continue Shopping
            </Button>
          </Box>
        ) : (
          <Grid container spacing={4}>
            {/* Cart Items */}
            <Grid item xs={12} md={8}>
              <TableContainer
                component={Paper}
                sx={{
                  borderRadius: "12px",
                  boxShadow: theme.shadows[2],
                  overflow: "hidden",
                }}
              >
                <Table>
                  <TableHead>
                    <TableRow sx={{ backgroundColor: "#f5f5f5" }}>
                      <TableCell sx={{ fontWeight: 700 }}>Product</TableCell>
                      <TableCell align="center" sx={{ fontWeight: 700 }}>
                        Price
                      </TableCell>
                      <TableCell align="center" sx={{ fontWeight: 700 }}>
                        Quantity
                      </TableCell>
                      <TableCell align="right" sx={{ fontWeight: 700 }}>
                        Subtotal
                      </TableCell>
                      <TableCell></TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {items.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell>
                          <Box sx={{ display: "flex", alignItems: "center" }}>
                            <CardMedia
                              component="img"
                              image={item.image}
                              alt={item.name}
                              sx={{
                                width: 80,
                                height: 80,
                                objectFit: "cover",
                                borderRadius: "8px",
                                mr: 3,
                              }}
                            />
                            <Typography variant="body1" fontWeight={500}>
                              {item.name}
                            </Typography>
                          </Box>
                        </TableCell>
                        <TableCell align="center">
                          ${item.price.toFixed(2)}
                        </TableCell>
                        <TableCell align="center">
                          <Box
                            sx={{
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "center",
                            }}
                          >
                            <IconButton
                              onClick={() =>
                                updateQuantity(item.id, item.quantity - 1)
                              }
                              sx={{
                                border: "1px solid #ddd",
                                "&:hover": {
                                  backgroundColor: "#FF6D00",
                                  color: "#fff",
                                },
                              }}
                            >
                              <RemoveIcon fontSize="small" />
                            </IconButton>
                            <Typography
                              sx={{
                                mx: 2,
                                minWidth: "30px",
                                textAlign: "center",
                                fontWeight: 500,
                              }}
                            >
                              {item.quantity}
                            </Typography>
                            <IconButton
                              onClick={() =>
                                updateQuantity(item.id, item.quantity + 1)
                              }
                              sx={{
                                border: "1px solid #ddd",
                                "&:hover": {
                                  backgroundColor: "#FF6D00",
                                  color: "#fff",
                                },
                              }}
                            >
                              <AddIcon fontSize="small" />
                            </IconButton>
                          </Box>
                        </TableCell>
                        <TableCell align="right">
                          ${(item.price * item.quantity).toFixed(2)}
                        </TableCell>
                        <TableCell align="right">
                          <IconButton
                            onClick={() => removeItem(item.id)}
                            sx={{
                              color: theme.palette.error.main,
                              "&:hover": {
                                backgroundColor: "rgba(244, 67, 54, 0.08)",
                              },
                            }}
                          >
                            <DeleteIcon />
                          </IconButton>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>

              <Box
                sx={{ mt: 3, display: "flex", justifyContent: "space-between" }}
              >
                <Button
                  component={Link}
                  to="/products"
                  variant="outlined"
                  sx={{
                    borderColor: "#FF6D00",
                    color: "#FF6D00",
                    py: 1,
                    px: 3,
                    fontWeight: 600,
                    "&:hover": {
                      backgroundColor: "rgba(255, 109, 0, 0.08)",
                    },
                  }}
                >
                  Continue Shopping
                </Button>
                <Button
                  variant="outlined"
                  sx={{
                    borderColor: theme.palette.grey[400],
                    color: theme.palette.text.secondary,
                    py: 1,
                    px: 3,
                    fontWeight: 600,
                    "&:hover": {
                      backgroundColor: "rgba(0, 0, 0, 0.04)",
                    },
                  }}
                  onClick={() => setItems([])}
                >
                  Clear Cart
                </Button>
              </Box>
            </Grid>

            {/* Order Summary */}
            <Grid item xs={12} md={4}>
              <Paper
                sx={{
                  p: 3,
                  borderRadius: "12px",
                  boxShadow: theme.shadows[2],
                  backgroundColor: "#fff",
                }}
              >
                <Typography
                  variant="h5"
                  fontWeight="bold"
                  sx={{ mb: 3, color: theme.palette.text.primary }}
                >
                  Order Summary
                </Typography>

                <Box sx={{ mb: 2 }}>
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      mb: 1,
                    }}
                  >
                    <Typography variant="body1">Subtotal:</Typography>
                    <Typography variant="body1" fontWeight={500}>
                      ${subtotal.toFixed(2)}
                    </Typography>
                  </Box>
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      mb: 1,
                    }}
                  >
                    <Typography variant="body1">Shipping:</Typography>
                    <Typography variant="body1" fontWeight={500}>
                      {shipping === 0 ? (
                        <Box component="span" sx={{ color: "success.main" }}>
                          Free
                        </Box>
                      ) : (
                        `$${shipping.toFixed(2)}`
                      )}
                    </Typography>
                  </Box>
                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      mb: 2,
                    }}
                  >
                    <Typography variant="body1">Tax (8%):</Typography>
                    <Typography variant="body1" fontWeight={500}>
                      ${tax.toFixed(2)}
                    </Typography>
                  </Box>

                  <Divider sx={{ my: 2 }} />

                  <Box
                    sx={{
                      display: "flex",
                      justifyContent: "space-between",
                      mb: 3,
                    }}
                  >
                    <Typography variant="h6" fontWeight={700}>
                      Total:
                    </Typography>
                    <Typography variant="h6" fontWeight={700} color="#FF6D00">
                      ${total.toFixed(2)}
                    </Typography>
                  </Box>
                </Box>

                <Button
                  fullWidth
                  variant="contained"
                  size="large"
                  startIcon={<ShoppingCartCheckoutIcon />}
                  sx={{
                    backgroundColor: "#FF6D00",
                    color: "#fff",
                    py: 1.5,
                    fontSize: "1.1rem",
                    fontWeight: 600,
                    borderRadius: "8px",
                    "&:hover": {
                      backgroundColor: "#FF5722",
                      boxShadow: "0 4px 12px rgba(255,109,0,0.3)",
                    },
                  }}
                >
                  Proceed to Checkout
                </Button>

                <Typography
                  variant="body2"
                  sx={{ mt: 2, textAlign: "center", color: "#757575" }}
                >
                  or{" "}
                  <Link
                    to="/products"
                    style={{
                      color: "#FF6D00",
                      textDecoration: "none",
                      fontWeight: 500,
                    }}
                  >
                    Continue Shopping
                  </Link>
                </Typography>
              </Paper>

              {/* Promo Code */}
              <Paper
                sx={{
                  p: 3,
                  mt: 3,
                  borderRadius: "12px",
                  boxShadow: theme.shadows[2],
                  backgroundColor: "#fff",
                }}
              >
                <Typography
                  variant="h6"
                  fontWeight="bold"
                  sx={{ mb: 2, color: theme.palette.text.primary }}
                >
                  Have a Promo Code?
                </Typography>
                <Box sx={{ display: "flex" }}>
                  <input
                    type="text"
                    placeholder="Enter promo code"
                    style={{
                      flexGrow: 1,
                      padding: "12px 16px",
                      border: "1px solid #ddd",
                      borderRadius: "8px 0 0 8px",
                      fontSize: "1rem",
                      outline: "none",
                    }}
                  />
                  <Button
                    variant="contained"
                    sx={{
                      backgroundColor: "#FF6D00",
                      color: "#fff",
                      borderRadius: "0 8px 8px 0",
                      px: 3,
                      "&:hover": {
                        backgroundColor: "#FF5722",
                      },
                    }}
                  >
                    Apply
                  </Button>
                </Box>
              </Paper>
            </Grid>
          </Grid>
        )}

        {/* Similar Products */}
        {items.length > 0 && (
          <Box sx={{ mt: 10 }}>
            <Typography
              variant="h4"
              fontWeight="bold"
              sx={{
                mb: 6,
                position: "relative",
                "&:after": {
                  content: '""',
                  position: "absolute",
                  bottom: -12,
                  left: 0,
                  width: "80px",
                  height: "4px",
                  backgroundColor: "#FF6D00",
                },
              }}
            >
              You Might Also Like
            </Typography>
            <Grid container spacing={4}>
              {similarProducts.map((product) => (
                <Grid item xs={12} sm={6} md={4} key={product.id}>
                  <Card
                    sx={{
                      height: "100%",
                      display: "flex",
                      flexDirection: "column",
                      transition: "all 0.3s ease",
                      borderRadius: "12px",
                      overflow: "hidden",
                      boxShadow: theme.shadows[2],
                      "&:hover": {
                        transform: "translateY(-8px)",
                        boxShadow: theme.shadows[6],
                      },
                    }}
                  >
                    <Box
                      sx={{
                        height: "200px",
                        backgroundImage: `url(${product.image})`,
                        backgroundSize: "cover",
                        backgroundPosition: "center",
                        transition: "transform 0.5s ease",
                        "&:hover": {
                          transform: "scale(1.05)",
                        },
                      }}
                    />
                    <Box sx={{ p: 3, flexGrow: 1 }}>
                      <Typography
                        variant="h5"
                        fontWeight="bold"
                        sx={{
                          mb: 1,
                          fontSize: "1.3rem",
                          color: theme.palette.text.primary,
                        }}
                      >
                        {product.name}
                      </Typography>
                      <Typography
                        variant="h6"
                        color="#FF6D00"
                        sx={{ mb: 2, fontWeight: 700 }}
                      >
                        {product.price}
                      </Typography>
                      <Button
                        component={Link}
                        to={`/products/chairs/${product.id}`}
                        fullWidth
                        variant="outlined"
                        sx={{
                          borderColor: "#FF6D00",
                          color: "#FF6D00",
                          fontWeight: 600,
                          "&:hover": {
                            backgroundColor: "rgba(255,109,0,0.1)",
                            borderColor: "#FF5722",
                          },
                        }}
                      >
                        View Product
                      </Button>
                    </Box>
                  </Card>
                </Grid>
              ))}
            </Grid>
          </Box>
        )}
      </Container>
    </Box>
  );
};

export default CartPage;
