import type { CSSProperties } from 'react';
import Divider from '@mui/material/Divider';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import AddIcon from '@mui/icons-material/Add';
import ArrowForwardRoundedIcon from '@mui/icons-material/ArrowForwardRounded';
import CloseIcon from '@mui/icons-material/Close';
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
import GridViewRoundedIcon from '@mui/icons-material/GridViewRounded';
import LockRoundedIcon from '@mui/icons-material/LockRounded';
import RemoveIcon from '@mui/icons-material/Remove';
import ShoppingCartRoundedIcon from '@mui/icons-material/ShoppingCartRounded';
import { styled } from '@mui/material/styles';

import type { CartItem } from './cartTypes';
import { CartDrawer, CartHeader, CartList, CartLine, EmptyCart, QtyControl } from './styles';
import { storeImageSrc } from '@/lib/storeImage';

/* ── Styled extras ───────────────────────────────────────────────────── */

const DrawerSummary = styled('div')({
  display: 'grid',
  gap: 0,
  borderTop: '1px solid rgba(20,33,31,0.1)',
  background: 'var(--store-surface)',
});

const SummaryRows = styled('div')({
  display: 'grid',
  gap: 0,
  padding: '14px 18px 10px',
  '& .row': {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    gap: 10,
    padding: '5px 0',
    '& span': { fontSize: 13, color: 'var(--store-muted)', fontWeight: 'var(--store-body-weight)' as unknown as number },
    '& strong': { fontSize: 13, color: 'var(--store-text)', fontWeight: 'var(--store-label-weight)' as unknown as number },
  },
  '& .row.total': {
    padding: '8px 0 4px',
    '& span': { fontSize: 15, fontWeight: 'var(--store-label-weight)' as unknown as number, color: 'var(--store-text)' },
    '& strong': { fontSize: 20, color: 'var(--store-primary)' },
  },
});

const DrawerActions = styled('div')({
  display: 'grid',
  gridTemplateColumns: '1fr 1fr',
  gap: 10,
  padding: '12px 18px 18px',
});

const CartBtn = styled('button')<{ $primary?: boolean }>(({ $primary }) => ({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 6,
  padding: '11px 16px',
  borderRadius: 12,
  border: $primary
    ? 'none'
    : '1px solid color-mix(in srgb, var(--store-primary) 30%, transparent)',
  background: $primary
    ? 'linear-gradient(135deg, var(--store-primary), color-mix(in srgb, var(--store-primary) 78%, #6366f1))'
    : 'color-mix(in srgb, var(--store-primary) 8%, #ffffff)',
  color: $primary ? '#fff' : 'var(--store-primary)',
  fontSize: 13,
  fontWeight: 700,
  cursor: 'pointer',
  boxShadow: $primary ? '0 8px 20px color-mix(in srgb, var(--store-primary) 34%, transparent)' : 'none',
  transition: 'transform 160ms ease, box-shadow 160ms ease, opacity 160ms ease',
  '&:hover:not(:disabled)': {
    transform: 'translateY(-2px)',
    boxShadow: $primary ? '0 12px 28px color-mix(in srgb, var(--store-primary) 42%, transparent)' : '0 6px 16px rgba(15,23,42,0.1)',
  },
  '&:disabled': {
    opacity: 0.45,
    cursor: 'not-allowed',
  },
  '& svg': { fontSize: 16 },
}));

const CartLineWrap = styled(CartLine)({
  position: 'relative',
  '& .remove-btn': {
    position: 'absolute',
    top: 6,
    right: 6,
    opacity: 0,
    transition: 'opacity 160ms ease',
  },
  '&:hover .remove-btn': {
    opacity: 1,
  },
});

/* ── Component ───────────────────────────────────────────────────────── */

type CartDrawerSectionProps = {
  open: boolean;
  items: CartItem[];
  totalItems: number;
  total: number;
  storeCssVariables: CSSProperties;
  formatPrice: (value: number) => string;
  onClose: () => void;
  onUpdateQuantity: (productId: string, delta: number) => void;
  onRemove?: (productId: string) => void;
  onCheckout: () => void;
  onViewCart?: () => void;
};

function CartDrawerSection({
  open,
  items,
  totalItems,
  total,
  storeCssVariables,
  formatPrice,
  onClose,
  onUpdateQuantity,
  onRemove,
  onCheckout,
  onViewCart,
}: CartDrawerSectionProps) {
  const iva = Math.round(total / 11);

  return (
    <CartDrawer
      anchor="right"
      open={open}
      PaperProps={{ style: storeCssVariables }}
      onClose={onClose}
    >
      <CartHeader>
        <div>
          <Typography variant="h6">Carrito</Typography>
          <Typography color="text.secondary" variant="body2">{totalItems} item(s)</Typography>
        </div>
        <IconButton aria-label="Cerrar carrito" onClick={onClose}>
          <CloseIcon />
        </IconButton>
      </CartHeader>

      <CartList>
        {items.length === 0 ? (
          <EmptyCart>
            <ShoppingCartRoundedIcon />
            <span>Tu carrito está vacío</span>
          </EmptyCart>
        ) : (
          items.map((item) => (
            <CartLineWrap key={item.id}>
              <img src={storeImageSrc(item.image, item.name)} alt={item.name} />
              <div>
                <strong>{item.name}</strong>
                <span>{formatPrice(item.price)}</span>
                <QtyControl>
                  <IconButton size="small" aria-label={`Restar una unidad de ${item.name}`} sx={{ width: 36, height: 36 }} onClick={() => onUpdateQuantity(item.id, -1)}>
                    <RemoveIcon fontSize="small" />
                  </IconButton>
                  <span>{item.quantity}</span>
                  <IconButton size="small" aria-label={`Sumar una unidad de ${item.name}`} sx={{ width: 36, height: 36 }} onClick={() => onUpdateQuantity(item.id, 1)}>
                    <AddIcon fontSize="small" />
                  </IconButton>
                </QtyControl>
              </div>
              {onRemove && (
                <IconButton
                  size="small"
                  className="remove-btn"
                  title="Eliminar"
                  onClick={() => onRemove(item.id)}
                  sx={{ color: 'var(--store-muted)', '&:hover': { color: 'var(--store-danger)' } }}
                >
                  <CloseRoundedIcon sx={{ fontSize: 15 }} />
                </IconButton>
              )}
            </CartLineWrap>
          ))
        )}
      </CartList>

      <DrawerSummary>
        <SummaryRows>
          <div className="row">
            <span>Sub-total</span>
            <strong>{formatPrice(total)}</strong>
          </div>
          <div className="row">
            <span>IVA 10% (incluido)</span>
            <strong>{formatPrice(iva)}</strong>
          </div>
          <Divider sx={{ my: 0.5 }} />
          <div className="row total">
            <span>Total</span>
            <strong>{formatPrice(total)}</strong>
          </div>
        </SummaryRows>

        <DrawerActions>
          <CartBtn
            type="button"
            disabled={items.length === 0}
            onClick={() => { onClose(); onViewCart?.(); }}
          >
            <GridViewRoundedIcon />
            Ver carrito
          </CartBtn>
          <CartBtn
            type="button"
            $primary
            disabled={items.length === 0}
            onClick={() => { onClose(); onCheckout(); }}
          >
            <LockRoundedIcon />
            Finalizar compra
            <ArrowForwardRoundedIcon />
          </CartBtn>
        </DrawerActions>
      </DrawerSummary>
    </CartDrawer>
  );
}

export default CartDrawerSection;
