'use client';
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { useQuery } from '@tanstack/react-query';
import { Skeleton } from "@/components/ui/skeleton";

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

async function fetchInventoryData() {
    const res = await fetch('/api/pharmacy/inventory/status');
    return res.json();
}

export function InventoryStatusChart() {
    const { data, isLoading } = useQuery({
        queryKey: ['pharmacy-inventory-chart'],
        queryFn: fetchInventoryData
    });

    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">Inventory Status</h3>
            <div className="h-[300px]">
                <ResponsiveContainer width="100%" height="100%">
                    <PieChart>
                        <Pie
                            data={data}
                            cx="50%"
                            cy="50%"
                            innerRadius={60}
                            outerRadius={80}
                            paddingAngle={5}
                            dataKey="value"
                            label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                        >
                            {data?.map((_, index) => (
                                <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                            ))}
                        </Pie>
                        <Tooltip
                            formatter={(value, name) => [`${value} items`, name]}
                        />
                        <Legend />
                    </PieChart>
                </ResponsiveContainer>
            </div>
        </div>
    );
}