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 { Button } from '@/components/ui/button';
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;

const ResendTransaction = () => {
    const { showResendDialog, handleResendDialog, selectedTransactionForResend } = useTransactionContext();
    const { GetData, PostData } = useCallApi();
    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) {
            // Reset form fields when dialog opens
            setFormField({
                pin: ''
            });
            setAlert({ show: false, message: '' });
            setTransactionDetails(null); // Optional reset
        }
    }, [showResendDialog]);

    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 (showResendDialog && selectedTransactionForResend) {
            fetchTransactionDetails();
        }
    }, [showResendDialog, selectedTransactionForResend, GetData]);

    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,
                    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':
                apiEndpoint = `${API_URL}/transaction/purchase`;
                apiJsonData = {
                    id_origin_customer: data.origin_customer.id,
                    code_product: "object purchase : masih null",
                    wallet: "emoney or point",
                    destination_number: "parameter number",
                    destination_amount: "parameter 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);
            toast.success('Success Retry Transaction');
            reload();

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

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

    return (
        <Dialog open={showResendDialog} onOpenChange={(open) => handleResendDialog(open, null)}>
            <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>
                        <span className="text-sm">You will retry this transaction!</span>
                    </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 variant="outline" onClick={() => handleResendDialog(false, null)}>
                        Cancel
                    </Button>
                    <Button variant="default" onClick={() => doResendTransaction(transactionDetails, formField.pin)}>
                        Retry
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
};

export default ResendTransaction;
