import { Alert, Container, DataGridInner } from '@/components';
import { TransactionTopupProvider } from './hooks/TransactionTopupContext';
import { Breadcrumbs, Link } from '@mui/material';
import { Helmet } from 'react-helmet';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import React, { useState, useEffect } 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 TransactionTopup = () => {
  const initialState: {
    topupAmount: string;
    pin: string;
  } = {
    topupAmount: '',
    pin: ''
  };

  const [form, setForm] = useState(initialState);
  const [alert, setAlert] = useState({
    show: false,
    message: ''
  });

  const [wallets, setWallets] = useState([]);
  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;

  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 doPostData = async (form: typeof initialState) => {
    setIsSubmitting(true);

    try {
      let response = await PostData(`${API_URL}/transaction/request-topup`, {
        amount: form.topupAmount,
        pin: form.pin
      });
      console.log(response);
      if (response?.status == true) {
        toast.success('Success Request Topup');
      } else {
        toast.warning(`${response?.message}`);
      }
    } catch (error: any) {
      const errorMessage =
        error?.response?.data?.message || error?.message || 'Something went wrong';
      toast.error(errorMessage);
    } finally {
      setIsSubmitting(false);
      setShowConfirmation(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // console.log('Submitted Data:', form);

    if (form.pin == '' || form.topupAmount == '') {
      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 handleCancelSubmit = () => {
    setShowConfirmation(false);
  };

  return (
    <>
      <Helmet>
        <title>TPAY | Transaction Topup Request</title>
      </Helmet>
      <TransactionTopupProvider>
        <Container className="mb-7">
          <h1 className="text-xl font-medium leading-none text-gray-900 mb-5">
            MANAGE TRANSACTION TOPUP REQUEST
          </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">Topup</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">
                {alert.show && (
                  <Alert variant="danger">
                    <h3>{alert.message}</h3>
                  </Alert>
                )}
                {/* form */}
                <form onSubmit={handleSubmit} className="space-y-6 mt-5">
                  <div>
                    <label htmlFor="topupAmount">Topup Amount</label>
                    <span className="text-red-500">*</span>
                    <Input
                      id="topupAmount"
                      type="number"
                      value={form.topupAmount}
                      onChange={(e) => setForm({ ...form, topupAmount: 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="button" onClick={handleSubmit}>
                      Submit
                    </Button>
                  </div>
                </form>
              </div>
            </div>
          </Container>
          {showConfirmation && (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
              <div className="bg-white p-6 rounded-lg shadow-lg max-w-md w-full">
                <h3 className="text-lg font-semibold mb-4">Confirm Transaction</h3>
                <p className="mb-6">
                  Are you sure you want to request a topup of{' '}
                  <span className="font-semibold">
                    {new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(
                      Number(form.topupAmount)
                    )}{' '}
                  </span>{' '}
                  ?
                </p>
                <div className="flex justify-end space-x-3">
                  <Button
                    variant="outline"
                    onClick={handleCancelSubmit}
                    className="border-gray-300 text-gray-700"
                  >
                    Cancel
                  </Button>
                  <Button onClick={() => doPostData(form)} disabled={isSubmitting}>
                    {isSubmitting ? (
                      <RefreshCw className="animate-spin h-8 w-8 text-white mx-3" />
                    ) : (
                      'Confirm'
                    )}
                  </Button>
                </div>
              </div>
            </div>
          )}
        </Container>
      </TransactionTopupProvider>
    </>
  );
};

export default TransactionTopup;
