'use client';

import Button from '@mui/material/Button';
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 ArrowBackRoundedIcon from '@mui/icons-material/ArrowBackRounded';
import ArrowForwardRoundedIcon from '@mui/icons-material/ArrowForwardRounded';
import CloseRoundedIcon from '@mui/icons-material/CloseRounded';
import LockRoundedIcon from '@mui/icons-material/LockRounded';
import RemoveIcon from '@mui/icons-material/Remove';
import ShoppingCartOutlinedIcon from '@mui/icons-material/ShoppingCartOutlined';
import { styled } from '@mui/material/styles';
import type { CartItem } from './cartTypes';
import { storeImageSrc } from '@/lib/storeImage';

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

const Wrap = styled('section')({
  display: 'grid',
  gap: 24,
});

const PageTop = styled('div')({
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'space-between',
  gap: 12,
});

const PageTitle = styled('div')({
  display: 'flex',
  alignItems: 'baseline',
  gap: 10,
  '& h1': {
    margin: 0,
    fontSize: 26,
    fontWeight: 950,
    color: 'var(--store-text)',
    letterSpacing: '-0.5px',
  },
  '& span': {
    fontSize: 14,
    color: 'var(--store-muted)',
    fontWeight: 'var(--store-body-weight)' as unknown as number,
  },
});

const TableWrap = styled('div')({
  borderRadius: 14,
  border: '1px solid rgba(20,33,31,0.09)',
  overflow: 'hidden',
  background: 'var(--store-surface)',
  boxShadow: '0 8px 24px rgba(15,23,42,0.05)',
});

const TableHead = styled('div')(({ theme }) => ({
  display: 'grid',
  gridTemplateColumns: '80px 1fr 140px 140px 140px 44px',
  background: 'color-mix(in srgb, var(--store-background) 60%, #f8f9fb)',
  borderBottom: '1px solid rgba(20,33,31,0.08)',
  '& span': {
    padding: '12px 14px',
    fontSize: 12,
    fontWeight: 'var(--store-label-weight)' as unknown as number,
    color: 'var(--store-muted)',
    textTransform: 'uppercase',
    letterSpacing: '0.5px',
  },
  [theme.breakpoints.down('md')]: {
    display: 'none',
  },
}));

const TableRow = styled('div')(({ theme }) => ({
  display: 'grid',
  gridTemplateColumns: '80px 1fr 140px 140px 140px 44px',
  alignItems: 'center',
  borderBottom: '1px solid rgba(20,33,31,0.07)',
  transition: 'background 160ms ease',
  '&:last-child': { borderBottom: 'none' },
  '&:hover': { background: 'color-mix(in srgb, var(--store-background) 30%, #fff)' },
  '& img': {
    width: 64,
    height: 64,
    objectFit: 'cover',
    borderRadius: 8,
    margin: '10px',
    border: '1px solid rgba(20,33,31,0.08)',
  },
  [theme.breakpoints.down('md')]: {
    gridTemplateColumns: '72px 1fr auto',
    gridTemplateAreas: '"img prod remove" "img qty remove"',
    columnGap: 10,
    rowGap: 6,
    padding: '12px 8px',
    '& img': { margin: 0, gridArea: 'img', alignSelf: 'start' },
    '& .cell-price, & .cell-total': { display: 'none' },
  },
}));

const ProductCell = styled('div')({
  padding: '10px 14px',
  '& strong': {
    display: 'block',
    fontSize: 14,
    fontWeight: 'var(--store-label-weight)' as unknown as number,
    color: 'var(--store-text)',
    lineHeight: 1.3,
    marginBottom: 2,
  },
  '& small': {
    color: 'var(--store-muted)',
    fontSize: 12,
  },
  '@media (max-width: 899.95px)': {
    gridArea: 'prod',
    padding: '0',
  },
});

const QtyCell = styled('div')(({ theme }) => ({
  padding: '10px 14px',
  display: 'inline-flex',
  alignItems: 'center',
  gap: 4,
  '& .qty-wrap': {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 4,
    padding: '3px 4px',
    border: '1px solid color-mix(in srgb, var(--store-primary) 16%, rgba(255,255,255,0.8))',
    borderRadius: 999,
    background: 'linear-gradient(135deg, rgba(255,255,255,0.92), color-mix(in srgb, var(--store-background) 80%, #fff))',
    boxShadow: '0 4px 10px rgba(15,23,42,0.06)',
  },
  '& .qty-num': {
    minWidth: 26,
    textAlign: 'center',
    fontSize: 14,
    fontWeight: 900,
    color: 'var(--store-text)',
  },
  '& .MuiIconButton-root': {
    width: 28,
    height: 28,
    color: 'var(--store-primary)',
    transition: 'background 150ms, color 150ms',
    '&:hover': { background: 'var(--store-primary)', color: '#fff' },
  },
  [theme.breakpoints.down('md')]: {
    padding: 0,
    gridArea: 'qty',
    justifySelf: 'start',
  },
}));

const PriceCell = styled('div')({
  padding: '10px 14px',
  fontSize: 14,
  color: 'var(--store-text)',
  fontWeight: 'var(--store-body-weight)' as unknown as number,
});

const TotalCell = styled('div')({
  padding: '10px 14px',
  fontSize: 15,
  fontWeight: 'var(--store-label-weight)' as unknown as number,
  color: 'var(--store-primary)',
});

const RemoveCell = styled('div')({
  padding: '10px 6px',
  display: 'flex',
  justifyContent: 'center',
  '@media (max-width: 899.95px)': {
    gridArea: 'remove',
    padding: 0,
    alignItems: 'flex-start',
  },
});

/**
 * El resumen colgaba abajo a la derecha y el resto de esa fila quedaba en blanco.
 * Ahora comparte el alto con la lista y queda a la vista mientras se revisa el
 * carrito, que es donde se lo busca.
 */
const CartLayout = styled('div')(({ theme }) => ({
  display: 'grid',
  gridTemplateColumns: 'minmax(0, 1fr) 320px',
  gap: 20,
  alignItems: 'start',
  [theme.breakpoints.down('md')]: {
    gridTemplateColumns: '1fr',
  },
}));

const CartMain = styled('div')({
  display: 'grid',
  gap: 16,
  minWidth: 0,
});

const CartAside = styled('div')(({ theme }) => ({
  position: 'sticky',
  top: 16,
  display: 'grid',
  gap: 12,
  [theme.breakpoints.down('md')]: {
    position: 'static',
  },
}));

const TotalsBox = styled('div')({
  minWidth: 0,
  borderRadius: 14,
  border: '1px solid rgba(20,33,31,0.09)',
  background: 'var(--store-surface)',
  boxShadow: '0 8px 24px rgba(15,23,42,0.05)',
  overflow: 'hidden',
  '& .totals-row': {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    gap: 14,
    padding: '11px 18px',
    borderBottom: '1px solid rgba(20,33,31,0.07)',
    '& span': { fontSize: 13, color: 'var(--store-muted)', fontWeight: 'var(--store-body-weight)' as unknown as number },
    '& strong': { fontSize: 14, color: 'var(--store-text)', fontWeight: 'var(--store-label-weight)' as unknown as number },
  },
  '& .totals-row:last-child': {
    borderBottom: 'none',
    '& span': { fontSize: 14, fontWeight: 'var(--store-label-weight)' as unknown as number, color: 'var(--store-text)' },
    '& strong': { fontSize: 22, color: 'var(--store-primary)' },
  },
  '& .totals-actions': {
    display: 'grid',
    gap: 10,
    padding: '14px 18px',
    borderTop: '1px solid rgba(20,33,31,0.08)',
    background: 'color-mix(in srgb, var(--store-background) 40%, #fff)',
  },
});

const EmptyState = styled('div')({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 12,
  padding: '64px 24px',
  color: 'var(--store-muted)',
  '& svg': { fontSize: 52, opacity: 0.3 },
});

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

type CartPageSectionProps = {
  items: CartItem[];
  totalItems: number;
  formatPrice: (v: number) => string;
  onBack: () => void;
  onUpdateQuantity: (productId: string, delta: number) => void;
  onRemove: (productId: string) => void;
  onCheckout: () => void;
};

export default function CartPageSection({
  items,
  totalItems,
  formatPrice,
  onBack,
  onUpdateQuantity,
  onRemove,
  onCheckout,
}: CartPageSectionProps) {
  const subtotal = items.reduce((s, i) => s + i.price * i.quantity, 0);
  // IVA 10% incluido en precio (Paraguay): IVA = total / 11
  const iva = Math.round(subtotal / 11);

  return (
    <Wrap>
      <PageTop>
        <PageTitle>
          <h1>Carrito de compras</h1>
          <span>{totalItems} producto{totalItems !== 1 ? 's' : ''}</span>
        </PageTitle>
      </PageTop>

      <CartLayout>
        <CartMain>
      <TableWrap>
        <TableHead>
          <span />
          <span>Producto</span>
          <span>Cantidad</span>
          <span>Precio unitario</span>
          <span>Total</span>
          <span />
        </TableHead>

        {items.length === 0 ? (
          <EmptyState>
            <ShoppingCartOutlinedIcon />
            <span>Tu carrito está vacío</span>
            <Button variant="outlined" size="small" startIcon={<ArrowBackRoundedIcon />} onClick={onBack}>
              Ver productos
            </Button>
          </EmptyState>
        ) : (
          items.map((item) => (
            <TableRow key={item.id}>
              <img src={storeImageSrc(item.image, item.name)} alt={item.name} />
              <ProductCell>
                <strong>{item.name}</strong>
                <small>{formatPrice(item.price)}</small>
                {item.financingPlan && (
                  <small style={{ color: 'var(--store-primary)', fontWeight: 700 }}>
                    {item.financingPlan.installmentsCount}x {formatPrice(item.financingPlan.installmentAmount)} ·{' '}
                    {item.financingPlan.label}
                  </small>
                )}
              </ProductCell>
              <QtyCell>
                <div className="qty-wrap">
                  <IconButton size="small" aria-label={`Restar una unidad de ${item.name}`} sx={{ width: 36, height: 36 }} onClick={() => onUpdateQuantity(item.id, -1)}>
                    <RemoveIcon sx={{ fontSize: 16 }} />
                  </IconButton>
                  <span className="qty-num">{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 sx={{ fontSize: 16 }} />
                  </IconButton>
                </div>
              </QtyCell>
              <PriceCell className="cell-price">{formatPrice(item.price)}</PriceCell>
              <TotalCell className="cell-total">{formatPrice(item.price * item.quantity)}</TotalCell>
              <RemoveCell>
                <IconButton
                  size="small"
                  title="Eliminar"
                  aria-label={`Quitar ${item.name} del carrito`}
                  onClick={() => onRemove(item.id)}
                  sx={{ color: 'var(--store-muted)', '&:hover': { color: 'var(--store-danger)', background: 'rgba(239,68,68,0.08)' } }}
                >
                  <CloseRoundedIcon sx={{ fontSize: 16 }} />
                </IconButton>
              </RemoveCell>
            </TableRow>
          ))
        )}
      </TableWrap>
          <div>
            <Button
              variant="outlined"
              startIcon={<ArrowBackRoundedIcon />}
              onClick={onBack}
              sx={{ borderColor: 'var(--store-primary)', color: 'var(--store-primary)' }}
            >
              Seguir comprando
            </Button>
          </div>
        </CartMain>

        {items.length > 0 && (
        <CartAside>
          <TotalsBox>
            <div className="totals-row">
              <span>Subtotal</span>
              <strong>{formatPrice(subtotal)}</strong>
            </div>
            <div className="totals-row">
              <span>IVA 10% incluido</span>
              <strong>{formatPrice(iva)}</strong>
            </div>
            <Divider />
            <div className="totals-row">
              <span>Total</span>
              <strong>{formatPrice(subtotal)}</strong>
            </div>
            <div className="totals-actions">
              <Button
                variant="contained"
                size="large"
                fullWidth
                startIcon={<LockRoundedIcon />}
                endIcon={<ArrowForwardRoundedIcon />}
                onClick={onCheckout}
                sx={{
                  borderRadius: 2.5, fontWeight: 800,
                  background: 'linear-gradient(135deg, var(--store-primary), color-mix(in srgb, var(--store-primary) 78%, #6366f1))',
                  boxShadow: '0 10px 28px color-mix(in srgb, var(--store-primary) 34%, transparent)',
                }}
              >
                Finalizar compra
              </Button>
            </div>
          </TotalsBox>
        </CartAside>
        )}
      </CartLayout>
    </Wrap>
  );
}
