import React from 'react';
import PaginationLayout from "../components/PaginationLayout";
import { GlobalContext } from "../context/Provider";
import { useContext, useEffect, useState } from "react";
import henceforthApi from "../utils/henceforthApi";
import moment from "moment";

interface WalletTransaction {
  _id: string;
  type: 'CREDIT' | 'DEBIT';
  amount: number;
  balance_before: number;
  balance_after: number;
  transaction_type: 'REFERRAL_REWARD' | 'WITHDRAWAL';
  description: string;
  status: 'PENDING' | 'COMPLETED' | 'FAILED' | 'CANCELLED';
  created_at: string;
  reference_id?: string;
}

function WalletTransation({ _id }: any) {
  const [page, setPage] = useState<number>(1);
  const [state, setState] = useState<{ data: { data: WalletTransaction[]; total_count: number } }>({
    data: {
      data: [],
      total_count: 0,
    },
  });
  const [loading, setLoading] = useState(false);
  const limit = 10;
  const { authState } = useContext(GlobalContext);
  if (authState.access_token) { henceforthApi.setToken(authState.access_token); }

  const onChangePagination = (newVal: number) => {
    setPage(Number(newVal));
  };

  const fetchWalletTransactions = async () => {
    setLoading(true);
    try {
      const res = await henceforthApi.User.walletTransactions(_id, page - 1, limit);
      setState(res);
    } catch (err) {
      console.error("Failed to fetch wallet transactions", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchWalletTransactions();
  }, [page]);

  const getTypeBadge = (type: string) => {
    return type === 'CREDIT'
      ? <span className="badge bg-success">CREDIT</span>
      : <span className="badge bg-danger">DEBIT</span>;
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'COMPLETED': return <span className="badge bg-success">COMPLETED</span>;
      case 'PENDING': return <span className="badge bg-warning text-dark">PENDING</span>;
      case 'FAILED': return <span className="badge bg-danger">FAILED</span>;
      case 'CANCELLED': return <span className="badge bg-secondary">CANCELLED</span>;
      default: return <span className="badge bg-secondary">{status}</span>;
    }
  };

  const getTransactionTypeBadge = (txType: string) => {
    switch (txType) {
      case 'REFERRAL_REWARD': return <span className="badge bg-info text-dark">REFERRAL REWARD</span>;
      case 'WITHDRAWAL': return <span className="badge bg-primary">WITHDRAWAL</span>;
      default: return <span className="badge bg-secondary">{txType}</span>;
    }
  };

  return (
    <div className="row">
      <div className="ibox">
        <div className="ibox-title">
          <h5>Wallet Transactions</h5>
        </div>
        <div className="ibox-content">
          <div className="table-responsive">
            <table className="table table-striped">
              <thead>
                <tr>
                  <th>Sr No</th>
                  <th>Type</th>
                  <th>Transaction Type</th>
                  <th>Amount</th>
                  <th>Description</th>
                  <th>Status</th>
                  <th>Date</th>
                </tr>
              </thead>
              {state.data.total_count !== 0 ? (
                <tbody>
                  {state.data.data.map((res: WalletTransaction, index: number) => (
                    <tr key={res._id || index}>
                      <td>{(page - 1) * limit + (index + 1)}.</td>
                      <td>{getTypeBadge(res.type)}</td>
                      <td>{getTransactionTypeBadge(res.transaction_type)}</td>
                      <td className={res.type === 'CREDIT' ? 'text-success fw-bold' : 'text-danger fw-bold'}>
                        {res.type === 'CREDIT' ? '+' : '-'}{res.amount ?? 'N/A'}
                      </td>
                      <td style={{ maxWidth: '250px' }}>
                        <span title={res.description}>
                          {res.description?.length > 60
                            ? res.description.slice(0, 60) + '...'
                            : res.description || 'N/A'}
                        </span>
                      </td>
                      <td>{getStatusBadge(res.status)}</td>
                      <td className="text-nowrap">
                        {res.created_at
                          ? moment(Number(res.created_at)).format('MMM DD, YYYY')
                          : 'N/A'}
                      </td>
                    </tr>
                  ))}
                </tbody>
              ) : (
                <tbody>
                  <tr>
                    <td colSpan={9}>
                      <div className="row mt-4">
                        <div className="col-12 text-center">
                          <b>Sorry! No wallet transactions to display</b>
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
              )}
            </table>
            <PaginationLayout
              count={state.data.total_count}
              data={state.data.data}
              page={page}
              limit={Number(limit)}
              loading={loading}
              onPageChange={(val) => onChangePagination(val)}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

export default WalletTransation;
