/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @typescript-eslint/no-explicit-any */
import UserDashboardLayout from '@/layouts/user_dashboard_layout'
import styles from './withdrawals.module.scss'
import { useState, useEffect } from 'react'
import { Head, router } from '@inertiajs/react'
import Transaction from '@/components/dashboard/Transaction'
import NoResults from '@/components/dashboard/NoResults'
import { FaFilter, FaPiggyBank } from 'react-icons/fa'
import WithdrawalModal from '@/components/dashboard/Modals/WithdrawModal'
import Pagination from '@/components/shared/Pagination'
import { usePaginatedData } from '@/hooks/use-paginated-data'
// import ResultsPerPage from '@/components/shared/ResultsPerPage'


// 🔹 New Table Skeleton Loader 🔹
const TableSkeleton = () => {
  return (
    <div className={styles.tableScrollWrapper}>
      <div className={styles['deposits__history__table']}>
        <span>&nbsp;</span>
        <span>&nbsp;</span>
        <span>&nbsp;</span>
      </div>
      <div className={styles['deposits__history__table__children']}>
        {[...Array(5)].map((_, i) => (
          <div key={i} className={styles['transactions__card--skeleton']} style={{ marginBottom: '1rem' }}>
            <div className={styles['skeleton__line']} style={{ width: '25%' }} />
            <div className={styles['skeleton__line']} style={{ width: '50%' }} />
            <div className={styles['skeleton__line']} style={{ width: '30%' }} />
          </div>
        ))}
      </div>
    </div>
  )
}

const Withdrawals = ({ withdrawals, filters, perPage: initialPerPage = 10, }: any) => {
  const [startDate, setStartDate] = useState(filters?.startDate || '')
  const [endDate, setEndDate] = useState(filters?.endDate || '')
  const [showFilters, setShowFilters] = useState(false)
  const [withdrawalModal, setWithdrawalModal] = useState(false)

   useEffect(() => {
      // Show skeleton loader for 2 seconds
      const timer = setTimeout(() => setLoading(false), 2000)
      return () => clearTimeout(timer)
  }, [])

  console.log("Withdrawals", withdrawals)

  const hasWithdrawals = withdrawals?.data?.length > 0

  const toggleWithdrawalModal = () => {
    setWithdrawalModal(!withdrawalModal)
  }

  const applyFilters = () => {
    router.get('/dashboard/withdrawals', {
      page: 1,
      startDate,
      endDate,
    }, {
      preserveScroll: true,
      preserveState: true,
    });
  }

  const clearFilters = () => {
    setStartDate('')
    setEndDate('')
    router.get('/dashboard/withdrawals', {
      page: 1,
    }, {
      preserveScroll: true,
      preserveState: true,
    });
  }

     const {
      perPage,
      loading: isLoading,
      setLoading,
      handlePageChange,
      handlePerPageChange,
    } = usePaginatedData(initialPerPage);

  return (
    <>
      <Head title="Withdraw from your wallet" />
      {withdrawalModal && <WithdrawalModal onClose={toggleWithdrawalModal} />}

      <div className={styles['deposits']}>
        <div className={styles['deposits__history']}>
          <div className={styles['deposits__history--top']}>
            <div className={styles['deposits__history--top--text']}>
              <h2>Withdrawals</h2>
              <p>View & manage all your withdrawals</p>
            </div>
            <button onClick={toggleWithdrawalModal} className={styles.depositNowBtn}>
              <FaPiggyBank size="1rem" />
              &nbsp; Withdraw
            </button>
          </div>

           {/* Toggle Filter Button */}
           <div className={styles['deposits__history--helpers']}>
            {/* Filter Toggle Button */}
            <button
              className={styles.filterToggleBtn}
              onClick={() => setShowFilters(!showFilters)}
            >
              <FaFilter /> &nbsp; {showFilters ? 'Hide Filters' : 'Apply Date Filter'}
            </button>
          </div>
          {/* <ResultsPerPage
              current={perPage}
              options={[1, 5, 10, 25, 50]}
              onChange={handlePerPageChange}
            /> */}
          {/* Date Filters */}
          {showFilters && (
            <div className={styles.filterSection}>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
              />
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
              />
               <div className={styles.filterButtons}>
                <button style={{ marginRight: "1rem" }} onClick={applyFilters}>Apply</button>
                <button style={{ background: "#f44336" }} onClick={clearFilters}>Clear</button>
              </div>
            </div>
          )}


          {/* 🔹 Show Table Skeleton if loading 🔹 */}
          {isLoading ? (
            <TableSkeleton />
          ) : (
            <div className={styles.tableScrollWrapper}>
              <div className={styles['deposits__history__table']}>
                <span>Type</span>
                <span>Amount</span>
                <span>Channel</span>
                <span>Date Created</span>
                <span>Status</span>
                <span>Details</span>
              </div>

              <div className={styles['deposits__history__table__children']}>
                {hasWithdrawals ? (
                  withdrawals?.data?.map((deposit: any) => (
                    <Transaction key={deposit?.transactionId} transaction={deposit} />
                  ))
                ) : (
                  <NoResults
                    title="No Results"
                    description="No results matched your criteria. Please clear and try again"
                  />
                )}
              </div>
            </div>
          )}

           <div className={styles["attend__pagination"]}>
            {withdrawals?.data?.length > 0 && withdrawals?.links?.length > 0 && (
              <Pagination links={withdrawals?.links} onChange={handlePageChange} />
            )}
        </div>
        </div>
      </div>
    </>
  )
}

Withdrawals.layout = (page: any) => (
  <UserDashboardLayout children={page} title="Dashboard overview" />
)

export default Withdrawals
