"use client";

import { useQuery } from "@tanstack/react-query";
import { PageHeader, DataTable, EmptyState, Badge } from "@/src/shared/ui";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useTenantId } from "@/hooks/useTenantId";
import { PrescriptionCard, StatWidget } from "@/src/modules/healthcare/design-system";
import {
  AggregateStatsRow,
  AnalyticsPage,
  HealthcarePageError,
  HealthcarePageLoader,
} from "./shared";

function PrescriptionsByStatus({ status, title }: { status: string; title: string }) {
  const { tenantId } = useTenantId();
  const rxQ = useQuery({
    queryKey: ["healthcare", tenantId, "rx", status],
    queryFn: () => healthcareApi.prescriptionOrders.list(tenantId!),
    enabled: !!tenantId,
    select: (rows) => rows.filter((r) => r.status === status),
  });

  if (!tenantId || rxQ.isLoading) return <HealthcarePageLoader />;
  if (rxQ.error) return <HealthcarePageError error={rxQ.error} onRetry={() => rxQ.refetch()} />;

  return (
    <div>
      <PageHeader title={title} description={`${(rxQ.data ?? []).length} نسخه — status: ${status}`} />
      <div className="space-y-3">
        {(rxQ.data ?? []).map((o) => (
          <PrescriptionCard key={o.id} order={o} />
        ))}
      </div>
      {(rxQ.data ?? []).length === 0 ? <EmptyState title="نسخه‌ای در این وضعیت نیست" /> : null}
    </div>
  );
}

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 function PharmacyIncoming() {
  return <PrescriptionsByStatus status="accepted" title="نسخه‌های ورودی" />;
}

export function PharmacyPreparation() {
  return <PrescriptionsByStatus status="preparing" title="صف آماده‌سازی" />;
}

export function PharmacyReady() {
  return <PrescriptionsByStatus status="ready" title="آماده تحویل" />;
}

export function PharmacyDelivered() {
  return <PrescriptionsByStatus status="completed" title="تحویل‌شده" />;
}

export function PharmacyDelivery() {
  const { tenantId } = useTenantId();
  const delQ = useQuery({
    queryKey: ["healthcare", tenantId, "delivery-integrations"],
    queryFn: () => healthcareApi.deliveryIntegrations.list(tenantId!),
    enabled: !!tenantId,
  });
  const jobsQ = useQuery({
    queryKey: ["healthcare", tenantId, "delivery-jobs"],
    queryFn: () => healthcareApi.deliveryJobIntents.list(tenantId!),
    enabled: !!tenantId,
  });

  if (!tenantId || delQ.isLoading) return <HealthcarePageLoader />;
  if (delQ.error) return <HealthcarePageError error={delQ.error} onRetry={() => delQ.refetch()} />;

  return (
    <div>
      <PageHeader title="درخواست ارسال" description="یکپارچگی و job intents تحویل." />
      <h2 className="mb-3 font-semibold text-secondary">یکپارچگی‌ها</h2>
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <Badge tone="default">{String(r.status)}</Badge>,
          },
        ]}
        rows={(delQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="یکپارچگی ثبت نشده" />}
      />
      <h2 className="mb-3 mt-8 font-semibold text-secondary">Job Intents</h2>
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "status", header: "وضعیت" },
          {
            key: "delivery_job_ref",
            header: "ارجاع",
            render: (r) => String(r.delivery_job_ref ?? "—"),
          },
        ]}
        rows={(jobsQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="درخواست ارسالی نیست" />}
      />
    </div>
  );
}

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