
import { useQuery } from '@tanstack/react-query';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';

import { Skeleton } from "@/components/ui/skeleton";
import { authFetch } from "@/lib/api";

async function fetchConsultationData() {
    return authFetch('/api/admin/consultations');
}

export const ConsultationChart = () => {
    const { data, isLoading, isError } = useQuery({
        queryKey: ['consultation-chart'],
        queryFn: fetchConsultationData,
    });

    if (isLoading) {
        return (
            <Card className="col-span-4 border-gray-200">
                <CardHeader>
                    <CardTitle>Weekly Consultations</CardTitle>
                </CardHeader>
                <CardContent className="pt-2">
                    <div className="h-[300px]">
                        <Skeleton className="h-full w-full" />
                    </div>
                </CardContent>
            </Card>
        );
    }

    if (isError) {
        return (
            <Card className="col-span-4 border-gray-200">
                <CardHeader>
                    <CardTitle>Weekly Consultations</CardTitle>
                </CardHeader>
                <CardContent className="pt-2">
                    <div className="h-[300px] flex items-center justify-center text-red-500">
                        Failed to load consultation data
                    </div>
                </CardContent>
            </Card>
        );
    }

    return (
        <Card className="col-span-4 border-gray-200">
            <CardHeader>
                <CardTitle>Weekly Consultations</CardTitle>
            </CardHeader>
            <CardContent className="pt-2">
                <div className="h-[300px]">
                    <ResponsiveContainer width="100%" height="100%">
                        <BarChart data={data}>
                            <CartesianGrid strokeDasharray="3 3" vertical={false} />
                            <XAxis dataKey="name" />
                            <YAxis />
                            <Tooltip
                                contentStyle={{
                                    backgroundColor: 'white',
                                    borderRadius: '8px',
                                    border: '1px solid #e2e8f0'
                                }}
                            />
                            <Bar dataKey="consultations" fill="#38BDF8" radius={[4, 4, 0, 0]} />
                        </BarChart>
                    </ResponsiveContainer>
                </div>
            </CardContent>
        </Card>
    );
};
