'use client';

import { useQuery } from '@tanstack/react-query';
import { User, Users, Calendar, Plus, Download } from "lucide-react";
import { StatsCard } from '@/components/Dashboard/StatsCard';
import { ConsultationChart } from "@/components/Dashboard/admin/ConsultationChart";
import { RecentConsultations } from "@/components/Dashboard/admin/RecentConsultations";
import { UserDistributionChart } from "@/components/Dashboard/admin/UserDistributionChart";
import { authFetch } from '@/lib/api';
import { Skeleton } from "@/components/ui/skeleton";
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { useState } from 'react';
import CreateAdminModal from '@/components/Dashboard/admin/CreateAdminModal';

async function fetchDashboardStats() {
    return authFetch('/api/admin/stats');
}

export default function AdminDashboard() {
    const { data: stats, isLoading, isError } = useQuery({
        queryKey: ['dashboard-stats'],
        queryFn: fetchDashboardStats,
        refetchInterval: 300000 // Refresh every 5 minutes
    });

    const [isCreateAdminModalOpen, setIsCreateAdminModalOpen] = useState(false);

    const handleDumpDownload = async () => {
        try {
            const res = await fetch("/api/dumpdatabase", {
                method: "GET",
                headers: {
                    "Authorization": `Bearer ${localStorage.getItem("token")}` // adjust if needed
                }
            });

            if (!res.ok) throw new Error("Failed to fetch dump");

            const blob = await res.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement("a");
            a.href = url;
            a.download = `database_dump_${new Date().toISOString().split("T")[0]}.sql`;
            a.click();
            window.URL.revokeObjectURL(url);
        } catch (err) {
            console.error(err);
            alert("Failed to download database dump");
        }
    };

    if (isError) {
        return <div className="p-4 text-red-500">Failed to load dashboard data</div>;
    }

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <h1 className="text-2xl font-bold tracking-tight">Dashboard</h1>
                <div className="flex gap-2">
                    <Button
                        onClick={() => setIsCreateAdminModalOpen(true)}
                        className="bg-blue-500 text-white hover:bg-blue-400 cursor-pointer"
                    >
                        <Plus size={16} />
                        Add Admin
                    </Button>
                    <Button
                        onClick={handleDumpDownload}
                        className="bg-green-500 text-white hover:bg-green-400 cursor-pointer"
                    >
                        <Download size={16} />
                        Dump DB
                    </Button>
                </div>
            </div>

            <CreateAdminModal
                isOpen={isCreateAdminModalOpen}
                onClose={() => setIsCreateAdminModalOpen(false)}
            />

            <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
                {isLoading ? (
                    <>
                        <StatCardSkeleton />
                        <StatCardSkeleton />
                        <StatCardSkeleton />
                        <StatCardSkeleton />
                    </>
                ) : (
                    <>
                        <Link href="/dashboard/admin/patients">
                            <StatsCard
                                title="Total Patients"
                                value={stats?.totalPatients.toLocaleString() || "0"}
                                description="Active patients in system"
                                className="cursor:pointer"
                                icon={<Users />}
                                trend={{
                                    value: `${stats?.patientsTrend || 0}%`,
                                    positive: (stats?.patientsTrend || 0) >= 0
                                }}
                            />
                        </Link>
                        <Link href="/dashboard/admin/doctors">
                            <StatsCard
                                title="Total Doctors"
                                value={stats?.totalDoctors.toLocaleString() || "0"}
                                description="Licensed practitioners"
                                className="cursor:pointer"
                                icon={<User />}
                                trend={{
                                    value: `${stats?.doctorsTrend || 0}%`,
                                    positive: (stats?.doctorsTrend || 0) >= 0
                                }}
                            />
                        </Link>
                        <Link href="/dashboard/admin/consultations">
                            <StatsCard
                                title="Total Consultations"
                                value={stats?.totalConsultations.toLocaleString() || "0"}
                                description="All time consultations"
                                className="cursor:pointer"
                                icon={<Calendar />}
                                trend={{
                                    value: `${stats?.consultationsTrend || 0}%`,
                                    positive: (stats?.consultationsTrend || 0) >= 0
                                }}
                            />
                        </Link>
                        <Link href="/dashboard/admin/users">
                            <StatsCard
                                title="New Users"
                                value={stats?.newUsers.toLocaleString() || "0"}
                                description="Signups this month"
                                className="cursor:pointer"
                                icon={<Users />}
                                trend={{
                                    value: `${stats?.newUsersTrend || 0}%`,
                                    positive: (stats?.newUsersTrend || 0) >= 0
                                }}
                            />
                        </Link>
                    </>
                )}
            </div>
            <div className="grid gap-4 grid-cols-1 lg:grid-cols-4">
                <ConsultationChart />
            </div>

            <div className="grid gap-4 grid-cols-1 lg:grid-cols-4">
                <UserDistributionChart />
                <RecentConsultations />
            </div>
        </div>
    );
}

function StatCardSkeleton() {
    return (
        <div className="p-6 bg-white rounded-lg shadow">
            <div className="flex items-center justify-between">
                <Skeleton className="h-6 w-24" />
                <Skeleton className="h-6 w-6 rounded-full" />
            </div>
            <Skeleton className="h-8 w-full mt-2" />
            <div className="flex items-center mt-4 space-x-2">
                <Skeleton className="h-4 w-16" />
                <Skeleton className="h-4 w-8" />
            </div>
        </div>
    );
}