import { useEffect, useState } from "react";
import Chart from "react-apexcharts";
import { ApexOptions } from "apexcharts";
import { MdDoneAll, MdPendingActions } from "react-icons/md";
import { Card } from "react-bootstrap";
import { PaidTransaction } from "@/types/stats";
import axios from "axios";
import EkspedisiController from "@/actions/App/Http/Controllers/EkspedisiController";
import { decimalFormatter } from "@/utils/decimal-formatter";
import { getVarCss } from "@/utils/css";

// Type definitions
interface ChartData {
    series: number[];
    options: ApexOptions;
}

export default function PaidTransactionComponent() {
    const [loading, setLoading] = useState<boolean>(true);
    const [response, setResponse] = useState<PaidTransaction | null>(null);
    const [chartData, setChartData] = useState<ChartData>({
        series: [],
        options: {},
    });

    const fetchData = async () => {
        setLoading(true);
        try {
            const { data: res } = await axios.get(EkspedisiController.paidTransaction.url());
            setResponse(res);
        } catch (error) {
            console.error(error);
        } finally {
            setLoading(false);
        }
    }

    useEffect(() => {
        fetchData();
    }, []);

    useEffect(() => {
        if (response) {
            const totalAmount = response.total.amount;
            const paidAmount = response.paid.amount;
            const percentage = totalAmount > 0 ? Math.round((paidAmount / totalAmount) * 100) : 0;

            setChartData({
                series: [percentage],
                options: {
                    chart: {
                        type: 'radialBar',
                        toolbar: {
                            show: false
                        },
                        animations: {
                            enabled: true,
                            speed: 800
                        }
                    },
                    title: {
                        text: 'Paid Transaction',
                        align: 'center',
                        margin: 10,
                        style: {
                            fontSize: '16px',
                            fontWeight: 'bold',
                            color: '#6c757d',
                        }
                    },
                    plotOptions: {
                        radialBar: {
                            startAngle: -135,
                            endAngle: 225,
                            hollow: {
                                margin: 0,
                                size: '65%',
                                background: 'transparent',
                                dropShadow: {
                                    enabled: false
                                }
                            },
                            track: {
                                background: getVarCss('--bs-light-border-subtle'),
                                strokeWidth: '100%',
                                margin: 5,
                                dropShadow: {
                                    enabled: false
                                }
                            },
                            dataLabels: {
                                show: true,
                                name: {
                                    offsetY: -10,
                                    show: true,
                                    color: '#6c757d',
                                    fontSize: '14px',
                                    fontWeight: 500
                                },
                                value: {
                                    formatter: function (val: any) {
                                        return `${parseInt(val)}%`;
                                    },
                                    color: '#495057',
                                    fontSize: '24px',
                                    fontWeight: 'bold',
                                    show: true,
                                    offsetY: 5
                                }
                            }
                        }
                    },
                    fill: {
                        type: 'gradient',
                        gradient: {
                            shade: 'light',
                            type: 'horizontal',
                            shadeIntensity: 0.3,
                            gradientToColors: [getVarCss('--bs-primary')],
                            inverseColors: false,
                            opacityFrom: 0.9,
                            opacityTo: 0.9,
                            stops: [0, 100]
                        }
                    },
                    stroke: {
                        lineCap: 'round',
                        dashArray: 0
                    },
                    labels: ['Completion'],
                    colors: [getVarCss('--bs-success')],
                    responsive: [
                        {
                            breakpoint: 768,
                            options: {
                                chart: {
                                    height: 280
                                },
                                title: {
                                    style: {
                                        fontSize: '14px'
                                    }
                                },
                                plotOptions: {
                                    radialBar: {
                                        hollow: {
                                            size: '60%'
                                        },
                                        dataLabels: {
                                            name: {
                                                fontSize: '12px'
                                            },
                                            value: {
                                                fontSize: '20px'
                                            }
                                        }
                                    }
                                }
                            }
                        },
                        {
                            breakpoint: 576,
                            options: {
                                chart: {
                                    height: 250
                                },
                                title: {
                                    style: {
                                        fontSize: '13px'
                                    }
                                },
                                plotOptions: {
                                    radialBar: {
                                        hollow: {
                                            size: '55%'
                                        },
                                        dataLabels: {
                                            name: {
                                                fontSize: '11px'
                                            },
                                            value: {
                                                fontSize: '18px'
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    ]
                },
            });
        }
    }, [response]);

    if (loading || !response) {
        return (
            <div className="d-flex justify-content-center align-items-center" style={{ height: 300 }}>
                <div className="spinner-border text-primary" role="status">
                    <span className="visually-hidden">Loading...</span>
                </div>
            </div>
        );
    }

    return (
        <div className="paid-transaction-chart">
            <Chart
                options={chartData.options}
                series={chartData.series}
                type="radialBar"
                height={350}
                width="100%"
            />

            <div className="d-flex flex-column gap-3">
                <Card body className="bg-light-subtle">
                    <div className="d-flex gap-2">
                        <div className="flex-shrink-0">
                            <div className="flex-center bg-primary-subtle text-primary rounded-circle" style={{ width: 35, height: 35 }}>
                                <MdPendingActions />
                            </div>
                        </div>
                        <div className="flex-grow-1">
                            <div className="small text-muted">Unpaid</div>
                            <div className="fw-medium">Rp {decimalFormatter(response?.unpaid?.amount || 0)}</div>
                        </div>
                    </div>
                </Card>
                <Card body className="bg-light-subtle">
                    <div className="d-flex gap-2">
                        <div className="flex-center bg-success-subtle text-success rounded-circle" style={{ width: 35, height: 35 }}>
                            <MdDoneAll />
                        </div>
                        <div className="flex-grow-1">
                            <div className="small text-muted">Already Paid</div>
                            <div className="fw-medium">Rp {decimalFormatter(response?.paid?.amount || 0)}</div>
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    );
}
