/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */

import styles from "./withdrawals.module.scss"
import AdminDashboardLayout from "@/layouts/admin_layout"
import PageIntro from "@/components/dashboard/PageIntro"
import { BsSearch } from "react-icons/bs"
import { useForm } from "@inertiajs/react"
import NoResults from "@/components/dashboard/NoResults"
import { useState, useEffect } from "react"
// import ProcessWithdrawalModal from "@/components/admin/Modals/ProcessWithdrawalModal"
import { usePaginatedData } from "@/hooks/use-paginated-data"
import Pagination from "@/components/shared/Pagination"
import ResultsPerPage from "@/components/shared/ResultsPerPage"
import { formatDate } from "@/lib/utils/format-date"
import { truncateEmail } from "@/lib/utils/truncate-email"
import ProcessWithdrawalModal from "@/components/admin/Modals/ProcessWithdrawalModal"
import {usePage} from "@inertiajs/react"
import WithdrawalDetailsModal from "@/components/admin/Modals/WithdrawalDetailsModal"

import currencyData from "../../../../data/countries-currencies.json";
import { formatMoneyComplete } from '@/lib/utils/format-money'

const Withdrawals = ({ withdrawals, perPage: initialPerPage = 10 }: any) => {
    const {
    perPage,
    loading: isLoading,
    handlePageChange,
    handlePerPageChange,
  } = usePaginatedData(initialPerPage)

  const { data, setData } = useForm({
    searchTerm: ""
  })

  const [processWithdrawal, setProcessWithdrawal] = useState(false)
  const [withdrawal, setWithdrawal] = useState({})
  const [loading, setLoading] = useState(true)

  const [showDetails, setShowDetails] = useState(false)
  const [selectedWithdrawal, setSelectedWithdrawal] = useState<any>(null)

  const toggleDetailsModal = (withdrawal: any) => {
    setSelectedWithdrawal(withdrawal)
    setShowDetails(!showDetails)
  }

   const { appSettings } = usePage().props as any

  const currency = currencyData.find(
    (item) => item.currency_code === appSettings?.base_currency
  )

  useEffect(() => {
    const timer = setTimeout(() => setLoading(false), 1500)
    return () => clearTimeout(timer)
  }, [])

  const toggleProcessWithdrawalModal = (singleWithdrawal: any) => {
    setProcessWithdrawal(!processWithdrawal)
    setWithdrawal(singleWithdrawal)
  }

  // Skeleton mimicking table structure
  const TableSkeleton = () => (
    <div className={styles["deposits__children"]}>
      {[...Array(5)].map((_, i) => (
        <div key={i} className={styles["skeleton__row"]}>
          {[...Array(6)].map((_, j) => (
            <div key={j} className={styles["skeleton__cell"]} />
          ))}
        </div>
      ))}
    </div>
  )

  return (
    <>
    {showDetails && (
      <WithdrawalDetailsModal
        withdrawal={selectedWithdrawal}
        closeModal={() => setShowDetails(false)}
      />
    )}

      {processWithdrawal && (
        <ProcessWithdrawalModal 
          closeModal={toggleProcessWithdrawalModal} 
          withdrawal={withdrawal}
        />
      )}

      <div className={styles["withdrawals"]}>
        <PageIntro
          title="Withdrawals"
          description="View and manage users withdrawal requests"
        />

        <div>
          <ResultsPerPage
            current={perPage}
            options={[1, 5, 10, 25, 50]}
            onChange={handlePerPageChange}
          />
        </div>

         {/* <div className={styles["withdrawals__header"]}>
          <form className={styles["withdrawals__header--form"]}>
            <div className={styles["withdrawals__header--form--left"]}>
              <BsSearch size="1.1rem" color="#FFF" />
              <input
                type="text"
                placeholder="Search withdrawals by email"
                value={data.searchTerm}
                onChange={(e) => setData("searchTerm", e.target.value)}
              />
            </div>
            <button type="submit">Search</button>
          </form>
        </div> */}

        <div className={styles["withdrawals__content"]}>
        <div className={styles["withdrawals__table-wrapper"]}>
          {/* Header */}
          <div className={styles["withdrawals__table"]}>
            <span>Client Name</span>
            <span>Email Address</span>
            <span>Amount</span>
            <span>Status</span>
            <span>Created At</span>
            <span>Details</span>
            <span>Action</span>
          </div>

          {/* Table Body */}
          <div className={styles["withdrawals__children"]}>
            {loading ? (
              <TableSkeleton />
            ) : withdrawals?.data?.length === 0 ? (
              <NoResults
                title="No Withdrawals Record"
                description="Oops! It seems like there are no withdrawals records at the moment"
              />
            ) : (
              withdrawals?.data?.map((withdrawal: any) => (
                <div
                  key={withdrawal.id}
                  className={styles["withdrawals__children--item"]}
                >
                  <span>{withdrawal.meta?.user_name}</span>
                  <span>{truncateEmail(withdrawal.meta?.user_email)}</span>
                  <span>{currency?.currency_symbol}{formatMoneyComplete(withdrawal.amount)}</span>
                  <span
                    className={
                      withdrawal.status === "success"
                        ? styles["withdrawals__children--item--processed"]
                        : styles["withdrawals__children--item--pending"]
                    }
                  >
                    {withdrawal.status === "success" ? "Processed" : "Pending"}
                  </span>
                  <span>{formatDate(withdrawal.created_at)}</span>
                  <span>
                      <button
                        onClick={() =>
                          toggleDetailsModal(withdrawal)
                        }
                        className={styles.actionButtonView}
                      >
                        View Details
                      </button>
                    </span>
                  <span className={styles["withdrawals__children--item--actions"]}>
                    {withdrawal.status === "pending" ? (
                      <button
                        onClick={() =>
                          toggleProcessWithdrawalModal(withdrawal)
                        }
                        className={styles["actionButtonProcess"]}
                      >
                        Process Now
                      </button>
                    ) : (
                      <button
                        disabled
                        className={styles["actionButtonProcessed"]}
                      >
                        Processed
                      </button>
                    )}
                  </span>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
        {/* Pagination */}
        <div className={styles["attend__pagination"]}>
          {withdrawals?.data?.length > 0 && withdrawals?.links?.length > 0 && (
            <Pagination links={withdrawals.links} onChange={handlePageChange} />
          )}
        </div>
      </div>
    </>
  )
}

Withdrawals.layout = (page: React.ReactNode) => (
  <AdminDashboardLayout title="Manage Withdrawals" children={page} />
)

export default Withdrawals
