import { useEffect, useState } from 'react';
import Flatpickr from 'react-flatpickr';
import 'flatpickr/dist/flatpickr.css';
import 'flatpickr/dist/plugins/monthSelect/style.css';
import monthSelectPlugin from 'flatpickr/dist/plugins/monthSelect';

const BarBudgetingCommissions = () => {
    const date = new Date();
    const monthYear = date.toLocaleString('default', { month: 'long', year: 'numeric' });

    const [selectedMonthYear, setSelectedMonthYear] = useState(monthYear);

    const [maxBudgetingCommission, setMaxBudgetingCommission] = useState(0); // Ensure this can be dynamically set or checked
    const [totalCompletedTransaction, setTotalCompletedTransaction] = useState(0);

    const [isMounted, setIsMounted] = useState(false);

    const [isLoadingChange, setIsLoadingChange] = useState(true);
    useEffect(() => {
        setIsMounted(true);
    }, []);

    async function getBudgetingCommission(selectedMonthYear: string) {
        setIsLoadingChange(true);
        try {
            const api_url = process.env.API_URL;
            const response = await fetch(`${api_url}api/setting/affiliate/budgeting-commission-month?monthYear=${encodeURIComponent(selectedMonthYear)}`, {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
            });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            setMaxBudgetingCommission(data.max_budgeting_commission || 0);
            setTotalCompletedTransaction(data.total_completed_transaction || 0);
        } catch (error) {
            console.error('Error fetching budgeting commission data:', error);
        } finally {
            setIsLoadingChange(false);
        }
    }

    useEffect(() => {
        if (isMounted) {
            if (selectedMonthYear) {
                getBudgetingCommission(selectedMonthYear);
            }
        }
    }, [isMounted, selectedMonthYear]); // Combined into a single useEffect for optimization

    // Validation for MAX_BUDGETING_COMMISSION to avoid division by zero
    const progressPercentage = maxBudgetingCommission > 0 ? (totalCompletedTransaction / maxBudgetingCommission) * 100 : 0;
    const progressWidth = `${progressPercentage}%`;

    let bgColor = 'bg-success';
    let textColor = 'text-success';

    if (progressPercentage >= 90) {
        bgColor = 'bg-danger';
        textColor = 'text-danger';
    } else if (progressPercentage >= 70) {
        bgColor = 'bg-warning';
        textColor = 'text-warning';
    }

    return (
        <>
            <div className="space-y-2">
                <div className="flex justify-between">
                    <div className="a flex items-center space-x-2">
                        <h3 className="text-base">Budgeting</h3>
                        <Flatpickr
                            options={{
                                plugins: [
                                    monthSelectPlugin({
                                        shorthand: true,
                                        theme: 'dark',
                                    }),
                                ],
                            }}
                            value={selectedMonthYear}
                            className="form-input"
                            placeholder="Month Year"
                            onChange={(date: any) => {
                                setSelectedMonthYear(date.toLocaleString('default', { month: 'long', year: 'numeric' }));
                            }}
                        />
                        {isLoadingChange && (
                            <div className="flex items-center justify-center">
                                <span className="m-auto  inline-block h-5 w-5 animate-spin rounded-full border-4 border-primary border-l-transparent align-middle"></span>
                            </div>
                        )}
                    </div>
                    <div className="text-sm">
                        <span className="font-medium">
                            <span className={`${textColor} text-lg`}>Rp {totalCompletedTransaction.toLocaleString('id-ID', { minimumFractionDigits: 0 })}</span> /{' '}
                            <span className="text-primary">Rp {maxBudgetingCommission.toLocaleString('id-ID', { minimumFractionDigits: 0 })}</span>
                            <span className={`${textColor} ml-1`}>({progressPercentage.toFixed(2)}%)</span>
                        </span>
                    </div>
                </div>
                <div className="flex h-4 w-full rounded-full bg-[#ebedf2] dark:bg-dark/40">
                    <div
                        className={`animated-progress h-4 rounded-full ${bgColor} text-center text-xs text-white`}
                        style={{
                            width: progressWidth,
                            backgroundImage: 'linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent)',
                            backgroundSize: '1rem 1rem',
                        }}
                    ></div>
                </div>
            </div>
        </>
    );
};

export default BarBudgetingCommissions;
