import React from "react";
import { Modal, Box, Typography, Button, IconButton } from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";

interface Transaction {
  type: string; // "CableSubscription", "BillPayment", "ManualFunding", "AutomaticFunding", "DataTransaction", "AirtimeTransaction"
  amount?: number; // General transaction amount
  balanceBefore: number; // Balance before transaction
  balanceAfter: number; // Balance after transaction
  status: string; // "Pending", "Successful", "Failed"
  userId?: string;
  bypass: boolean;
  referenceId: string;

  // Airtime Transaction Fields
  airtimeType: string;
  buyingPrice: number;
  // Cable Subscription Fields
  iucOrSmartcardNumber?: number;
  provider: string;
  cablePlan: string;
  action: string;
  refund?: boolean;

  // Bill Payment Fields
  meterNumber?: number;
  token?: string;
  customerPhone?: number;
  meterType?: string;
  request_id?: string;
  customerName?: string;
  customerAddress?: string;
  discoName?: string;

  // Data Transaction Fields
  planType?: string;
  plansize: string;
  mobileNumber?: number;
  medium?: string; // e.g., "API", "Web"
  network?: string;

  // Funding Transaction Fields
  fundingType?: "Manual" | "Automatic"; // Specific to funding transactions
  fundingSource?: "API" | "Admin" | "Referral" | "ONE TIME PAYMENT";
  createdAt: string;
}

interface TransactionDetailsModalProps {
  transaction: Transaction | null;
  onClose: () => void;
}
const TransactionDetailsModal: React.FC<TransactionDetailsModalProps> = ({
  transaction,
  onClose,
}) => {
  if (!transaction) return null;

  const handleDownload = async (format: "pdf" | "image") => {
    const element = document.getElementById("transaction-content");
    if (!element) return;

    if (format === "image") {
      const canvas = await html2canvas(element, { scale: 2 });
      const image = canvas.toDataURL("image/png");
      const link = document.createElement("a");
      link.href = image;
      link.download = "transaction.png";
      link.click();
    } else if (format === "pdf") {
      const pdf = new jsPDF({ orientation: "l", unit: "mm", format: "a4" });
      pdf.html(element, {
        callback: function (doc) {
          doc.save("transaction.pdf");
        },
        x: 15,
        y: 15,
        width: 180,
      });
    }
  };

  const renderTransactionDetails = () => {
    switch (transaction.type) {
      case "AirtimeTransaction":
        return (
          <>
            <Typography variant="body1">
              Network: {transaction.network}
            </Typography>
            <Typography variant="body1">
              Amount: {transaction.amount}
            </Typography>
            <Typography variant="body1">
              Mobile Number: {transaction.mobileNumber}
            </Typography>
            <Typography variant="body1">
              Date: {new Date(transaction.createdAt).toLocaleString()}
            </Typography>
            <Typography variant="body1">
              Status: {transaction.status}
            </Typography>
            <Typography variant="body1">
              Refunded: {transaction.refund}
            </Typography>
          </>
        );
      case "DataTransaction":
        return (
          <>
            <Typography variant="body1">
              Network: {transaction.network}
            </Typography>
            <Typography variant="body1">
              Plan Type: {transaction.planType}
            </Typography>
            <Typography variant="body1">
              Plan Size: {transaction.plansize}
            </Typography>
            <Typography variant="body1">
              Amount: {transaction.amount}
            </Typography>
            <Typography variant="body1">
              Mobile Number: {transaction.mobileNumber}
            </Typography>
            <Typography variant="body1">
              Date: {new Date(transaction.createdAt).toLocaleString()}
            </Typography>
            <Typography variant="body1">
              Status: {transaction.status}
            </Typography>
            <Typography variant="body1">
              Refunded: {transaction.refund}
            </Typography>
          </>
        );
      case "CableSubscription":
        return (
          <>
            <Typography variant="body1">
              Provider: {transaction.provider}
            </Typography>
            <Typography variant="body1">
              IUC Number: {transaction.iucOrSmartcardNumber}
            </Typography>
            <Typography variant="body1">
              Action: {transaction.action}
            </Typography>
            <Typography variant="body1">
              Amount: {transaction.amount}
            </Typography>
            <Typography variant="body1">
              Cable Plan: {transaction.cablePlan}
            </Typography>
            <Typography variant="body1">
              Date: {new Date(transaction.createdAt).toLocaleString()}
            </Typography>
            <Typography variant="body1">
              Status: {transaction.status}
            </Typography>
            <Typography variant="body1">
              Refunded: {transaction.refund}
            </Typography>
          </>
        );
      case "BillPayment":
        return (
          <>
            <Typography variant="body1">
              Provider: {transaction.discoName}
            </Typography>
            <Typography variant="body1">
              Meter Number: {transaction.meterNumber}
            </Typography>
            <Typography variant="body1">
              Meter Type: {transaction.meterType}
            </Typography>
            <Typography variant="body1">Token: {transaction.token}</Typography>
            <Typography variant="body1">
              Amount: {transaction.amount}
            </Typography>
            <Typography variant="body1">
              Cable Plan: {transaction.cablePlan}
            </Typography>
            <Typography variant="body1">
              Date: {new Date(transaction.createdAt).toLocaleString()}
            </Typography>
            <Typography variant="body1">
              Status: {transaction.status}
            </Typography>
            <Typography variant="body1">
              Refunded: {transaction.refund}
            </Typography>
          </>
        );
      case "ManualFunding":
      case "AutomaticFunding":
      case "WithdrawalTransaction":
        return (
          <>
            <Typography variant="body1">
              Amount: {transaction.amount}
            </Typography>
            <Typography variant="body1">
              Funding Type: {transaction.fundingType}
            </Typography>
            <Typography variant="body1">
              Funding Source: {transaction.fundingSource}
            </Typography>
            <Typography variant="body1">
              Previous Balance: {transaction.balanceBefore}
            </Typography>

            <Typography variant="body1">
              New Balance: {transaction.balanceAfter}
            </Typography>
          </>
        );
      default:
        return (
          <Typography variant="body1">
            No additional details available.
          </Typography>
        );
    }
  };

  return (
    <Modal open={Boolean(transaction)} onClose={onClose}>
      <Box
        sx={{
          width: 350,
          bgcolor: "background.paper",
          p: 4,
          position: "relative",
          boxShadow: 24,
          borderRadius: 2,
          mx: "auto",
          mt: 5,
        }}
        id="transaction-details"
      >
        <IconButton
          sx={{ position: "absolute", right: 8, top: 8 }}
          onClick={onClose}
        >
          <CloseIcon />
        </IconButton>
        <Box id="transaction-content">
          <Typography variant="h6" gutterBottom>
            Transaction Details/Receipt
          </Typography>
          {renderTransactionDetails()}
          <Typography variant="body1">Status: {transaction.status}</Typography>
          <Typography variant="body1">
            Reference ID: {transaction.referenceId}
          </Typography>
        </Box>
        <Button
          variant="contained"
          color="primary"
          onClick={() => handleDownload("pdf")}
          sx={{ mt: 2, mr: 1 }}
        >
          Download as PDF
        </Button>
        <Button
          variant="contained"
          color="secondary"
          onClick={() => handleDownload("image")}
          sx={{ mt: 2 }}
        >
          Download as Image
        </Button>
      </Box>
    </Modal>
  );
};

export default TransactionDetailsModal;
