"use client";

import { useEffect, useState } from "react";
import {
  Box,
  Typography,
  Chip,
  Button,
  LinearProgress,
} from "@mui/material";
import { useRouter, useSearchParams, useParams } from "next/navigation";
import axios from "axios";
import PageContainer from "@/app/components/container/PageContainer";
import BaseCard from "@/app/components/shared/BaseCard";
import { getSession } from "@/utils/sessionData";

export default function TransactionView() {
  const { id } = useParams();
  const searchParams = useSearchParams();
  const kioskId = searchParams.get("kioskId") ?? searchParams?.get("kiosk_id");
  const type = searchParams.get("type") ?? "";

  const router = useRouter();
  const [txn, setTxn] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [sessionData, setSessionData] = useState<any>(null);
  const [actionLoading, setActionLoading] = useState(false);

  useEffect(() => {
    setSessionData(getSession());
  }, []);

  const fetchTxn = async () => {
    try {
      setLoading(true);
      const token = sessionData?.token;

      const response = await axios.post("/api/getTransaction", {
        id,
        type,
        token,
      });

      if (response.data.status !== "error") {
        setTxn(response.data);
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (sessionData?.token) fetchTxn();
  }, [sessionData?.token]);

  const handleApprove = async () => {
    setActionLoading(true);
    const token = sessionData?.token;
    const payload = { id: txn.id };

    let url =
      txn.txnType === "deposit"
        ? "https://kapi.logiclane.tech/api/kiosk/approveDeposit"
        : "https://kapi.logiclane.tech/api/kiosk/approveRedeem";

    try {
      const res = await axios.post(url, payload, {
        headers: { Authorization: `Bearer ${token}` },
      });

      if (res.data.status !== "error") fetchTxn();
    } finally {
      setActionLoading(false);
    }
  };

  const handleReject = async () => {
    setActionLoading(true);
    const token = sessionData?.token;
    const payload = { id: txn.id };

    let url =
      txn.txnType === "deposit"
        ? "https://kapi.logiclane.tech/api/kiosk/rejectDeposit"
        : "https://kapi.logiclane.tech/api/kiosk/rejectRedeem";

    try {
      const res = await axios.post(url, payload, {
        headers: { Authorization: `Bearer ${token}` },
      });

      if (res.data.status !== "error") fetchTxn();
    } finally {
      setActionLoading(false);
    }
  };

  if (loading) return <LinearProgress />;

  if (!txn)
    return (
      <PageContainer title="Transaction Detail">
        <Box p={3}>
          <Typography>No transaction found</Typography>
        </Box>
      </PageContainer>
    );

  return (
    <PageContainer title="Transaction Detail">
      <Box>
        <Button variant="outlined" onClick={() => router.back()} sx={{ mb: 2 }}>
          ← Back
        </Button>

        <BaseCard title={`Transaction #${txn.id}`}>
          <Box
            display="flex"
            flexWrap="wrap"
            gap={2}
            mt={2}
            justifyContent="space-between"
          >
            {/* Amount */}
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Amount
              </Typography>
              <Typography variant="h6" fontWeight={600}>
                ${txn.amount}
              </Typography>
            </Box>

            {/* Type always opposite Amount for alignment */}
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Type
              </Typography>
              <Typography variant="h6">
                {txn.txnType.charAt(0).toUpperCase() +
                  txn.txnType.slice(1)}
              </Typography>
            </Box>

            {/* Deposit / Redeem: Game */}
            {txn.txnType !== "cashout" && txn.txnType !== "cash" && (
              <Box flex="1 1 45%">
                <Typography variant="body2" color="textSecondary">
                  Game
                </Typography>
                <Typography variant="h6">{txn.Game?.name}</Typography>
              </Box>
            )}

            {/* Deposit / Redeem: User */}

            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                User
              </Typography>
              <Typography
                variant="h6"
                component="a"
                href={`/viewUser/${txn?.KioskUser?.id}?kioskId=${kioskId}`}
                style={{
                  color: "#5D87FF",
                  textDecoration: "none",
                  fontWeight: 600,
                  cursor: "pointer",
                }}
              >
                {txn?.KioskUser?.firstName} {txn?.KioskUser?.lastName}
              </Typography>
            </Box>


            {/* CASHOUT — place denoms in RIGHT COLUMN to avoid empty space */}
            {txn.txnType === "cashout" &&
              txn.cassetteBreakdown?.length > 0 && (
                <Box flex="1 1 45%">
                  <Typography variant="body2" color="textSecondary">
                    Cashout Denominations
                  </Typography>
                  <Box mt={1}>
                    {txn.cassetteBreakdown.map((cb: any, i: number) => (
                      <Typography key={i} variant="h6">
                        {cb.label}
                      </Typography>
                    ))}
                  </Box>
                </Box>
              )}

            {/* DEPOSIT — NV200 denominations */}
            {txn.txnType === "deposit" && (() => {
              let combo = [];

              try {
                combo = Array.isArray(txn?.combination)
                  ? txn?.combination
                  : JSON.parse(txn?.combination);
              } catch {
                combo = [];
              }

              return combo?.length > 0 ? (
                <Box flex="1 1 45%">
                  <Typography variant="body2" color="textSecondary">
                    Denominations
                  </Typography>
                  <Box mt={1}>
                    {combo?.map((cash: any, i: number) => (
                      <Typography key={i} variant="h6">
                        {cash?.name}
                      </Typography>
                    ))}
                  </Box>
                </Box>
              ) : null;
            })()}

            {/* Approve / Reject */}
            {txn.status === "0" && (
              <Box
                flex="1 1 100%"
                display="flex"
                gap={2}
                justifyContent="flex-end"
                mt={2}
              >
                <Button
                  variant="contained"
                  color="error"
                  onClick={handleReject}
                  disabled={actionLoading}
                >
                  Reject
                </Button>

                <Button
                  variant="contained"
                  color="success"
                  onClick={handleApprove}
                  disabled={actionLoading}
                >
                  Approve
                </Button>
              </Box>
            )}

            {/* STATUS — ALWAYS LAST, FULL WIDTH */}
            <Box flex="1 1 45%" mt={1}>
              <Typography variant="body2" color="textSecondary">
                Status
              </Typography>
              <Chip
                label={
                  txn.status === "1"
                    ? "Completed"
                    : txn.status === "2"
                      ? "Rejected"
                      : "Pending"
                }
                color={
                  txn.status === "1"
                    ? "success"
                    : txn.status === "2"
                      ? "error"
                      : "warning"
                }
                sx={{ mt: 1 }}
              />
            </Box>
          </Box>
        </BaseCard>
        <br />
        <BaseCard title="Api Log">
          <Box
            display="flex"
            flexWrap="wrap"
            gap={2}
            mt={2}
            justifyContent="space-between"
          >
            {/* REQUEST */}
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Request
              </Typography>

              <Box
                component="pre"
                sx={{
                  background: "#0f0f0f",
                  color: "#00e676",
                  p: 2,
                  // borderRadius: 2,
                  whiteSpace: "pre-wrap",
                  wordBreak: "break-word",
                  fontSize: "14px",
                  maxHeight: 300,
                  overflow: "auto",
                }}
              >
                {txn?.ApiLog?.request
                  ? JSON.stringify(JSON.parse(txn.ApiLog.request), null, 2)
                  : "No Request"}
              </Box>
            </Box>

            {/* RESPONSE */}
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Response
              </Typography>

              <Box
                component="pre"
                sx={{
                  background: "#0f0f0f",
                  color: "#29b6f6",
                  p: 2,
                  // borderRadius: 2,
                  whiteSpace: "pre-wrap",
                  wordBreak: "break-word",
                  fontSize: "14px",
                  maxHeight: 300,
                  overflow: "auto",
                }}
              >
                {txn?.ApiLog?.response
                  ? JSON.stringify(JSON.parse(txn.ApiLog.response), null, 2)
                  : "No Response"}
              </Box>
            </Box>
          </Box>
        </BaseCard>
      </Box>
    </PageContainer>
  );
}
