import { useTransactionContext } from '../hooks/useTransactionContext';
import { useCallApi } from '@/hooks';
import { apiConfig } from '@/config/api.config';
import { useCallback, useEffect, useState } from 'react';
import {
    Dialog,
    DialogBody,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle
} from '@/components/ui/dialog';
import { Alert, useDataGrid } from '@/components';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';

const API_URL = apiConfig.transaction;

interface ResendTransactionProps {
    isOpen: boolean | null;
    onClose: () => void | null;
    selectedTransactionForResend: any | null; // Adjust the type as per your requirements
}

const ResendTransaction = ({ isOpen, onClose, selectedTransactionForResend }: ResendTransactionProps) => {

    // const { showResendDialog, handleResendDialog, selectedTransactionForResend } = useTransactionContext();
    const { GetData, PostData } = useCallApi();
    const {
        showDetailDialog,
        setShowDetailDialog,
        selectedTransactionId
    } = useTransactionContext();
    const { reload } = useDataGrid();
    const [transactionDetails, setTransactionDetails] = useState<any>(null);
    const [alert, setAlert] = useState({
        show: false,
        message: ''
    });
    const initialStatePin = {
        pin: ''
    };
    const [formField, setFormField] = useState(initialStatePin);

    useEffect(() => {
        // if (showResendDialog) {
        if (isOpen) {
            // Reset form fields when dialog opens
            setFormField({
                pin: ''
            });
            setAlert({ show: false, message: '' });
            // setTransactionDetails(null); // Optional reset
        }
    }, [isOpen]);

    // useEffect(() => {
    //     const fetchTransactionDetails = async () => {
    //         if (selectedTransactionForResend) {
    //             try {
    //                 const response = await GetData(
    //                     `${API_URL}/transaction/history/detail/${selectedTransactionForResend}`,
    //                     {
    //                         id: selectedTransactionForResend,
    //                     }
    //                 );
    //                 setTransactionDetails(response?.data);
    //             } catch (error) {
    //                 console.error('Error fetching transaction', error);
    //             }
    //         }

    //     };

    //     if (isOpen && selectedTransactionForResend) {
    //         fetchTransactionDetails();
    //     }
    // }, [isOpen, selectedTransactionForResend, GetData]);

    // console.log(selectedTransactionForResend);


    const doResendTransaction = useCallback(async (data: any | null, pintransactiion: string) => {

        if (pintransactiion.trim() === '') {
            setAlert({ show: true, message: 'Please fill pin.' });
            return;
        }

        if (pintransactiion.length < 6) {
            setAlert({ show: true, message: 'Pin length must be 6 characters long.' });
            return;
        }

        if (!data) {
            toast.error('No Transaction selected');
            return;
        }

        if (!data.type) {
            toast.error('No Transaction Type selected');
            return;
        }

        let apiEndpoint: string | null | undefined = null;
        let apiJsonData: any | null | undefined = null;

        switch (data.kind) {
            case 'T':
                apiEndpoint = `${API_URL}/transaction/transfer`;
                apiJsonData = {
                    id_origin_customer: data.origin_customer.id,
                    // msisdn_destination: data.transfer.destination_customer.msisdn,
                    msisdn_destination: data.transfer.destination_msisdn,
                    id_transaction_type: data.type.id,
                    amount: String(data.transfer.amount),
                    pin: pintransactiion,
                    type: data.transfer.type
                }
                break;
            case 'U':
                apiEndpoint = `${API_URL}/transaction/topup`;
                apiJsonData = {
                    id_origin_customer: data.origin_customer.id,
                    id_transaction_type: data.type.id,
                    pin_p24: data.transfer.pin_p24,
                    amount: String(data.transfer.amount),
                    pin: pintransactiion
                }
                break;
            case 'W':
                apiEndpoint = `${API_URL}/transaction/withdraw`;
                apiJsonData = {
                    id_origin_customer: data.origin_customer.id,
                    id_transaction_type: data.type.id,
                    destination_iban: data.transfer.destination_iban,
                    amount: String(data.transfer.amount),
                    pin: pintransactiion
                }
                break;
            case 'P':
                let walletParam = "";
                apiEndpoint = `${API_URL}/transaction/purchase`;
                if (data.origin_wallet.name === 'Emoney Account') {
                    walletParam = "emoney";
                } else if (data.origin_wallet.name === 'Point Account') {
                    walletParam = "point";
                }
                apiJsonData = {
                    id_origin_customer: data.origin_customer.id,
                    code_product: data.purchase.code,
                    wallet: walletParam,
                    destination_number: "",
                    destination_amount: String(data.purchase.amount),
                    pin: pintransactiion
                }
                break;
        }

        if (!apiEndpoint || !apiJsonData) {
            toast.error('Invalid transaction');
            return;
        }

        const response = await PostData(apiEndpoint, apiJsonData);

        if (response?.status) {
            setAlert({ show: false, message: '' });
            // handleResendDialog(false, null);
            onClose();
            setShowDetailDialog(false);
            reload();
            toast.success('Success Retry Transaction');

            const createActivity = {
                module: 'History Transaction',
                description: `Retry Transaction => ${data.code}`,
                action: 'U'
            };

            doSaveLogActivity(createActivity);
        } else {
            setAlert({ show: true, message: response?.message.message });
            toast.error('Failed Retry Transaction');
        }
    }, [selectedTransactionForResend, PostData]);

    if (!isOpen) return null;

    return (
        <Dialog open={isOpen} onOpenChange={onClose}>
            <DialogContent className="container-fixed max-w-md flex flex-col p-5 overflow-hidden [&>button]:hidden">
                <DialogHeader className="p-0 border-0 block">
                    <DialogTitle></DialogTitle>
                    <DialogDescription></DialogDescription>
                    <Alert variant="warning">
                        <h3 className="text-lg">Are you sure?</h3>
                        <p className="text-sm">You will retry this transaction!</p>
                    </Alert>
                    {alert.show && (
                        <Alert variant="danger">
                            <h3>{alert.message}</h3>
                        </Alert>
                    )}
                </DialogHeader>
                <DialogBody>
                    <label className="form-label flex items-center gap-1 max-w-56">
                        Pin<span className="text-red-500">*</span>
                    </label>
                    <Input
                        className="input"
                        type="password"
                        value={formField.pin}
                        onChange={(e) => setFormField({ ...formField, pin: e.target.value })}
                    />
                </DialogBody>
                <DialogFooter className="flex justify-end items-center gap-4 mt-3">
                    <button onClick={onClose}>Close</button>
                    {/* <Button variant="outline" onClick={() => handleResendDialog(false, null)}>
                        Cancel
                    </Button> */}
                    <button className="btn btn-primary" onClick={() => doResendTransaction(selectedTransactionForResend, formField.pin)}>
                        Retry
                    </button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
};

export default ResendTransaction;
