
import React, { useEffect, useRef, useState } from "react";
import { IoCopyOutline } from "react-icons/io5";
import wp from '/assets/whatsapplogo.png'
import { RiWhatsappLine } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import { userchatlist, depositRequest, customerDetails, getPromotionsOffer } from "../../redux/_reducers/_reducers";

import moment from "moment";
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';


import { CONST } from "../../config/Const";
import { httpPostFormData } from "../../config/HTTP";
import Loader from "../../component/Loader/Loader";


function Deposit() {

    const [Isdeposit, Setdeposit] = useState(0);
    const [imgData, SetImgData] = useState();
    const [defaultAllData, setDefaultAllData] = useState()
    const [utrNumber, setUtrNumber] = useState("");
    const [paymentProof, setPaymentProof] = useState(null);
    const [amount, setAmount] = useState("");
    const [bonusId, setbonusId] = useState("0")

    const [iconClicked, setIconClicked] = useState(false);
    const [copySuccess, setCopySuccess] = useState('');
    // const [loading, setLoading] = useState(false)
    const [utrError, setUtrError] = useState('');
    const [depositError, setDepositError] = useState('');
    const [paymentProofError, setPaymentProofError] = useState('');
    const [amountError, setAmountError] = useState('');
    const dispatch = useDispatch();
    const fileInputRef = useRef(null);
    const handleUtrChange = (e) => setUtrNumber(e.target.value);
    const handleAmountChange = (e) => setAmount(e.target.value);
    const { defaultSettingData, customerDetailsData, userchatlistData, loading, getPromotionsData } = useSelector((state) => state.authentication);
    console.log(getPromotionsData, "getPromotionsData");

    useEffect(() => {
        dispatch(getPromotionsOffer())
    }, []);


    const DepositClick = (index) => {
        Setdeposit(index);
        setUtrNumber("");
        setAmount("");
        setPaymentProof('');
    };

    const handlePaymentProofChange = (e) => {
        setPaymentProof('')
        const uploadedFile = e.target.files[0];
        setPaymentProof(uploadedFile);
        if (uploadedFile) {
            uploadFileToServer(uploadedFile);
        }
    };

    const handleCopy = (bank_name) => {
        navigator.clipboard.writeText(bank_name)
            .then(() => {
                setIconClicked(true); toast.success('Copied', { autoClose: 2000 });
            })
            .catch(() => {
                setCopySuccess('Failed to copy text.'); toast.error('Failed to copy text.', { autoClose: 2000 });
            });
    };


    const uploadFileToServer = async (file) => {
        if (file) {
            const formData = new FormData();

            formData.append('deposite', file);
            try {
                let fileData = await httpPostFormData('uploadDepositeFile', formData);
                if (fileData && fileData.message) {
                    toast.success(fileData.message);
                    SetImgData(fileData?.data?.attachment)
                }
            } catch (error) {
                console.error('Error uploading file:', error);
            }
        } else {
            const errorMessage = 'Please select a valid file.';
            this.setState({ errorMessage });
        }
    }

    const customerData = () => {
        const payload = { "type": "D" };
        dispatch(customerDetails(payload));
    }

    const userChatListData = () => {

        const data = {
            "limit": 15,
            "page": 1,
            "status": "AL",
            "type": "D"
        };
        dispatch(userchatlist(data));
    }

    useEffect(() => {
        userChatListData();
        customerData();
    }, [dispatch]);


    useEffect(() => {
        if (defaultSettingData) {
            setDefaultAllData(defaultSettingData);
        }
    }, [defaultSettingData]);



    const whatsappData = defaultAllData?.find((item) => item.key === "site.whatsapp");

    const handleSubmit = async (element) => {
        setUtrError('');
        setPaymentProofError('');
        setAmountError('');
        setDepositError('');

        let isValid = true;

        if (!utrNumber) {
            setUtrError('Please enter a valid UTR number.');
            isValid = false;
        }
        else if (utrNumber.length < 6 || utrNumber.length > 12) {
            setUtrError('UTR number must be between 6 to 12 digits.');
            isValid = false;
        }

        if (!paymentProof) {
            setPaymentProofError('Please upload your payment proof.');
            isValid = false;
        }

        if (Number(amount) < 100) {
            setAmountError('Amount must be at least 100.');
            isValid = false;
        }

        // if (!depositError) {
        //     setDepositError('Please select deposit type.');
        //     isValid = false;
        // }

        if (!isValid) {
            return;
        }
        // setLoading(true)
        const data = {
            "amount": Number(amount),
            "account_number": element?.account_phone_number,
            "ifsc": element?.account_ifsc_code,
            "account_name": element?.account_holder_name,
            "type": "D",
            "user_id": 20,
            "transaction_id": utrNumber,
            "sender": "",
            "reciver": "",
            "dwtype": "D",
            "method": element.account_type,
            "attachment": imgData,
            "bonusId": bonusId,
        }
        try {
            await dispatch(depositRequest(data));
            userChatListData();

            if (fileInputRef.current) {
                fileInputRef.current.value = null;
            }

        } catch (error) {
            console.error("API call failed", error);
            toast.error("Submission failed. Please try again.");
        }
        // setLoading(false)
        setUtrNumber("");
        setAmount("");
        setPaymentProof('');
    };

    const handleSelectChange = (e) => {
        e.preventDefault();
        console.log("selected value", e.target.value);

        setbonusId(e.target.value);
    }

    return (
        <div className="overflow-y-auto p-1 bg-[#f5f5f5]">
            {loading && <Loader />}
            <section>
                <div className="w-full">
                    {/* <div className="lg:w-9/12 w-full mt-3"> */}
                    <div className="row mx-0">
                        <div className="col-12 px-2 scoretabcontent-work shadow-none d-flex flex-column flex-sm-row align-items-start pb-2">
                            <div className="tabs w-100 mt-2">
                                <div className=" py-4 px-2 shadow bg-white w-full">
                                    <div className="border-l-4 border-l-[var(--primary)] text-left px-2 border-b border-b-black">Payment Method</div>
                                    <div className="grid grid-cols-3 py-5 gap-2 rounded w-full mx-auto">
                                        <Link to={whatsappData?.value} className=" cursor-pointer rounded-lg text-center px-2 flex flex-col justify-center items-center border text-black">
                                            <div className="uppercase font-[600] text-[10px] ">WHATSAPP DEPOSIT</div>
                                            <img src={wp} alt="WhatsApp Deposit" className="w-[35px] h-[35px]" />
                                        </Link>

                                        {customerDetailsData && customerDetailsData?.length > 0 ? customerDetailsData?.map((element, index) => (
                                            <div
                                                key={index}
                                                onClick={() => DepositClick(index)}
                                                className={`cursor-pointer px-5 py-2 rounded-lg text-[12px] text-center ${Isdeposit === index ? 'bg-[var(--light-header)] text-white' : 'bg-white border'}`}>
                                                {element.account_type === "IMPS" ? (
                                                    <>
                                                        <h4 className="uppercase font-[600]">Account</h4>
                                                        <img src="/assets/bank-account.png" alt="Bank Account" className="mx-auto w-[45px] h-[45px]" />
                                                    </>
                                                ) : (
                                                    <>
                                                        <h4 className="uppercase font-[700]">UPI</h4>
                                                        <img src="/assets/upi-icon.png" alt="UPI Icon" className="mx-auto w-[45px] h-[45px]" />
                                                    </>
                                                )}
                                            </div>
                                        )) : null}
                                    </div>
                                </div>
                                {customerDetailsData && customerDetailsData.length > 0 ? customerDetailsData.map((element, index) => (
                                    <div key={index} className="tab-content mt-4 shadow bg-white w-full py-2">
                                        {Isdeposit === index &&
                                            <div>
                                                {element.account_type === "IMPS" ?
                                                    <>
                                                        <div className="">
                                                            <div className='depositbank bg-white p-5 shadow-md rounded'>
                                                                <h3 className="text-lg font-semibold mb-4 text-center">BANK ACCOUNT</h3>
                                                                <div className=''>
                                                                    <div className="w-full">
                                                                        <div className="bg-[#f3f2f6] shadow-md rounded-lg p-4">
                                                                            <ul className="space-y-3">
                                                                                {[
                                                                                    { label: "Bank Name", value: element?.bank_name },
                                                                                    { label: "A/C Number", value: element?.account_phone_number },
                                                                                    { label: "IFSC Code", value: element?.account_ifsc_code },
                                                                                    { label: "Account Name", value: element?.account_holder_name },
                                                                                    { label: "Min Amount", value: element?.min_diposit },
                                                                                    { label: "Max Amount", value: element?.max_diposit },
                                                                                ].map((item, index) => (
                                                                                    <li key={index} className="flex justify-between items-center border-b pb-2">
                                                                                        <div className="flex items-center space-x-2">
                                                                                            <span className="font-semibold">{item.label}:</span>
                                                                                            <span className="text-gray-700">{item.value}</span>
                                                                                        </div>
                                                                                        <button onClick={() => handleCopy(item.value)} className="text-gray-500 hover:text-black">
                                                                                            <IoCopyOutline />
                                                                                        </button>
                                                                                    </li>
                                                                                ))}
                                                                            </ul>
                                                                            {copySuccess && <p className="text-green-600 text-center mt-2">{copySuccess}</p>}
                                                                        </div>
                                                                        <div className="mt-4 text-center">
                                                                            <Link
                                                                                to={whatsappData?.value}
                                                                                className="flex flex-col items-center hover:bg-green-600 bg-[#64cc2f] text-white py-2 px-4 rounded-lg shadow-lg w-full transition-all"
                                                                            >
                                                                                FOR PAYMENT RELATED ISSUES
                                                                                <span className="text-2xl animate-bounce mt-1">
                                                                                    <RiWhatsappLine />
                                                                                </span>
                                                                            </Link>
                                                                        </div>
                                                                    </div>
                                                                    <div className="w-full mt-6 lg:mt-4">
                                                                        <div className="bg-white lg:px-4 text-[13px] text-black font-[500]">

                                                                            <div className="flex flex-col gap-2 mb-4">
                                                                                <label className="text-[#525252] text-left">Select Promotion <span className="text-red-500">*</span></label>
                                                                                <select
                                                                                    // value={offer_percentage}
                                                                                    onChange={handleSelectChange}
                                                                                    className="w-full px-3 py-2 border !bg-white border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer">
                                                                                    <option value="0">Default Deposit</option>
                                                                                    {getPromotionsData?.map((item, index) => (
                                                                                        // <option value="">Select</option>
                                                                                        <option key={index} value={item?.id}>
                                                                                            {item?.offer_percentage}% ({item?.sub_title})
                                                                                        </option>
                                                                                    ))}
                                                                                </select>
                                                                                {/* {depositError && <span className="text-red-500 text-sm">{depositError}</span>} */}
                                                                            </div>

                                                                            <div className="mb-4">
                                                                                <label className="block text-left">
                                                                                    Unique Transaction Reference <span className="text-red-500">*</span>
                                                                                </label>
                                                                                <input
                                                                                    type="text"
                                                                                    value={utrNumber}
                                                                                    onChange={handleUtrChange}
                                                                                    placeholder="6 to 12 Digits UTR Number"
                                                                                    className="!bg-white w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                                                                />
                                                                                {utrError && <span className="text-red-500 text-sm">{utrError}</span>}
                                                                            </div>
                                                                            <div className="mb-4">
                                                                                <label className="block text-left">
                                                                                    Upload Your Payment Proof <span className="text-red-500">[Required]</span>
                                                                                </label>
                                                                                <input
                                                                                    ref={fileInputRef}
                                                                                    onChange={handlePaymentProofChange}
                                                                                    type="file"
                                                                                    className="!bg-white w-full px-3 py-2 border border-gray-300 rounded-md cursor-pointer"
                                                                                />
                                                                                {paymentProofError && <span className="text-red-500 text-sm">{paymentProofError}</span>}
                                                                            </div>
                                                                            <div className="mb-4">
                                                                                <label className="block text-left">
                                                                                    Amount <span className="text-red-500">*</span>
                                                                                </label>
                                                                                <input
                                                                                    type="number"
                                                                                    value={amount}
                                                                                    onChange={handleAmountChange}
                                                                                    placeholder="Please Enter Minimum 100 Rs."
                                                                                    className="!bg-white w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                                                                />
                                                                                {amountError && <span className="text-red-500 text-sm">{amountError}</span>}
                                                                            </div>
                                                                            <div className="text-center">
                                                                                <button
                                                                                    onClick={() => handleSubmit(element)}
                                                                                    className="bg-[var(--light-header)] text-white font-semibold px-6 w-full py-2.5 rounded transition-all"
                                                                                >
                                                                                    SUBMIT
                                                                                </button>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div>
                                                            <ul className="bg-white p-5 text-[11px] mt-3 text-left rounded">
                                                                <li className="list">1.  Deposit money only in the below available accounts to get the fastest credits and avoid possible delays. </li>
                                                                <li className="list">2.Deposits made 45 minutes after the account removal from the site are valid & will be added to their wallets.</li>
                                                                <li className="list">3. Site is not responsible for money deposited to Old, Inactive or Closed accounts.</li>
                                                                <li className="list">4. After deposit, add your UTR and amount to receive balance.</li>
                                                                <li className="list">5 .NEFT receiving time varies from 40 minutes to 2 hours.</li>
                                                                <li className="list">6. In case of account modification: payment valid for 1 hour after changing account details in deposit page.</li>
                                                            </ul>
                                                        </div>
                                                    </> : <>
                                                        <div className="depositbank bg-white shadow-md rounded py-4 px-3">
                                                            <h3 className="text-lg font-semibold mb-4 text-center">UPI</h3>
                                                            <div className="">
                                                                <div className="w-full">
                                                                    <div className="bg-[#f3f2f6] shadow-md rounded-lg p-4">
                                                                        <ul className="space-y-3">
                                                                            {[
                                                                                { label: "Name", value: element?.account_holder_name },
                                                                                { label: "UPI ID", value: element?.upi_id },
                                                                                { label: "Min Amount", value: element?.min_diposit },
                                                                                { label: "Max Amount", value: element?.max_diposit },
                                                                            ].map((item, index) => (
                                                                                <li key={index} className="flex justify-between items-center border-b pb-2">
                                                                                    <div className="flex items-center space-x-2">
                                                                                        <span className="font-semibold">{item.label}:</span>
                                                                                        <span className="text-gray-700">{item.value}</span>
                                                                                    </div>
                                                                                    <button onClick={() => handleCopy(item.value)} className="text-gray-500 hover:text-black">
                                                                                        <IoCopyOutline />
                                                                                    </button>
                                                                                </li>
                                                                            ))}
                                                                        </ul>
                                                                        {copySuccess && <p className="text-green-600 text-center mt-2">{copySuccess}</p>}
                                                                        {element?.attachment && (
                                                                            <div className="flex justify-center mt-4">
                                                                                <img src={`${CONST.PAYMENT_URL}${element?.attachment}`} alt="QR Code" className="w-40 h-40 object-contain" />
                                                                            </div>
                                                                        )}
                                                                    </div>
                                                                    <div className="mt-4 text-center">
                                                                        <Link
                                                                            to={whatsappData?.value}
                                                                            className="flex flex-col items-center hover:bg-green-600 bg-[#64cc2f] text-white py-2 px-4 rounded-lg shadow-lg w-full transition-all"
                                                                        >
                                                                            FOR PAYMENT RELATED ISSUES
                                                                            <span className="text-2xl animate-bounce mt-1">
                                                                                <RiWhatsappLine />
                                                                            </span>
                                                                        </Link>
                                                                    </div>
                                                                </div>
                                                                <div className="w-full mt-6 lg:mt-4">
                                                                    <div className="bg-white lg:px-4 text-[13px] text-black font-[500]">
                                                                        <div className="flex flex-col gap-2 mb-4">
                                                                            <label className="text-[#525252] text-left">Select Promotion <span className="text-red-500">*</span></label>
                                                                            <select
                                                                                // value={offer_percentage}
                                                                                onChange={handleSelectChange}
                                                                                className="!bg-white w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer">
                                                                                <option value="0">Default Deposit</option>
                                                                                {getPromotionsData?.map((item, index) => (
                                                                                    <option key={index} value={item?.id}>
                                                                                        {item?.offer_percentage}% ({item?.sub_title})
                                                                                    </option>
                                                                                ))}
                                                                            </select>
                                                                            {/* {depositError && <span className="text-red-500 text-sm">{depositError}</span>} */}
                                                                        </div>
                                                                        <div className="mb-4">
                                                                            <label className="block text-left">
                                                                                Unique Transaction Reference <span className="text-red-500">*</span>
                                                                            </label>
                                                                            <input
                                                                                type="text"
                                                                                value={utrNumber}
                                                                                onChange={handleUtrChange}
                                                                                placeholder="6 to 12 Digits UTR Number"
                                                                                className="!bg-white w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                                                            />
                                                                            {utrError && <span className="text-red-500 text-sm">{utrError}</span>}
                                                                        </div>
                                                                        <div className="mb-4">
                                                                            <label className="block text-left">
                                                                                Upload Your Payment Proof <span className="text-red-500">[Required]</span>
                                                                            </label>
                                                                            <input
                                                                                onChange={handlePaymentProofChange}
                                                                                type="file"
                                                                                className="!bg-white w-full px-3 py-2 border border-gray-300 rounded-md cursor-pointer"
                                                                            />
                                                                            {paymentProofError && <span className="text-red-500 text-sm">{paymentProofError}</span>}
                                                                        </div>
                                                                        <div className="mb-4">
                                                                            <label className="block text-left">
                                                                                Amount <span className="text-red-500">*</span>
                                                                            </label>
                                                                            <input
                                                                                type="number"
                                                                                value={amount}
                                                                                onChange={handleAmountChange}
                                                                                placeholder="Please Enter Minimum 100 Rs."
                                                                                className="!bg-white w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                                                                            />
                                                                            {amountError && <span className="text-red-500 text-sm">{amountError}</span>}
                                                                        </div>
                                                                        <div className="text-center">
                                                                            <button
                                                                                onClick={() => handleSubmit(element)}
                                                                                className="bg-[var(--light-header)] text-white font-semibold px-6 py-2.5 rounded transition-all w-full"
                                                                            >
                                                                                SUBMIT
                                                                            </button>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div>
                                                            <ul className="bg-white p-5 text-[11px] mt-3 rounded text-left">
                                                                <li className="list">1.  Deposit money only in the below available accounts to get the fastest credits and avoid possible delays. </li>
                                                                <li className="list">2.Deposits made 45 minutes after the account removal from the site are valid & will be added to their wallets.</li>
                                                                <li className="list">3. Site is not responsible for money deposited to Old, Inactive or Closed accounts.</li>
                                                                <li className="list">4. After deposit, add your UTR and amount to receive balance.</li>
                                                                <li className="list">5 .NEFT receiving time varies from 40 minutes to 2 hours.</li>
                                                                <li className="list">6. In case of account modification: payment valid for 1 hour after changing account details in deposit page.</li>
                                                            </ul>
                                                        </div>
                                                    </>}
                                            </div>}
                                    </div>)) : null}
                            </div>
                        </div>
                    </div>
                    {/* </div> */}
                    {/* <div className="lg:w-1/4 w-full mt-3 lg:pr-0 bg-white"> */}
                    <div className="w-full">
                        <div className="bg-white shadow-md overflow-hidden">
                            <div className="overflow-y-auto h-full">
                                <table className="w-full border border-[#96c6ef]">
                                    <thead>
                                        <tr className="bg-[#96c6ef] text-black text-center text-nowrap">
                                            <th className="p-2">Transaction No.</th>
                                            <th>Amount</th>
                                            <th>Status</th>
                                            <th>Date</th>
                                            <th>Reason</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        {userchatlistData && userchatlistData?.length > 0 ? userchatlistData?.map((element, index) => (
                                            <tr key={index} className="bg-gray-100 text-center">
                                                <td className="px-2 py-2">{element.UTR}</td>
                                                <td className="px-2 py-2">{element.amount}</td>
                                                <td className="px-2 py-2">
                                                    <div className={`m-2 px-2 py-1 border-2 rounded text-black ${element.status === "D" ? "border-red-500" :
                                                        element.status === "S" ? "border-green-500" :
                                                            element.status === "A" ? "border-blue-500" :
                                                                "border-red-500"
                                                        }`}
                                                    >
                                                        {element.status === "D" ? "Decline" :
                                                            element.status === "S" ? "Success" :
                                                                element.status === "A" ? "Approve" : "Pending"}
                                                    </div>
                                                </td>
                                                <td className="px-2 py-2">{moment.unix(element.created_at).format("DD-MM-YYYY HH:MM:SS A")}</td>
                                                <td className="px-2 py-2">{element.reason ? element.reason : "-"}</td>
                                            </tr>
                                        )) : null}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    {/* </div> */}
                </div>
            </section>
        </div>
    )
}

export default Deposit;