'use client';

import { useQuery } from '@tanstack/react-query';
import { Pill, ClipboardList, Truck, Clock } from "lucide-react";
import { StatsCard } from '@/components/Dashboard/StatsCard';
import { PrescriptionChart } from "@/components/Dashboard/pharmacy/PrescriptionChart";
import { RecentPrescriptions } from "@/components/Dashboard/pharmacy/RecentPrescriptions";
import { authFetch } from '@/lib/api';
import { Skeleton } from "@/components/ui/skeleton";
import { useAuthStore } from '@/stores/authStore'; // ✅ Add this import

async function fetchPharmacyStats() {
  return authFetch('/api/pharmacies/dashboard/stats');
}

export default function PharmacyDashboard() {
  const user = useAuthStore((state) => state.user); // ✅ Access auth state

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

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

  return (
    <div className="space-y-6 p-4">
      {/* Verification alert */}
      {!user?.profile?.isVerified && (
        <div className="bg-yellow-100 text-yellow-800 border border-yellow-300 p-4 rounded text-center">
          <p className="text-sm font-medium">
            Your pharmacy profile is not yet verified. Please update your profile to access all platform features.
          </p>
        </div>
      )}

      {/* Dashboard Stats */}
      <div className="grid gap-4 grid-cols-1 sm:grid-cols-2 lg:grid-cols-4">
        {isLoading ? (
          <>
            <StatCardSkeleton />
            <StatCardSkeleton />
            <StatCardSkeleton />
            <StatCardSkeleton />
          </>
        ) : (
          <>
            <StatsCard
              title="Today's Prescriptions"
              value={stats?.todaysPrescriptions || "0"}
              description="Prescriptions received today"
              icon={<ClipboardList />}
              trend={{
                value: `${stats?.prescriptionsTrend || 0}%`,
                positive: (stats?.prescriptionsTrend || 0) >= 0
              }}
            />
            <StatsCard
              title="Pending Fulfillment"
              value={stats?.pendingFulfillment || "0"}
              description="Awaiting processing"
              icon={<Clock />}
              trend={{
                value: `${stats?.fulfillmentTrend || 0}%`,
                positive: (stats?.fulfillmentTrend || 0) <= 0
              }}
            />
            <StatsCard
              title="Ready for Pickup"
              value={stats?.readyForPickup || "0"}
              description="Completed orders today"
              icon={<Truck />}
              trend={{
                value: `${stats?.pickupTrend || 0}%`,
                positive: (stats?.pickupTrend || 0) >= 0
              }}
            />
            <StatsCard
              title="Total Prescriptions"
              value={stats?.totalPrescriptions || "0"}
              description="All-time prescriptions"
              icon={<Pill />}
              trend={{
                value: `${stats?.totalPrescriptionsTrend || 0}%`,
                positive: (stats?.totalPrescriptionsTrend || 0) >= 0
              }}
            />
          </>
        )}
      </div>

      {/* Charts */}
      <div className="grid gap-4 grid-cols-1 lg:grid-cols-3">
        <PrescriptionChart />
      </div>

      {/* Recent Prescriptions */}
      <div className="grid gap-4 grid-cols-1">
        <RecentPrescriptions />
      </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>
  );
}