import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getAllCoinPlan } from '../../store/coinPlanSlice';
import NewTitle from '../../extra/Title';
import Table from '../../extra/Table';
import Pagination from '../../extra/Pagination';
import moment from 'moment';
import { useRouter } from 'next/router';
import { getSetting } from '../../store/settingSlice';
import Button from '../../extra/Button';
import { IconHistory } from '@tabler/icons-react';

const CoinPlanHistoryPage = () => {
  const dispatch = useDispatch();
  const router = useRouter();
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(20);
  const [data, setData] = useState([]);
  const [startDate, setStartDate] = useState('All');
  const [endDate, setEndDate] = useState('All');
  const { allCoinPlan, totalEarnings, total } = useSelector(
    (state) => state.coinPlan
  );
  const { setting } = useSelector((state) => state.setting);

  

  useEffect(() => {
    setData(allCoinPlan);
  }, [allCoinPlan]);

  useEffect(() => {
    dispatch(getAllCoinPlan({ startDate, endDate, page, size }));
  }, [startDate, page, size]);

  useEffect(() => {
     dispatch(getSetting());
  }, [dispatch]);

  const handlePageChange = (pageNumber) => {
    setPage(pageNumber);
  };
  const handleRowsPerPage = (value) => {
    setPage(1);
    setSize(value);
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      sessionStorage.removeItem('coinPlanHistory');
    }
  }, []);

  const handleOpen = async (row) => {
    if (typeof window !== 'undefined') {
      sessionStorage.setItem('coinPlanHistory', JSON.stringify(row));
      await router.prefetch('/coinPlanHistory');
      router.push(`/coinPlanHistory`);
    }
  };

  const coinPlanTable = [
    {
      Header: 'No',
      body: 'no',
      Cell: ({ index }) => (
        <span className="  text-nowrap">
          {(page - 1) * size + parseInt(index) + 1}
        </span>
      ),
    },
    {
      Header: 'Name',
      body: 'name',
      Cell: ({ row }) => (
        <span className="  text-nowrap">{row?.name || '-'}</span>
      ),
    },
    {
      Header: 'Total Purchases',
      body: 'totalPurchases',
      Cell: ({ row }) => (
        <span className="text-nowrap">{row?.totalPlansPurchased || '-'}</span>
      ),
    },
    {
      Header: 'Amount Spent',
      body: 'amountSpent',
      Cell: ({ row }) => (
        <span className="text-nowrap">{row?.totalAmountSpent || '-'}</span>
      ),
    },
    {
      Header: 'Date',
      body: 'createdAt',
      Cell: ({ row }) => (
        <span className="  text-nowrap">
          {moment(row?.createdAt).format('DD/MM/YYYY')}
        </span>
      ),
    },
    {
      Header: 'History',
      body: 'history',
      Cell: ({ row }) => (

        <div className='action-button'>
          <Button
            btnIcon={
              <IconHistory className="text-secondary" />
            }
            onClick={() => handleOpen(row)}
          />
        </div>
      ),
    },
  ];
  return (
    <>
      <div className="user-table real-user mb-3">
        <div className="align-items-center d-flex justify-content-between user-table-top">
          <h5
            style={{
              fontWeight: "500",
              fontSize: "20px",
              marginBottom: "5px",
              marginTop: "5px",
            }}
          >
            Coin Plan History
          </h5>
          <p className="fw-medium m-0 text-success">Admin Earnings : {totalEarnings} {setting?.currency?.symbol || "$"}</p>
        </div>
        <Table
          data={data}
          mapData={coinPlanTable}
          serverPerPage={size}
          serverPage={page}
          type={"server"}
        />
        <Pagination
          type={"client"}
          activePage={page}
          rowsPerPage={size}
          userTotal={total}
          setPage={setPage}
          handleRowsPerPage={handleRowsPerPage}
          handlePageChange={handlePageChange}
        />
      </div>
    </>
  );
};
export default CoinPlanHistoryPage;
