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,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
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 ApprovalDialog = () => {
    const { GetData, PostData } = useCallApi();

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

    const [transactionDetails, setTransactionDetails] = useState<any>(null);

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

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

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

            if (!transactionDetails || !transactionDetails.code) {
                toast.error('Transaction data not loaded yet.');
                return;
            }

            if (!formField.status) {
                toast.error('Please select a status.');
                return;
            }
            const response = await PostData(`${API_URL}/transaction/set-approval`, {
                id_transaction: transactionDetails.id,
                status: formField.status,
                notes: formField.notes,
            });

            if (response?.status) {
                setAlert({ show: false, message: '' });
                toast.success('Success Update Position');
                const createActivity = {
                    module: 'Approval Transaction',
                    description: `Change status approve for transaction => ${transactionDetails.code}`,
                    action: 'U',
                };
                doSaveLogActivity(createActivity);
                setShowApprovalDialog(false);
            } else {
                setAlert({ show: true, message: response?.message });
            }
        },
        [formField, transactionDetails]
    );

    useEffect(() => {
        if (showApprovalDialog) {
            // Reset form fields when dialog opens
            setFormField({
                transaction_code: '',
                status: '',
                notes: '',
            });
            setTransactionDetails(null); // Optional reset
        }
    }, [showApprovalDialog]);

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

        if (showApprovalDialog && selectedTransactionIdForApproval) {
            fetchTransactionDetails();
        }
    }, [showApprovalDialog, selectedTransactionIdForApproval, GetData]);

    // Set formField.transaction_code once details are fetched
    useEffect(() => {
        if (transactionDetails) {
            setFormField((prev) => ({
                ...prev,
                transaction_code: transactionDetails.id ?? '',
            }));
        }
    }, [transactionDetails]);

    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>
                <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>

                                {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>
                                )}
                            </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;