import React, { useEffect, useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Box, Typography, CircularProgress } from "@mui/material";
import { buildWireGirocodeDataUrl } from "../../utils/wireGirocode.js";
import {
  orderGrossTotal,
  isWireGirocodeEligible,
} from "../../utils/wireGirocodeEligibility.js";
import { WIRE_GIROCODE_RECIPIENT } from "../../config/wireGirocodeRecipient.js";

/**
 * Full-width row content: Girocode QR + bank details (pending + wire only).
 */
const WireOrderGirocode = ({ order, t }) => {
  const { i18n } = useTranslation();
  const [dataUrl, setDataUrl] = useState(null);
  const [genError, setGenError] = useState(false);

  const eligible = isWireGirocodeEligible(order);

  const amount = useMemo(() => {
    const raw = orderGrossTotal(order);
    return Math.round(raw * 100) / 100;
  }, [order]);

  const amountFormatted = useMemo(() => {
    const locale = (i18n.language || "de").replace("_", "-");
    return new Intl.NumberFormat(locale, {
      style: "currency",
      currency: "EUR",
    }).format(amount);
  }, [amount, i18n.language]);

  useEffect(() => {
    if (!eligible || amount < 0.01) {
      setDataUrl(null);
      setGenError(false);
      return;
    }

    let cancelled = false;
    setDataUrl(null);
    setGenError(false);

    buildWireGirocodeDataUrl({
      amount,
      reference: order.orderId,
    })
      .then((url) => {
        if (!cancelled) setDataUrl(url);
      })
      .catch(() => {
        if (!cancelled) setGenError(true);
      });

    return () => {
      cancelled = true;
    };
  }, [eligible, amount, order.orderId]);

  if (!eligible) {
    return null;
  }

  const hint = t
    ? t("orders.girocode.hint")
    : "Mit Ihrer Banking-App scannen, um zu bezahlen.";
  const alt = t
    ? t("orders.girocode.alt")
    : "Girocode für die Überweisung";

  const paymentPending = t
    ? t("orders.girocode.paymentPending")
    : "Diese Bestellung wartet auf Ihre Überweisung.";
  const payToAccount = t
    ? t("orders.girocode.payToAccount")
    : "Bitte überweisen Sie den Betrag auf folgendes Konto:";
  const holder = t
    ? t("orders.girocode.holder", { name: WIRE_GIROCODE_RECIPIENT.name })
    : `Kontoinhaber: ${WIRE_GIROCODE_RECIPIENT.name}`;
  const ibanLine = t
    ? t("orders.girocode.iban", { iban: WIRE_GIROCODE_RECIPIENT.iban })
    : `IBAN: ${WIRE_GIROCODE_RECIPIENT.iban}`;
  const bicLine = t
    ? t("orders.girocode.bic", { bic: WIRE_GIROCODE_RECIPIENT.bic })
    : `BIC: ${WIRE_GIROCODE_RECIPIENT.bic}`;
  const amountLine = t
    ? t("orders.girocode.amount", { amount: amountFormatted })
    : `Betrag: ${amountFormatted}`;
  const purposeLine = t
    ? t("orders.girocode.purpose", { orderId: order.orderId })
    : `Verwendungszweck: ${order.orderId}`;

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: { xs: "column", sm: "row" },
        gap: { xs: 2, sm: 3 },
        alignItems: "flex-start",
      }}
    >
      <Box sx={{ flexShrink: 0, width: { xs: "100%", sm: "auto" } }}>
        <Typography
          variant="caption"
          component="div"
          sx={{ display: "block", mb: 0.5, lineHeight: 1.35, maxWidth: 220 }}
        >
          {hint}
        </Typography>
        {!dataUrl && !genError && (
          <Box
            sx={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              width: 200,
              height: 200,
            }}
          >
            <CircularProgress size={28} />
          </Box>
        )}
        {genError && (
          <Typography variant="caption" color="text.secondary" component="div">
            {t
              ? t("orders.girocode.error")
              : "QR-Code konnte nicht erzeugt werden."}
          </Typography>
        )}
        {dataUrl && (
          <img
            src={dataUrl}
            width={200}
            height={200}
            alt={alt}
            style={{ display: "block", borderRadius: 4 }}
          />
        )}
      </Box>

      <Box sx={{ flex: 1, minWidth: 0 }}>
        <Typography variant="body2" sx={{ mb: 1.5, lineHeight: 1.5 }}>
          {paymentPending}
        </Typography>
        <Typography variant="body2" sx={{ mb: 1, fontWeight: 600 }}>
          {payToAccount}
        </Typography>
        <Typography variant="body2" component="div" sx={{ lineHeight: 1.6 }}>
          {holder}
        </Typography>
        <Typography
          variant="body2"
          component="div"
          sx={{
            lineHeight: 1.6,
            wordBreak: "break-all",
            fontFamily: "ui-monospace, monospace",
          }}
        >
          {ibanLine}
        </Typography>
        <Typography variant="body2" component="div" sx={{ lineHeight: 1.6 }}>
          {bicLine}
        </Typography>
        <Typography variant="body2" component="div" sx={{ mt: 1.5, lineHeight: 1.6 }}>
          {amountLine}
        </Typography>
        <Typography variant="body2" component="div" sx={{ lineHeight: 1.6 }}>
          {purposeLine}
        </Typography>
      </Box>
    </Box>
  );
};

export default WireOrderGirocode;
