"use client";

import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import {
  PageHeader,
  StatCard,
  Badge,
  Card,
  CardContent,
  DataTable,
  EmptyState,
  PageLoader,
  PageError,
} from "@/src/shared/ui";
import { healthcareApi, type HealthcareAuditLog } from "@/src/modules/healthcare/services/healthcare-api";
import { useTenantId } from "@/hooks/useTenantId";
import { useHealthcareLookups } from "@/src/modules/healthcare/hooks/useHealthcareLookups";
import { StatWidget } from "@/src/modules/healthcare/design-system";

export const HealthcarePageLoader = PageLoader;
export const HealthcarePageError = PageError;

export function useHealthcareServiceMeta() {
  const healthQ = useQuery({
    queryKey: ["healthcare", "health"],
    queryFn: () => healthcareApi.health(),
  });
  const capsQ = useQuery({
    queryKey: ["healthcare", "capabilities"],
    queryFn: () => healthcareApi.capabilities(),
  });
  const metricsQ = useQuery({
    queryKey: ["healthcare", "metrics"],
    queryFn: () => healthcareApi.metrics(),
  });
  return { healthQ, capsQ, metricsQ };
}

export function ServiceMetaBadges() {
  const { healthQ, capsQ } = useHealthcareServiceMeta();
  return (
    <div className="flex flex-wrap items-center gap-2">
      {healthQ.data ? (
        <Badge tone={healthQ.data.status === "ok" ? "success" : "danger"}>
          سرویس {healthQ.data.version}
        </Badge>
      ) : null}
      {capsQ.data ? <Badge tone="default">فاز {capsQ.data.phase}</Badge> : null}
    </div>
  );
}

export function MetricsGrid() {
  const { metricsQ } = useHealthcareServiceMeta();
  if (metricsQ.isLoading) return null;
  if (!metricsQ.data) return null;
  return (
    <Card className="mt-6">
      <CardContent className="pt-5">
        <h2 className="mb-2 font-semibold text-secondary">متریک‌های سرویس</h2>
        {metricsQ.data.note ? (
          <p className="mb-3 text-xs text-[var(--muted)]">{metricsQ.data.note}</p>
        ) : null}
        <div className="flex flex-wrap gap-2">
          {Object.entries(metricsQ.data.metrics).map(([k, v]) => (
            <Badge key={k} tone="default">
              {k}: {String(v)}
            </Badge>
          ))}
        </div>
      </CardContent>
    </Card>
  );
}

export function AuditLogsTable({
  entityType,
  entityId,
  title,
  description,
}: {
  entityType: string;
  entityId: string;
  title: string;
  description?: string;
}) {
  const { tenantId } = useTenantId();
  const logsQ = useQuery({
    queryKey: ["healthcare", tenantId, "audit", entityType, entityId],
    queryFn: () => healthcareApi.audit.list(tenantId!, entityType, entityId),
    enabled: !!tenantId && !!entityId,
  });

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

  return (
    <div>
      <PageHeader title={title} description={description} />
      <DataTable
        columns={[
          { key: "action", header: "عملیات" },
          { key: "entity_type", header: "موجودیت" },
          { key: "message", header: "پیام", render: (r) => String(r.message ?? "—") },
          {
            key: "created_at",
            header: "زمان",
            render: (r) => new Date(String(r.created_at)).toLocaleString("fa-IR"),
          },
        ]}
        rows={(logsQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="رویدادی ثبت نشده" />}
      />
    </div>
  );
}

export function AggregateStatsRow({
  stats,
}: {
  stats: { label: string; value: string | number; hint?: string }[];
}) {
  return (
    <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
      {stats.map((s) => (
        <StatWidget key={s.label} label={s.label} value={s.value} hint={s.hint} />
      ))}
    </div>
  );
}

export function AppointmentsCountStat({ status }: { status?: string }) {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["healthcare", tenantId, "appointments-count", status],
    queryFn: () =>
      healthcareApi.appointments.list(tenantId!, {
        page: 1,
        page_size: 1,
        status,
      }),
    enabled: !!tenantId,
  });
  if (!tenantId || q.isLoading) return <StatCard label="نوبت‌ها" value="…" />;
  return <StatCard label={status ? `نوبت (${status})` : "نوبت‌ها"} value={q.data?.total ?? 0} />;
}

export function ExternalProvidersByKind({
  kind,
  title,
  description,
  accountingLink,
}: {
  kind: "accounting" | "crm" | "communication" | "delivery";
  title: string;
  description: string;
  accountingLink?: boolean;
}) {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["healthcare", tenantId, "external-providers", kind],
    queryFn: () => healthcareApi.externalProviders.list(tenantId!),
    enabled: !!tenantId,
    select: (rows) => rows.filter((p) => p.provider_kind === kind),
  });

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

  return (
    <div>
      <PageHeader
        title={title}
        description={description}
        actions={
          accountingLink ? (
            <Link href="/accounting">
              <Badge tone="default">حسابداری تربت‌یار</Badge>
            </Link>
          ) : undefined
        }
      />
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          { key: "adapter_key", header: "آداپتر" },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <Badge tone="default">{String(r.status)}</Badge>,
          },
        ]}
        rows={(q.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="ارائه‌دهنده‌ای ثبت نشده" />}
      />
    </div>
  );
}

export function SettingsListPage({ title, description }: { title: string; description: string }) {
  const { tenantId } = useTenantId();
  const q = useQuery({
    queryKey: ["healthcare", tenantId, "settings"],
    queryFn: () => healthcareApi.settings.list(tenantId!),
    enabled: !!tenantId,
  });

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

  return (
    <div>
      <PageHeader title={title} description={description} />
      <DataTable
        columns={[
          { key: "key", header: "کلید" },
          {
            key: "value",
            header: "مقدار",
            render: (r) => (
              <span className="text-xs text-[var(--muted)]">
                {JSON.stringify(r.value ?? {})}
              </span>
            ),
          },
          { key: "description", header: "توضیح", render: (r) => String(r.description ?? "—") },
        ]}
        rows={(q.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="تنظیماتی ثبت نشده" />}
      />
    </div>
  );
}

export function MonitoringPage() {
  const { healthQ, capsQ, metricsQ } = useHealthcareServiceMeta();

  if (healthQ.isLoading || capsQ.isLoading) return <HealthcarePageLoader />;
  const err = healthQ.error || capsQ.error || metricsQ.error;
  if (err) return <HealthcarePageError error={err} onRetry={() => healthQ.refetch()} />;

  return (
    <div>
      <PageHeader
        title="مانیتورینگ سرویس"
        description="وضعیت سلامت، قابلیت‌ها و متریک‌های realtime سرویس healthcare."
      />
      <div className="grid gap-4 lg:grid-cols-3">
        <Card>
          <CardContent className="pt-5">
            <h3 className="font-semibold text-secondary">Health</h3>
            <p className="mt-2 text-sm">{healthQ.data?.status}</p>
            <p className="text-xs text-[var(--muted)]">{healthQ.data?.service} v{healthQ.data?.version}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <h3 className="font-semibold text-secondary">Capabilities</h3>
            <p className="mt-2 text-sm">فاز {capsQ.data?.phase}</p>
            <p className="text-xs text-[var(--muted)]">{capsQ.data?.commercial_product}</p>
          </CardContent>
        </Card>
        <Card>
          <CardContent className="pt-5">
            <h3 className="font-semibold text-secondary">Independence</h3>
            <p className="mt-2 text-xs text-[var(--muted)]">
              {capsQ.data?.independence.integration_mode}
            </p>
          </CardContent>
        </Card>
      </div>
      <section className="mt-6 rounded-2xl border border-[var(--border)] bg-[var(--surface)] p-5">
        <h2 className="mb-3 font-semibold text-secondary">قابلیت‌های فعال</h2>
        <ul className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
          {Object.entries(capsQ.data?.features ?? {}).map(([key, on]) => (
            <li
              key={key}
              className="flex items-center justify-between rounded-xl border border-[var(--border)] px-3 py-2 text-sm"
            >
              <span className="text-[var(--muted)]">{key}</span>
              <Badge tone={on ? "success" : "default"}>{on ? "فعال" : "آینده"}</Badge>
            </li>
          ))}
        </ul>
      </section>
      <MetricsGrid />
    </div>
  );
}

export function AnalyticsPage({ title }: { title: string }) {
  const { tenantId } = useTenantId();
  const { clinics, doctors, patients, isLoading } = useHealthcareLookups();
  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "analytics-appointments"],
    queryFn: () => healthcareApi.appointments.list(tenantId!, { page: 1, page_size: 1 }),
    enabled: !!tenantId,
  });
  const rxQ = useQuery({
    queryKey: ["healthcare", tenantId, "analytics-rx"],
    queryFn: () => healthcareApi.prescriptionOrders.list(tenantId!),
    enabled: !!tenantId,
  });
  const { capsQ, metricsQ } = useHealthcareServiceMeta();

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

  return (
    <div>
      <PageHeader title={title} description="تحلیل بر اساس داده‌های واقعی سرویس سلامت." />
      <AggregateStatsRow
        stats={[
          { label: "کلینیک‌ها", value: clinics.length },
          { label: "پزشکان", value: doctors.length },
          { label: "بیماران", value: patients.length },
          { label: "نوبت‌ها", value: apptsQ.data?.total ?? 0 },
          { label: "نسخه‌ها", value: rxQ.data?.length ?? 0 },
          {
            label: "قابلیت‌های فعال",
            value: Object.values(capsQ.data?.features ?? {}).filter(Boolean).length,
          },
        ]}
      />
      <MetricsGrid />
    </div>
  );
}

export type AuditRow = HealthcareAuditLog;
