import { Container, DataGridInner } from '@/components';
import { TransactionDisbursementProvider } from './hooks/TransactionDisbursementContext';
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 } from 'react';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
import { toast } from 'sonner';
import { getAuth } from '@/auth';

const TransactionDisbursement = () => {
  const [form, setForm] = useState({
    msisdn: '',
    amount: '',
    pin: ''
  });
  const [wallets, setWallets] = useState([]);
  const { GetData, PostData } = useCallApi();
  const parsedUser = getAuth()?.user;
  const API_URL = apiConfig.transaction;
  const API_URL_WALLET = apiConfig.service_wallet

  useEffect(() => {
    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');
      }
    };

    fetchWallets();
  }, []);

  const handleSubmit = async (e: any) => {
    e.preventDefault();
    console.log('Submitted Data:', form);
    if (form.amount == '' || form.msisdn == '' || form.pin == '') {
      toast.warning('Please fill in all required fields.')
      return
    }
    try {
      let requestTopup = await PostData(`${API_URL}/transaction/topup-downline`, {
        msisdn_destination: form.msisdn,
        amount: form.amount,
        pin: form.pin
      })
      if (requestTopup?.status == true) {
        toast.success('Success Request Topup')
      } else {
        toast.warning(`${requestTopup?.message}`)
      }
    } catch (error) {
      toast.warning('Failed')
    }
    // TODO: Kirim ke backend atau proses lainnya
  };

  return (
    <>
      <Helmet>
        <title>TPAY | Transaction Disbursement Saldo</title>
      </Helmet>
      <TransactionDisbursementProvider>
        <Container className="mb-7">
          <h1 className="text-xl font-medium leading-none text-gray-900 mb-5">MANAGE TRANSACTION DISBURSEMENT SALDO</h1>
          <Breadcrumbs sx={{ mb: 2 }}>
            <Link underline="none" color="inherit" href="/">
              <span className="text-sm hover:underline">Dashboard</span>
            </Link>
            <Link underline="none" color="inherit">
              <span className="text-sm">Transaction</span>
            </Link>
            <Link underline="none" color="inherit">
              <span className="text-sm">Disbursement Saldo</span>
            </Link>
          </Breadcrumbs>
          {/* Wallet Section */}
          <div className="mb-6">
            <h2 className="text-md font-semibold text-gray-700 mb-3">Your Wallets</h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              {wallets.map((wallet: any) => (
                <div key={wallet.id_wallet} className="border rounded-lg p-4 bg-white">
                  <p className="text-sm text-gray-500">{wallet.wallet}</p>
                  <p className="text-lg font-semibold text-green-600">
                    {new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(wallet.amount)}
                  </p>
                </div>
              ))}
            </div>
          </div>
          <Container className="flex items-center justify-center">
            <div className="card max-w-[750px] w-full">
              <div className="card-body p-10">
                {/* form */}
                <form onSubmit={handleSubmit} className="space-y-6">
                <div>
                  <label htmlFor="msisdn">Destination MSISDN</label><span className="text-red-500">*</span>
                  <Input
                    id="msisdn"
                    type="number"
                    value={form.msisdn}
                    onChange={(e) => setForm({ ...form, msisdn: e.target.value })}
                  />
                </div>
                <div>
                  <label htmlFor="amount">Amount</label><span className="text-red-500">*</span>
                  <Input
                    id="amount"
                    type="number"
                    value={form.amount}
                    onChange={(e) => setForm({ ...form, amount: e.target.value })}
                  />
                </div>
                <div>
                  <label htmlFor="pin">PIN</label><span className="text-red-500">*</span>
                  <Input
                    id="pin"
                    type="password"
                    value={form.pin}
                    onChange={(e) => setForm({ ...form, pin: e.target.value })}
                  />
                </div>
                <div>
                  <Button type="submit">Submit</Button>
                </div>
              </form>
              </div>
            </div>
          </Container>
        </Container>
      </TransactionDisbursementProvider>
    </>
  );
};

export default TransactionDisbursement;
