"use client";

import React, { useEffect, useRef, useState } from "react";
import { Button, Center, Divider, Group, List, Modal, Paper, PasswordInput, Radio, ScrollArea, Select, Stack, Text, TextInput, ThemeIcon, Title } from "@mantine/core";
import { notifications } from "@mantine/notifications";
import { useRouter } from "next/navigation";
import { IconAlertTriangle, IconRefresh } from "@tabler/icons-react";
import Image from "next/image";
import img from '@/app/image/logo1.jpg'
import { sendOtp, verifyOtp } from "@/app/_util/otp";
import { getDailyLimit } from "@/app/_util/transactionLimit";


interface accountData {
    stAccountNo: string;
    stAccountType: string;
    stAvailableBalance: string;
    custname: string;
}
export default function SendToBeneficiaryOthers() {
    const router = useRouter();
    const [authorized, setAuthorized] = useState<boolean | null>(null);
    const [accountData, setAccountData] = useState<accountData[]>([]);
    const [beneficiaryData, setBeneficiaryData] = useState<any[]>([]);
    const [showIntroModal, setShowIntroModal] = useState(true);
    const [selectedAccNo, setSelectedAccNo] = useState<string | null>(null);
    const [beneficiaryAcc, setBeneficiaryAcc] = useState<string | null>(null);
    const [beneficiaryName, setBeneficiaryName] = useState<string | null>(null);
    const [beneficiaryIFSC, setBeneficiaryIFSC] = useState<string | null>(null);
    const [paymentMode, setPaymentMode] = useState('IMPS');
    const [isVisibilityLocked, setIsVisibilityLocked] = useState(false);
    const [amount, setAmount] = useState("");
    const [remarks, setRemarks] = useState("");
    const [showConfirmModel, setConfirmModel] = useState(false);
    const [showTxnPassword, setShowTxnPassword] = useState(false);
    const [txnPassword, setTxnPassword] = useState("");
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [showOtpField, setShowOtpField] = useState(false);
    const [otp, setOtp] = useState("");
    const [countdown, setCountdown] = useState(180);
    const [timerActive, setTimerActive] = useState(false);
    const [dailyLimit, setDailyLimit] = useState<number | null>(null);
    const [usedLimit, setUsedLimit] = useState<number | null>(null);

    const FetchDailyLimit = async () => {
        try {
            const token = localStorage.getItem("access_token");
            if (!token) return;
            const data = await getDailyLimit(token);
            if (data) {
                setDailyLimit(data.dailyLimit);
                setUsedLimit(data.usedLimit);
            } else {
                setDailyLimit(null);
                setUsedLimit(null);
            }
        } catch {
            setDailyLimit(null);
            setUsedLimit(null);
        }
    };

    async function handleSendOtp() {
        const mobileNumber = localStorage.getItem('remitter_mobile_no');
        if (!mobileNumber) {
            notifications.show({
                title: 'Error',
                message: 'Mobile number not found.Contact to administrator',
                color: 'red',
            });
            return;
        }
        try {
            if (paymentMode === "IMPS") { await sendOtp({ type: 'IMPS' }); }
            if (paymentMode === "RTGS") {
                await sendOtp(
                    {
                        type: 'RTGS',
                        amount: amount ? Number(amount) : undefined,
                        beneficiary: beneficiaryName || undefined
                    });
            }
            if (paymentMode === "NEFT") {
                await sendOtp(
                    {
                        type: 'NEFT',
                        amount: amount ? Number(amount) : undefined,
                        beneficiary: beneficiaryName || undefined
                    });
            }
            setShowOtpField(true);
            setCountdown(180);
            setTimerActive(true);
        } catch (err: any) {
            notifications.show({
                title: 'Error',
                message: err.message || 'Send OTP failed.Please try again later.',
                color: 'red',
            });
        }
    }

    async function handleVerifyOtp() {
        try {
            await verifyOtp(otp);
            return true;
        } catch {
            return false;
        }
    }

    const getAmountError = () => {
        if (!amount || !selectedAccount) return null;
        const amt = Number(amount);
        const balance = Number(selectedAccount.stAvailableBalance);
        if (paymentMode === "IMPS") {
            if (amt > 200000) return "IMPS limit is ₹2,00,000";
            if (amt > balance) return "Amount exceeds available balance";
        }
        if (paymentMode === "RTGS") {
            if (amt < 200000) return "RTGS requires minimum ₹2,00,000";
            if (amt > balance) return "Amount exceeds available balance";
        }
        if (paymentMode === "NEFT") {
            if (amt > balance) return "Amount exceeds available balance";
        }
        if (amt <= 0) return "Amount cannot be less than or equal to zero";
        return null;
    };

    const FetchBeneficiaryDetails = async () => {
        try {
            const token = localStorage.getItem("access_token");
            const response = await fetch("/api/beneficiary", {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    "X-Login-Type": "IB",
                    Authorization: `Bearer ${token}`,
                },
            });
            const data = await response.json();
            // console.log(data);
            if (response.ok && Array.isArray(data)) {
                setBeneficiaryData(data);
            } else {
                notifications.show({
                    title: "Error",
                    message: "Unable to fetch beneficiary list",
                    color: "red",
                });
            }
        } catch {
            notifications.show({
                title: "Error",
                message: "Something went wrong while fetching beneficiaries",
                color: "red",
            });
        }
    };
    const selectedAccount = accountData.find((acc) => acc.stAccountNo === selectedAccNo);
    const accountOptions = accountData.map((acc) => ({
        value: acc.stAccountNo,
        label: `${acc.stAccountNo} (${acc.stAccountType})`,
    }));

    const benAccountOption = beneficiaryData.
        filter((ben) => !ben.ifscCode?.startsWith("KACE"))
        .map((ben) => ({
            value: ben.accountNo,
            label: `${ben.accountNo} - ${ben.name}`,

        }));

    const handleBeneficiary = (ben: string | null) => {
        if (ben) {
            setBeneficiaryAcc(ben);
            const selected = beneficiaryData.find((item) => item.accountNo === ben && !item.ifscCode?.startsWith("KACE"));
            if (selected) {
                setBeneficiaryName(selected.name);
                setBeneficiaryIFSC(selected?.ifscCode ?? '');
            }
            else {
                setBeneficiaryAcc('');
                setBeneficiaryName('');
                setBeneficiaryIFSC('');
            }
        }
    }
    const FetchAccountDetails = async () => {
        try {
            const token = localStorage.getItem("access_token");
            const response = await fetch("/api/customer", {
                method: "GET",
                headers: {
                    "Content-Type": "application/json",
                    "X-Login-Type": "IB",
                    Authorization: `Bearer ${token}`,
                },
            });
            const data = await response.json();
            if (response.ok && Array.isArray(data)) {
                const filterSAaccount = data.filter((acc) => ['SA', 'SB','CC','OD','CA'].includes(acc.stAccountType));
                setAccountData(filterSAaccount);
            }
        } catch {
            notifications.show({
                withBorder: true,
                color: "red",
                title: "Please try again later",
                message: "Unable to Fetch, Please try again later",
                autoClose: 5000,
            });
        }
    };

    useEffect(() => {
        const token = localStorage.getItem("access_token");
        if (!token) {
            setAuthorized(false);
            router.push("/login");
        } else {
            setAuthorized(true);
        }
    }, []);

    useEffect(() => {
        if (authorized) {
            FetchAccountDetails();
            FetchBeneficiaryDetails();
            FetchDailyLimit();
        }
    }, [authorized]);

    useEffect(() => {
        let interval: number | undefined;
        if (timerActive && countdown > 0) {
            interval = window.setInterval(() => {
                setCountdown((prev) => prev - 1);
            }, 1000);
        }
        if (countdown === 0) {
            if (interval) clearInterval(interval);
            setTimerActive(false);
        }
        return () => {
            if (interval) clearInterval(interval);
        };
    }, [timerActive, countdown]);

    async function handleProceed() {
        if (!selectedAccNo || !beneficiaryAcc! || !beneficiaryName || !beneficiaryIFSC || !paymentMode || !amount || !remarks) {
            notifications.show({
                title: "Validation Error",
                message: `Please fill all required fields`,
                color: "red",
            });
            return;
        }

        if (parseInt(amount) <= 0) {
            notifications.show({
                title: "Invalid amount",
                message: "Amount Can not be less than Zero",
                color: "red",
            });
            return;
        }
        if (getAmountError()) {
            notifications.show({
                title: "Invalid amount",
                message: getAmountError()!,
                color: "red",
            });
            return;
        }
        if (!showOtpField && !showTxnPassword && !showConfirmModel) {
            setConfirmModel(true);
            setIsVisibilityLocked(true);
            return;
        }

        if (showOtpField && !showTxnPassword) {
            if (!otp) {
                notifications.show({
                    title: "Error",
                    message: "Please enter the OTP",
                    color: "red",
                });
                return;
            }

            const verified = await handleVerifyOtp();
            if (!verified) {
                notifications.show({
                    title: "Invalid OTP",
                    message: "The OTP entered does not match",
                    color: "red",
                });
                return;
            }
            // If OTP verified successfully → show transaction password field
            setShowTxnPassword(true);
            return;
        }

        if (!showTxnPassword) {
            setShowTxnPassword(true);
            return;
        }

        if (!txnPassword) {
            notifications.show({
                title: "Missing field",
                message: "Please Enter Transaction Password Before Proceed",
                color: "red",
            });
            return;
        }
        try {
            setIsSubmitting(true);
            const token = localStorage.getItem("access_token");
            const remitter_name = localStorage.getItem("remitter_name");
            let url = "";
            if (paymentMode === "NEFT")
                url = "/api/payment/neft";
            if (paymentMode === "RTGS")
                url = "/api/payment/rtgs"
            if (paymentMode === "IMPS")
                url = "/api/payment/imps";

            const res = await fetch(url, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-Login-Type": "IB",
                    Authorization: `Bearer ${token}`,
                },
                body: JSON.stringify({
                    fromAccount: selectedAccNo,
                    toAccount: beneficiaryAcc,
                    ifscCode: beneficiaryIFSC,
                    amount: amount,
                    beneficiaryName: beneficiaryName,
                    remitterName: remitter_name,
                    tpassword: txnPassword,
                    remarks: remarks
                }),
            });
            const result = await res.json();
            if (res.ok) {
                notifications.show({
                    title: "Success",
                    message: result?.utr ? `Transaction successful - UTR =${result.utr}` : "Transaction successful",
                    color: "green",
                });
                setShowTxnPassword(false);
                setTxnPassword("");
                setShowOtpField(false);
                setOtp("");
                setBeneficiaryName('');
                await FetchDailyLimit();
            }
            else {
                notifications.show({
                    title: "Error",
                    message: result?.error || "Transaction failed",
                    color: "red",
                });
            }

        } catch {
            notifications.show({
                title: "Error",
                message: "Something went wrong",
                color: "red",
            });
        } finally {
            setSelectedAccNo(null);
            setBeneficiaryAcc(null);
            setBeneficiaryName('');
            setPaymentMode('');
            setAmount('');
            setRemarks('');
            setIsVisibilityLocked(false);
            setIsSubmitting(false);
            setShowTxnPassword(false);
            setShowOtpField(false);
            setOtp('');
            setTxnPassword('');
        }
    };

    if (!authorized) return null;

    return (
        <>
            <Modal
                opened={showIntroModal}
                onClose={() => setShowIntroModal(false)}
                centered
                withCloseButton={false} // force them to press OK
            >
                <Stack gap={1}>

                    <Center>
                        <Image
                            src={img}
                            alt="KCC Bank Logo"
                            width={100}
                            height={100}
                            style={{ border: "2px solid black" }}
                        />
                    </Center>



                    <Title order={4} style={{ textAlign: "center" }}>
                        Important Note
                    </Title>

                    <Text size="sm">
                        • <strong>IMPS</strong> is available 24X7. Limit: up to ₹5,00,000.
                        Money is transfer instantly.
                    </Text>
                    <Text size="sm">
                        • <strong>NEFT</strong> is available 24x7. Can be used for any amount
                        but not instant.
                    </Text>
                    <Text size="sm">
                        • <strong>RTGS</strong> is for ₹2,00,000 and above. Available during
                        banking hours. As per directions of RBI, RTGS transactions are
                        subjected to the following <strong>Time Varying Tariff</strong> in
                        addition to the existing <strong>RTGS</strong> Commission. The tariff
                        will be calculated based on the time of completion of transaction.
                    </Text>

                    <List
                        spacing="xs"
                        size="sm"
                        icon={
                            <ThemeIcon color="red" size={20} radius="xl">
                                <IconAlertTriangle size={14} />
                            </ThemeIcon>
                        }
                    >
                        <List.Item>
                            From <strong>09:00 hrs</strong> to <strong>12:00 hrs</strong> →{" "}
                            <strong>₹0.00</strong>
                        </List.Item>
                        <List.Item>
                            After <strong>12:00 hrs</strong> up to <strong>15:30 hrs</strong> →{" "}
                            <strong>₹1.00</strong>
                        </List.Item>
                        <List.Item>
                            After <strong>15:30 hrs</strong> → <strong>₹5.00</strong>
                        </List.Item>
                    </List>

                    <Divider my="sm" variant="dashed" />

                    {/* <Text size="xs" c="blue">
                        • Minimum Transfer Amount on this Day is Rs. 1.00
                    </Text>
                    <Text size="xs" c="blue">
                        • Maximum Transfer Limit per Day is Rs. 500000.00
                    </Text>
                    <Text size="xs" c="blue">
                        • Available Transfer Amount on this Day is Rs. 500000.00
                    </Text> */}
                    <Stack gap={1} mt="xs">
                        <Text size="xs" c="green">
                            • Minimum Transfer Amount on this Day is Rs. 1.00
                        </Text>
                        {dailyLimit !== null ? (
                            <>
                                <Text size="xs" c="green">
                                    • Maximum Transfer Limit per Day is Rs. {dailyLimit.toFixed(2)}
                                </Text>
                                <Text size="xs" c="green">
                                    • Available Transfer Amount on this Day is Rs.{" "}
                                    {usedLimit?.toFixed(2)}
                                </Text>
                            </>
                        ) : (
                            <Text size="xs" c="red">
                                • No daily limit set for this user
                            </Text>
                        )}
                    </Stack>

                    <Group justify="flex-end" mt="md">
                        <Button color="blue" onClick={() => setShowIntroModal(false)}>
                            Okay
                        </Button>
                    </Group>
                </Stack>
            </Modal>

            <Modal
                opened={showConfirmModel}
                onClose={() => setConfirmModel(false)}
                // title="Confirm Transaction"
                centered
            >
                <Stack>
                    <Image
                        src={img}
                        alt="KCC Bank Logo"
                        width={70}
                        height={70}
                        style={{
                            //border: "2px solid black",
                            marginTop: "-5px",
                            marginRight: "10px",
                        }}
                    />
                    <Title order={4}>Confirm Transaction</Title>
                    <Text><strong>Debit Account:</strong> {selectedAccNo}</Text>
                    <Text><strong>Beneficiary Account:</strong> {beneficiaryAcc}</Text>
                    <Text><strong>Beneficiary Name:</strong> {beneficiaryName}</Text>
                    <Text><strong>Payment Type:</strong> {paymentMode}</Text>
                    <Text><strong>Amount:</strong> ₹ {amount}</Text>
                    <Text><strong>Remarks:</strong>  {remarks}</Text>
                </Stack>
                <Group justify="flex-end" mt="md">
                    <Button variant="default" onClick={() => setConfirmModel(false)}>Cancel</Button>
                    <Button
                        color="blue"
                        onClick={async () => {
                            setConfirmModel(false);
                            const otp = await handleSendOtp();
                            setShowOtpField(true);
                            notifications.show({
                                title: "OTP Sent",
                                message: `Check your registered device for OTP`,
                                color: "green",
                                autoClose: 5000,
                            });
                        }}
                    >
                        Confirm
                    </Button>
                </Group>
            </Modal>

            {/* main content */}
            {!showIntroModal && (
                <div style={{ maxHeight: "350px", overflowY: "auto" }}>
                    <Stack gap={5} justify="flex-start">
                        <Group grow gap='xs' >
                            <Select
                                label="Select Debit Account Number"
                                placeholder="Choose account number"
                                data={accountOptions}
                                value={selectedAccNo}
                                onChange={setSelectedAccNo}
                                withAsterisk
                                readOnly={isVisibilityLocked}
                            />
                            <Select
                                label="Beneficiary Account No"
                                placeholder="Choose beneficiary account number"
                                data={benAccountOption}
                                value={beneficiaryAcc}
                                onChange={handleBeneficiary}
                                withAsterisk
                                readOnly={isVisibilityLocked}
                                nothingFoundMessage='No account found'
                            />
                            <TextInput
                                label="Beneficiary Name"
                                value={beneficiaryName ? beneficiaryName : ""}
                                disabled
                                readOnly
                                withAsterisk
                            />
                            <TextInput
                                label="Beneficiary IFSC Code"
                                value={beneficiaryIFSC ? beneficiaryIFSC : ""}
                                disabled
                                readOnly
                                withAsterisk
                            />
                        </Group>
                        <Group gap='xs' >
                            <Text size="xs" c="green" style={{ visibility: selectedAccount ? "visible" : "hidden" }}>Available Balance :
                                {selectedAccount ? selectedAccount.stAvailableBalance : 0}
                            </Text>
                        </Group>
                        <Group grow gap='xs'>
                            <Radio.Group
                                name="payment-mode"
                                label="Select Payment Method"
                                value={paymentMode}
                                onChange={setPaymentMode}
                                withAsterisk
                                readOnly={isVisibilityLocked}
                            >
                                <Group gap="xs">
                                    <Radio value="IMPS" label="IMPS" />
                                    <Radio value="RTGS" label="RTGS" />
                                    <Radio value="NEFT" label="NEFT" />
                                </Group>
                                <Text size="xs" c="red">
                                    {paymentMode === "IMPS" && "IMPS is available 24X7. Limit: up to ₹2,00,000. Money is transfer instantly. "}
                                    {paymentMode === "RTGS" && "RTGS is for ₹2,00,000 and above. Available during banking hours."}
                                    {paymentMode === "NEFT" && "NEFT is available 24x7. Can be used for any amount but not instant."}
                                </Text>
                            </Radio.Group>

                            <TextInput
                                label="Amount"
                                type="number"
                                value={amount}
                                onChange={(e) => {
                                    let input = e.currentTarget.value;
                                    if (/^\d*\.?\d{0,2}$/.test(input))
                                        setAmount(input);
                                }}
                                error={getAmountError()}
                                leftSection="₹"
                                withAsterisk
                                readOnly={showOtpField}
                            />

                            <TextInput
                                label="Remarks"
                                placeholder="Enter remarks"
                                value={remarks}
                                onChange={(e) => {
                                    let input = e.currentTarget.value;
                                    input = input.replace(/[^a-zA-Z0-9 ]/g, "");
                                    setRemarks(input)
                                }}
                                maxLength={50}
                                withAsterisk
                                readOnly={showOtpField}
                            />
                        </Group>
                        <Group grow>
                            {showOtpField && (
                                <>
                                    <Group gap="xs" align="flex-end">
                                        <PasswordInput
                                            label="OTP"
                                            placeholder="Enter OTP"
                                            type="otp"
                                            value={otp}
                                            maxLength={6}
                                            onChange={(e) => setOtp(e.currentTarget.value)}
                                            withAsterisk
                                            disabled={showTxnPassword}
                                            style={{ flex: 1 }}
                                        />
                                        {!showTxnPassword && (
                                            timerActive ? (
                                                <Text size="xs" c="dimmed" style={{ minWidth: "120px" }}>
                                                    Resend OTP will be enabled in{" "}
                                                    {String(Math.floor(countdown / 60)).padStart(2, "0")}:
                                                    {String(countdown % 60).padStart(2, "0")}
                                                </Text>
                                            ) : (
                                                <IconRefresh
                                                    size={22}
                                                    style={{ cursor: "pointer", color: "blue", marginBottom: "6px" }}
                                                    onClick={handleSendOtp}
                                                />
                                            )
                                        )}

                                    </Group>
                                </>
                            )}
                            {showTxnPassword && (
                                <TextInput
                                    label="Transaction Password"
                                    placeholder="Enter transaction password"
                                    type="password"
                                    value={txnPassword}
                                    onChange={(e) => setTxnPassword(e.currentTarget.value)}
                                    withAsterisk
                                />
                            )}
                        </Group>
                        <Group justify="flex-start">
                            <Button
                                variant="filled"
                                color="blue"
                                onClick={handleProceed}
                                loading={isSubmitting}
                            >
                                {!showTxnPassword && showOtpField ? "Validate the OTP" : showTxnPassword ? "Proceed to Pay" : "Proceed"}
                            </Button>
                        </Group>
                        <Stack gap={1} mt="xs">
                            {paymentMode === "RTGS" &&
                                <>
                                    <Text size="xs" >
                                        • As per directions of RBI, RTGS transactions are subjected to the following{" "}
                                        <strong>Time Varying Tariff</strong> in addition to the existing RTGS
                                        Commission. The tariff will be calculated based on the time of completion
                                        of transaction.
                                    </Text>
                                    <List
                                        spacing="xs"
                                        size="sm"
                                    // icon={
                                    //     <ThemeIcon color="red" size={20} radius="xl">
                                    //         <IconAlertTriangle size={14} />
                                    //     </ThemeIcon>
                                    // }
                                    >
                                        <List.Item>
                                            From <strong>09:00 hrs</strong> to <strong>12:00 hrs</strong> →{" "}
                                            <strong>₹0.00</strong>
                                        </List.Item>
                                        <List.Item>
                                            After <strong>12:00 hrs</strong> up to <strong>15:30 hrs</strong> →{" "}
                                            <strong>₹1.00</strong>
                                        </List.Item>
                                        <List.Item>
                                            After <strong>15:30 hrs</strong> → <strong>₹5.00</strong>
                                        </List.Item>
                                    </List>
                                </>
                            }
                            <Stack gap={1} mt="xs">
                                <Text size="xs" c="green">
                                    • Minimum Transfer Amount on this Day is Rs. 1.00
                                </Text>
                                {dailyLimit !== null ? (
                                    <>
                                        <Text size="xs" c="green">
                                            • Maximum Transfer Limit per Day is Rs. {dailyLimit.toFixed(2)}
                                        </Text>
                                        <Text size="xs" c="green">
                                            • Available Transfer Amount on this Day is Rs.{" "}
                                            {usedLimit?.toFixed(2)}
                                        </Text>
                                    </>
                                ) : (
                                    <Text size="xs" c="red">
                                        • No daily limit set for this user
                                    </Text>
                                )}
                            </Stack>

                        </Stack>
                    </Stack>
                </div >
            )}
        </>
    );
}


