"use client";

import { useQuery } from "@tanstack/react-query";
import { PageHeader } from "@/src/shared/ui";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useTenantId } from "@/hooks/useTenantId";
import {
  PrescriptionOrdersResourcePage,
  DeliveryIntegrationsResourcePage,
  DeliveryJobIntentsResourcePage,
  PharmaciesResourcePage,
} from "@/src/modules/healthcare/components/entities";
import { AggregateStatsRow, AnalyticsPage, HealthcarePageLoader } from "./shared";

export function PharmacyDashboard() {
  const { tenantId } = useTenantId();
  const rxQ = useQuery({
    queryKey: ["healthcare", tenantId, "pharmacy-all-rx"],
    queryFn: () => healthcareApi.prescriptionOrders.list(tenantId!),
    enabled: !!tenantId,
  });
  const pharmQ = useQuery({
    queryKey: ["healthcare", tenantId, "pharmacies"],
    queryFn: () => healthcareApi.pharmacies.list(tenantId!),
    enabled: !!tenantId,
  });

  if (!tenantId || rxQ.isLoading) return <HealthcarePageLoader />;

  const byStatus = (s: string) => (rxQ.data ?? []).filter((r) => r.status === s).length;

  return (
    <div>
      <PageHeader title="داشبورد داروخانه" description="جریان نسخه و آماده‌سازی." />
      <AggregateStatsRow
        stats={[
          { label: "داروخانه‌ها", value: pharmQ.data?.length ?? 0 },
          { label: "کل نسخه‌ها", value: rxQ.data?.length ?? 0 },
          { label: "ورودی", value: byStatus("submitted") + byStatus("accepted") },
          { label: "آماده", value: byStatus("ready") },
        ]}
      />
    </div>
  );
}

export const PharmacyIncoming = () => <PrescriptionOrdersResourcePage title="نسخه‌های ورودی" status="accepted" />;
export const PharmacyPreparation = () => <PrescriptionOrdersResourcePage title="صف آماده‌سازی" status="preparing" />;
export const PharmacyReady = () => <PrescriptionOrdersResourcePage title="آماده تحویل" status="ready" />;
export const PharmacyDelivered = () => <PrescriptionOrdersResourcePage title="تحویل‌شده" status="completed" />;

export function PharmacyDelivery() {
  return (
    <div className="space-y-8">
      <DeliveryIntegrationsResourcePage title="یکپارچگی تحویل" />
      <DeliveryJobIntentsResourcePage title="Job Intents" />
    </div>
  );
}

export const PharmacyReports = () => <AnalyticsPage title="گزارش داروخانه" />;
