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,
    DialogHeader,
    DialogTitle,
    DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { doSaveLogActivity } from '@/actions/GlobalActions';
import { toast } from 'sonner';
import { Input } from '@/components/ui/input';
import { DefaultTooltip, KeenIcon, useDataGrid } from '@/components';
import Swal from 'sweetalert2'; // ✅ IMPORT sweetalert2

const API_URL = apiConfig.transaction;

const RollbackTransaction = () => {
    const { GetData, PostData } = useCallApi();
    const { reload } = useDataGrid();

    const {
        showRollbackDialog,
        setShowRollbackDialog,
        selectedTransactionId,
    } = useTransactionContext();


    const [formField, setFormField] = useState({
        transaction_code: '',
        notes: '',
        pin: ''
    });

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

    const doApproval = useCallback(
        async (e: React.FormEvent<HTMLFormElement>) => {
            e.preventDefault();

            // ✅ TUTUP Dialog sebelum munculkan SweetAlert
            setShowRollbackDialog(false);

            // ✅ TAMPILKAN SWEETALERT
            const result = await Swal.fire({
                title: 'Are you sure?',
                text: "You want to save changes?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, save it!',
                cancelButtonText: 'Cancel'
            });

            if (result.isConfirmed) {
                // ✅ Kalau tekan YES, baru tembak API
                const response = await PostData(`${API_URL}/transaction/rollback`, {
                    id_transaction: selectedTransactionId,
                    notes: formField.notes,
                    pin: formField.pin,
                });

                // console.log(response?.message?.error?.message,response?.status);

                if (response?.status === false) {
                    // console.log(response);
                    toast.error(JSON.stringify(response));
                    return;
                }

                if (response?.status) {
                    toast.success('Success Update Approval');
                    const createActivity = {
                        module: 'History Transaction',
                        description: `Rollback Transaction for transaction => ${selectedTransactionId}`,
                        action: 'U',
                    };
                    doSaveLogActivity(createActivity);
                    reload();
                }
            } else {
                // ✅ Kalau tekan Cancel
                console.log('User cancelled');
            }
        },
        [formField]
    );

    useEffect(() => {
        if (showRollbackDialog) {
            setFormField({
                transaction_code: '',
                notes: '',
                pin: ''
            });
            setAlert({ show: false, message: '' });
        }
    }, [showRollbackDialog]);


    return (
        <Dialog open={showRollbackDialog} onOpenChange={setShowRollbackDialog}>
            <DialogContent className="container-fixed max-w-[1024px] flex flex-col p-5 overflow-hidden">
                <DialogHeader>
                    <DialogTitle>Rollback Transaction</DialogTitle>
                </DialogHeader>
                <DialogDescription></DialogDescription>
                <DialogBody>
                    <form onSubmit={doApproval}>
                        <div className="card-body grid gap-5 p-0">
                            <div className="w-full">
                                <div className="flex items-center flex-wrap gap-2.5 mt-4">
                                    <label className="form-label max-w-56">Notes</label>
                                    <div className="grow">
                                        <Input
                                            type="text"
                                            placeholder="Notes"
                                            name="notes"
                                            id="notes"
                                            value={formField.notes}
                                            onChange={(e) =>
                                                setFormField((prev) => ({
                                                    ...prev,
                                                    notes: e.target.value,
                                                }))
                                            }
                                        />
                                    </div>
                                </div>
                                <div className="flex items-center flex-wrap gap-2.5 mt-3 mb-3">
                                    <label className="form-label max-w-56">PIN</label>
                                    <div className="grow">
                                        <Input
                                            required
                                            type="password"
                                            placeholder="PIN"
                                            name="pin"
                                            id="pin"
                                            value={formField.pin}
                                            onChange={(e) =>
                                                setFormField((prev) => ({
                                                    ...prev,
                                                    pin: e.target.value,
                                                }))
                                            }
                                        />
                                    </div>
                                </div>
                                {alert.show && (
                                    <div className="mt-4">
                                        <span className="inline-block bg-red-100 text-red-800 text-sm font-medium px-4 py-2 rounded-md">
                                            {alert.message}
                                        </span>
                                    </div>
                                )}
                            </div>

                            <hr />
                            <div className="flex justify-end">
                                <Button className="btn btn-primary" type="submit">
                                    Save Changes
                                </Button>
                            </div>
                        </div>
                    </form>
                </DialogBody>
            </DialogContent>
        </Dialog>
    );
};

export default RollbackTransaction;
