import { useTransactionContext } from '../hooks/useApprovalTransactionContext';
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 ApprovalDialog = () => {
    const { GetData, PostData } = useCallApi();
    const { reload } = useDataGrid();

    const {
        showApprovalDialog,
        setShowApprovalDialog,
        selectedTransactionIdForApproval,
    } = useTransactionContext();


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

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

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

            if (!formField.status) {
                toast.error('Please select a status.');
                return;
            }

            // ✅ TUTUP Dialog sebelum munculkan SweetAlert
            setShowApprovalDialog(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/set-approval`, {
                    id_transaction: selectedTransactionIdForApproval,
                    notes: formField.notes,
                    status: formField.status,
                    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: 'Approval Transaction',
                        description: `Change status approve for transaction => ${selectedTransactionIdForApproval}`,
                        action: 'U',
                    };
                    doSaveLogActivity(createActivity);
                    reload();
                }
            } else {
                // ✅ Kalau tekan Cancel
                console.log('User cancelled');
            }
        },
        [formField]
    );

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


    return (
        <Dialog open={showApprovalDialog} onOpenChange={setShowApprovalDialog}>
            <DialogContent className="container-fixed max-w-[1024px] flex flex-col p-5 overflow-hidden">
                <DialogHeader>
                    <DialogTitle>Approval 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">
                                    <label className="form-label max-w-56">Status</label>
                                    <div className="grow">
                                        <Select
                                            value={formField.status}
                                            onValueChange={(status) =>
                                                setFormField((prev) => ({ ...prev, status }))
                                            }
                                        >
                                            <SelectTrigger>
                                                <SelectValue placeholder="Select" />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="Y">APPROVE</SelectItem>
                                                <SelectItem value="N">REJECTED</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </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>

                                {formField.status === 'N' && (
                                    <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>
                                )}

                                {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 ApprovalDialog;
