import { Alert, Container, DataGridInner } from '@/components'; import { TransactionWithdrawProvider } from './hooks/TransactionWithdrawContext'; import { Breadcrumbs, Link } from '@mui/material'; import { Helmet } from 'react-helmet'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; import { useState, useEffect, useRef } from 'react'; import { useCallApi } from '@/hooks'; import { apiConfig } from '@/config/api.config'; import { toast } from 'sonner'; import { getAuth } from '@/auth'; import { RefreshCw } from 'lucide-react'; const TransactionWithdraw = () => { const initialForm: { msisdn: string; amount: string; pin: string; purpose: string; } = { msisdn: '', amount: '', pin: '', purpose: '' }; const [form, setForm] = useState(initialForm); const [wallets, setWallets] = useState([]); const [isLoading, setIsLoading] = useState(false); const [customerMsisdn, setCustomerMsisdn] = useState<{ value: string; label: string }[]>([]); const [searchTerm, setSearchTerm] = useState(''); const [dropdownOpen, setDropdownOpen] = useState(false); const { GetData, PostData } = useCallApi(); const [isSubmitting, setIsSubmitting] = useState(false); const [showConfirmation, setShowConfirmation] = useState(false); const parsedUser = getAuth()?.user; const API_URL = apiConfig.transaction; const API_URL_WALLET = apiConfig.service_wallet; const API_URL_CUSTOMER = apiConfig.service_customer; const dropdownRef = useRef(null); const [alert, setAlert] = useState({ show: false, message: '' }); const fetchWallets = async () => { try { const response = await GetData( `${API_URL_WALLET}/dashboard/balance/account/${parsedUser.customer.id}`, {} ); if (response?.status === true) { setWallets(response.data || []); } else { toast.warning(response?.message || 'Failed to fetch wallet data'); } } catch (error) { toast.warning('Failed to fetch wallet data'); } }; const fetchCustomerMsisdn = async (sorting: any, filterValue: string) => { const filter: any = filterValue.trim().length === 0 ? {} : { or: [ { msisdn: { like: `%${filterValue}%` } }, { fullname: { like: `%${filterValue}%` } } ] }; const query: any = { limit: 100, page: 1, with_deleted: false, order_field: sorting[0].id, order_direction: sorting[0].desc ? 'DESC' : 'ASC' }; if (filter && Object.keys(filter).length > 0) { query.filter = JSON.stringify(filter); // query.page = page + 1; } try { const response = await GetData(`${API_URL_CUSTOMER}/customer/list`, query); setCustomerMsisdn( response?.data.list.map((item: any) => ({ value: item.msisdn, label: `${item.msisdn} - ${item.fullname}` })) ); } catch (error) { toast.error('Failed to fetch customer msisdn'); } finally { setIsLoading(false); } }; const doPostData = async (form: typeof initialForm) => { setIsSubmitting(true); try { let response = await PostData(`${API_URL}/transaction/transfer`, { msisdn_destination: form.msisdn, amount: form.amount, pin: form.pin, purpose: form.purpose, id_transaction_type: "20c8a690-dc02-463d-b391-324184d1fefa", id_origin_customer: getAuth()?.id, type:"S" }); if (response?.status == true) { await fetchWallets(); toast.success('Success Request Topup'); } else { toast.error(`${response?.message?.message}`); } } catch (error: any) { const errorMessage = error?.response?.data?.message || error?.message || 'Something went wrong'; toast.error(errorMessage); setAlert({ show: true, message: errorMessage }); } finally { setIsSubmitting(false); setShowConfirmation(false); ResetForm(); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (form.amount == '' || form.msisdn == '' || form.pin == '') { setAlert({ show: true, message: 'Please fill in all required fields.' }); return; } setAlert({ show: false, message: '' }); setShowConfirmation(true); // TODO: Kirim ke backend atau proses lainnya }; const ResetForm = () => { setForm(initialForm); setAlert({ show: false, message: '' }); setSearchTerm(''); }; const handleCancelSubmit = () => { setShowConfirmation(false); }; const handleMsisdnSearch = (e: React.ChangeEvent) => { setIsLoading(true); setSearchTerm(e.target.value); setDropdownOpen(true); const timer = setTimeout(() => { fetchCustomerMsisdn([{ id: 'msisdn', desc: false }], e.target.value); }, 500); return () => clearTimeout(timer); }; const handleMsisdnSelect = (msisdn: string) => { setForm({ ...form, msisdn }); setDropdownOpen(false); setSearchTerm(msisdn); }; useEffect(() => { fetchWallets(); fetchCustomerMsisdn([{ id: 'msisdn', desc: false }], ''); const handleClickOutside = (event: any) => { if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { setDropdownOpen(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, []); const filteredMsisdn = customerMsisdn .filter((item) => item.label.toLowerCase().includes(searchTerm.toLowerCase())) .slice(0, 10); return ( <> TPAY | Transaction Withdraw Saldo

MANAGE TRANSACTION WITHDRAW SALDO

Dashboard Transaction Withdraw Saldo {/* Wallet Section */}

Your Wallets

{wallets.map((wallet: any) => (

{wallet.wallet}

{new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format( wallet.amount )}

))}
{alert.show && (

{alert.message}

)} {/* form */}
*
setDropdownOpen(true)} /> {dropdownOpen && (
{filteredMsisdn.length > 0 ? ( filteredMsisdn.map((item, index) => (
handleMsisdnSelect(item.value)} > {item.label}
)) ) : (
{isLoading ? 'Loading...' : 'No results found'}
)}
)}
* { const value = Number(e.target.value); if (value >= 0) { setForm({ ...form, amount: String(value) }); } }} />
* setForm({ ...form, pin: e.target.value })} />
* setForm({ ...form, purpose: e.target.value })} />
{showConfirmation && (

Confirm Transaction

Are you sure you want to withdraw saldo of{' '} {new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format( Number(form.amount) )}{' '} ?

)}
); }; export default TransactionWithdraw;