"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/viewTransaction", {
        id,
        type,
        token,
      });

      if (response.data.status !== "error") {
        setTxn(response.data.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={3}>

            <Box flex="1 1 45%">
              <Typography variant="body2">Amount</Typography>
              <Typography variant="h6">${txn.amount}</Typography>
            </Box>

            <Box flex="1 1 45%">
              <Typography variant="body2">Type</Typography>
              <Typography variant="h6">
                {txn.type == "1" ? "Deposit" : "Withdraw"}
              </Typography>
            </Box>

            <Box flex="1 1 45%">
              <Typography variant="body2">Method</Typography>
              <Typography variant="h6">
                {txn.method?.charAt(0).toUpperCase() + txn.method?.slice(1)}
              </Typography>
            </Box>

            <Box flex="1 1 45%">
              <Typography variant="body2">Employee</Typography>
              <Typography variant="h6">
                {txn.admin?.first} {txn.admin?.last}
              </Typography>
            </Box>


            <Box flex="1 1 45%">
              <Typography variant="body2">Status</Typography>
              <Chip
                label={
                  txn.status == "1"
                    ? "Completed"
                    : txn.status == "2"
                      ? "Rejected"
                      : "Pending"
                }
                color={
                  txn.status == "1"
                    ? "success"
                    : txn.status == "2"
                      ? "error"
                      : "warning"
                }
              />
            </Box>
          </Box>
        </BaseCard>
        <br />
        <BaseCard title="API Log">
          <Box display="flex" flexWrap="wrap" gap={2}>

            {/* REQUEST */}
            <Box flex="1 1 45%">
              <Typography variant="body2">Request</Typography>
              <Box
                component="pre"
                sx={{
                  background: "#0f0f0f",
                  color: "#00e676",
                  p: 2,
                  fontSize: 14,
                  maxHeight: 300,
                  overflow: "auto",
                  whiteSpace: "pre-wrap"
                }}
              >
                {txn?.request
                  ? JSON.stringify(JSON.parse(txn.request), null, 2)
                  : "No Request"}
              </Box>
            </Box>

            {/* RESPONSE */}
            <Box flex="1 1 45%">
              <Typography variant="body2">Response</Typography>
              <Box
                component="pre"
                sx={{
                  background: "#0f0f0f",
                  color: "#29b6f6",
                  p: 2,
                  fontSize: 14,
                  maxHeight: 300,
                  overflow: "auto",
                  whiteSpace: "pre-wrap"
                }}
              >
                {txn?.response
                  ? JSON.stringify(JSON.parse(txn.response), null, 2)
                  : "No Response"}
              </Box>
            </Box>

          </Box>
        </BaseCard>

      </Box>
    </PageContainer>
  );
}
