import { Icon } from "@iconify/react";
import { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import styled from "styled-components";
import { initPagoBancard } from "../../api/bancard.service";

// ─── Styles ───────────────────────────────────────────────────────────────────
const Overlay = styled.div`
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1400;
`;

const Dialog = styled.div`
  background: ${({ theme }) => theme.bg1};
  border-radius: 14px;
  width: min(620px, 96vw);
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);
`;

const Header = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid ${({ theme }) => theme.color2};
`;

const Title = styled.h3`
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
`;

const CloseBtn = styled.button`
  background: none;
  border: none;
  cursor: pointer;
  color: ${({ theme }) => theme.color1};
  opacity: 0.6;
  font-size: 20px;
  line-height: 1;
  &:hover { opacity: 1; }
`;

const Body = styled.div`
  flex: 1;
  overflow: hidden;
  position: relative;
  min-height: 400px;
`;

const Frame = styled.iframe`
  width: 100%;
  height: 100%;
  min-height: 440px;
  border: none;
`;

const LoadingOverlay = styled.div`
  position: absolute;
  inset: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  background: ${({ theme }) => theme.bg1};
  font-size: 14px;
  color: ${({ theme }) => theme.textSecondary};
`;

const Footer = styled.div`
  padding: 12px 20px;
  border-top: 1px solid ${({ theme }) => theme.color2};
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: ${({ theme }) => theme.textSecondary};
`;

const AmountBadge = styled.span`
  font-weight: 700;
  font-size: 15px;
  color: ${({ theme }) => theme.color1};
`;

/**
 * BancardPagoModal
 * Props:
 *   open         - boolean
 *   onClose      - () => void
 *   onSuccess    - (pagoId) => void  — llamado cuando Bancard redirige con éxito
 *   monto        - number (Gs)
 *   moneda       - string (default: 'PYG')
 *   descripcion  - string
 *   origenModulo - string
 *   origenId     - string (UUID)
 *   clienteId    - string (UUID, opcional)
 */
export function BancardPagoModal({
  open,
  onClose,
  onSuccess,
  monto,
  moneda = "PYG",
  descripcion,
  origenModulo,
  origenId,
  clienteId,
}) {
  const [loading, setLoading] = useState(false);
  const [processUrl, setProcessUrl] = useState(null);
  const [pagoId, setPagoId] = useState(null);
  const iframeRef = useRef(null);

  useEffect(() => {
    if (!open) {
      setProcessUrl(null);
      setPagoId(null);
      setLoading(false);
      return;
    }
    setLoading(true);
    initPagoBancard({ monto, moneda, descripcion, origenModulo, origenId, clienteId })
      .then((res) => {
        setProcessUrl(res.processUrl);
        setPagoId(res.pagoId);
      })
      .catch((err) => {
        toast.error(err.response?.data?.message || "Error iniciando pago Bancard");
        onClose();
      })
      .finally(() => setLoading(false));
  }, [open]);

  // Escuchar mensaje de Bancard (si la return_url redirige al mismo dominio)
  useEffect(() => {
    const handleMessage = (event) => {
      // Seguridad: solo aceptar mensajes del propio origen. La return_url de Bancard
      // redirige a nuestra página (PagoPublico), que postea al parent en el mismo
      // dominio. Ignorar cualquier mensaje de otro origen (spoofing de UI).
      if (event.origin !== window.location.origin) return;
      if (event.data?.bancardStatus === "success") {
        onSuccess?.(pagoId);
        onClose();
      } else if (event.data?.bancardStatus === "cancel") {
        toast.info("Pago cancelado");
        onClose();
      }
    };
    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, [pagoId]);

  if (!open) return null;

  const fmtGs = (v) =>
    `Gs. ${Number(v || 0).toLocaleString("es-PY", { maximumFractionDigits: 0 })}`;

  return (
    <Overlay onClick={(e) => e.target === e.currentTarget && onClose()}>
      <Dialog>
        <Header>
          <Title>
            <Icon icon="mdi:credit-card-outline" />
            Pago con Bancard
          </Title>
          <CloseBtn onClick={onClose} title="Cerrar">
            <Icon icon="mdi:close" />
          </CloseBtn>
        </Header>

        <Body>
          {loading && (
            <LoadingOverlay>
              <Icon icon="mdi:loading" style={{ fontSize: 32, animation: "spin 1s linear infinite" }} />
              Preparando formulario de pago…
            </LoadingOverlay>
          )}
          {processUrl && (
            <Frame
              ref={iframeRef}
              src={processUrl}
              title="Pago Bancard"
              allow="payment"
            />
          )}
        </Body>

        <Footer>
          <span>{descripcion}</span>
          <AmountBadge>{fmtGs(monto)}</AmountBadge>
        </Footer>
      </Dialog>
    </Overlay>
  );
}
