import { useEffect, useState } from "react";
import Chart from "react-apexcharts";
import { ApexOptions } from "apexcharts";
import axios from "axios";
import DashboardController from "@/actions/App/Http/Controllers/DashboardController";

// Type definitions
interface ChartData {
    series: Array<{
        name: string;
        data: number[];
    }>;
    options: ApexOptions;
}

interface ApiResponse {
    success: boolean;
    data: {
        revenue: number[];
        expense: number[];
        months: string[];
    };
    period: {
        start: string;
        end: string;
    };
}

export default function RevenueExpense() {
    const [chartData, setChartData] = useState<ChartData>({
        series: [],
        options: {},
    });
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        // Fetch real data from API
        const fetchData = async () => {
            try {
                setLoading(true);
                setError(null);

                // API call to revenue-expense endpoint
                const response = await axios.get<ApiResponse>(DashboardController.revenueVsExpense.url(), {
                    params: {
                        // Optional: add date filters
                        // start_date: '2024-01-01',
                        // end_date: '2024-12-31'
                    }
                });

                if (!response.data.success) {
                    throw new Error('Failed to fetch data');
                }

                const { revenue, expense, months } = response.data.data;

                setChartData({
                    series: [
                        {
                            name: "Pendapatan",
                            data: revenue,
                        },
                        {
                            name: "Pengeluaran",
                            data: expense,
                        },
                    ],
                    options: {
                        chart: {
                            type: "line",
                            height: 350,
                            toolbar: { show: true },
                            zoom: { enabled: true },
                            animations: {
                                enabled: true,
                                speed: 800,
                                animateGradually: {
                                    enabled: true,
                                    delay: 150
                                },
                                dynamicAnimation: {
                                    enabled: true,
                                    speed: 350
                                }
                            }
                        },
                        title: {
                            text: 'Pendapatan vs Pengeluaran',
                            align: 'center',
                            style: {
                                fontSize: '18px',
                                fontWeight: 'bold',
                                color: '#6c757d',
                            }
                        },
                        stroke: {
                            width: 3,
                            curve: "smooth",
                        },
                        colors: ["#28a745", "#dc3545"],
                        fill: {
                            type: "gradient",
                            gradient: {
                                shade: "light",
                                type: "vertical",
                                shadeIntensity: 0.3,
                                gradientToColors: ["#20c997", "#e74c3c"],
                                inverseColors: false,
                                opacityFrom: 1.0,
                                opacityTo: 1.0,
                                stops: [0, 100],
                            },
                        },
                        dataLabels: {
                            enabled: false
                        },
                        grid: {
                            borderColor: "#e9ecef",
                            strokeDashArray: 3,
                            xaxis: {
                                lines: { show: true }
                            },
                            yaxis: {
                                lines: { show: true }
                            },
                            padding: {
                                top: 0,
                                right: 30,
                                bottom: 0,
                                left: 20
                            }
                        },
                        xaxis: {
                            categories: months,
                            title: {
                                text: "Month",
                                style: {
                                    color: "#6c757d",
                                    fontSize: "14px",
                                    fontWeight: 600
                                }
                            },
                            labels: {
                                style: {
                                    colors: "#6c757d",
                                    fontSize: "12px"
                                }
                            },
                            axisBorder: {
                                show: true,
                                color: "#e9ecef"
                            },
                            axisTicks: {
                                show: true,
                                color: "#e9ecef"
                            }
                        },
                        yaxis: {
                            title: {
                                text: "Amount (Rp)",
                                style: {
                                    color: "#6c757d",
                                    fontSize: "14px",
                                    fontWeight: 600
                                }
                            },
                            labels: {
                                formatter: (val: number) => {
                                    if (val >= 1000000) {
                                        return `Rp${(val / 1000000).toFixed(0)}M`;
                                    }
                                    return `Rp${val.toLocaleString('id-ID')}`;
                                },
                                style: {
                                    colors: "#6c757d",
                                    fontSize: "12px"
                                }
                            },
                        },
                        legend: {
                            position: "top",
                            horizontalAlign: "right",
                            floating: false,
                            offsetY: -10,
                            labels: {
                                colors: "#6c757d"
                            },
                            markers: {
                                size: 10,
                                strokeWidth: 2
                            }
                        },
                        tooltip: {
                            shared: true,
                            intersect: false,
                            y: {
                                formatter: (val: number) => `Rp${val.toLocaleString('id-ID')}`,
                            },
                            x: {
                                show: true,
                                format: 'dd MMM'
                            }
                        },
                        responsive: [
                            {
                                breakpoint: 992,
                                options: {
                                    chart: {
                                        height: 320
                                    },
                                    title: {
                                        style: {
                                            fontSize: '16px'
                                        }
                                    },
                                    legend: {
                                        position: "bottom",
                                        horizontalAlign: "center"
                                    }
                                }
                            },
                            {
                                breakpoint: 768,
                                options: {
                                    chart: {
                                        height: 300,
                                        toolbar: {
                                            show: false
                                        }
                                    },
                                    title: {
                                        style: {
                                            fontSize: '15px'
                                        }
                                    },
                                    legend: {
                                        position: "bottom",
                                        horizontalAlign: "center"
                                    },
                                    xaxis: {
                                        title: {
                                            style: {
                                                fontSize: "12px"
                                            }
                                        },
                                        labels: {
                                            style: {
                                                fontSize: "11px"
                                            }
                                        }
                                    },
                                    yaxis: {
                                        title: {
                                            style: {
                                                fontSize: "12px"
                                            }
                                        },
                                        labels: {
                                            style: {
                                                fontSize: "11px"
                                            }
                                        }
                                    }
                                }
                            },
                            {
                                breakpoint: 576,
                                options: {
                                    chart: {
                                        height: 280,
                                        toolbar: {
                                            show: false
                                        }
                                    },
                                    title: {
                                        style: {
                                            fontSize: '14px'
                                        }
                                    },
                                    stroke: {
                                        width: 2
                                    },
                                    grid: {
                                        padding: {
                                            right: 10,
                                            left: 10
                                        }
                                    },
                                    xaxis: {
                                        title: {
                                            text: "",
                                            style: {
                                                fontSize: "11px"
                                            }
                                        },
                                        labels: {
                                            style: {
                                                fontSize: "10px"
                                            }
                                        }
                                    },
                                    yaxis: {
                                        title: {
                                            text: "",
                                            style: {
                                                fontSize: "11px"
                                            }
                                        },
                                        labels: {
                                            formatter: (val: number) => {
                                                if (val >= 1000000) {
                                                    return `${(val / 1000000).toFixed(0)}M`;
                                                }
                                                return `${val.toLocaleString('id-ID')}`;
                                            },
                                            style: {
                                                fontSize: "10px"
                                            }
                                        }
                                    }
                                }
                            }
                        ]
                    },
                });
            } catch (error) {
                console.error('Error fetching chart data:', error);
                setError(error instanceof Error ? error.message : 'Failed to fetch data');
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, []);

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

    if (error) {
        return (
            <div className="d-flex justify-content-center align-items-center" style={{ height: 350 }}>
                <div className="text-center text-danger">
                    <i className="bi bi-exclamation-triangle-fill mb-2" style={{ fontSize: '2rem' }}></i>
                    <p className="mb-0">Error loading chart data</p>
                    <small className="text-muted">{error}</small>
                </div>
            </div>
        );
    }

    return (
        <div className="revenue-expense-chart">
            <Chart
                options={chartData.options}
                series={chartData.series}
                type="line"
                height={350}
            />
        </div>
    );
}
