'use client';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import { useQuery } from '@tanstack/react-query';
import { Skeleton } from "@/components/ui/skeleton";

async function fetchPrescriptionData() {
    const res = await fetch('/api/prescriptions/volume');
    return res.json();
}

export function PrescriptionChart() {
    const { data, isLoading } = useQuery({
        queryKey: ['pharmacy-prescription-chart'],
        queryFn: fetchPrescriptionData
    });

    if (isLoading) return <Skeleton className="w-full h-[300px]" />;

    return (
        <div className="p-4 bg-white rounded-lg shadow">
            <h3 className="font-medium mb-4">Prescription Volume (7 Days)</h3>
            <div className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                    <LineChart data={data}>
                        <CartesianGrid strokeDasharray="3 3" opacity={0.2} />
                        <XAxis
                            dataKey="day"
                            tickFormatter={(value) => value.split('-')[2]} // Show only day number
                        />
                        <YAxis />
                        <Tooltip
                            formatter={(value) => [`${value} prescriptions`, 'Count']}
                            labelFormatter={(label) => `Day ${label.split('-')[2]}`}
                        />
                        <Line
                            type="monotone"
                            dataKey="count"
                            stroke="#8884d8"
                            strokeWidth={2}
                            dot={{ r: 4 }}
                            activeDot={{ r: 6 }}
                        />
                    </LineChart>
                </ResponsiveContainer>
            </div>
        </div>
    );
}