"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 { useHealthcareLookups } from "@/src/modules/healthcare/hooks/useHealthcareLookups";
import {
  AppointmentCard,
  DoctorCard,
  PatientCard,
  QueueRow,
  StatWidget,
} from "@/src/modules/healthcare/design-system";
import {
  AggregateStatsRow,
  AnalyticsPage,
  ExternalProvidersByKind,
  HealthcarePageError,
  HealthcarePageLoader,
} from "./shared";

export function ReceptionDashboard() {
  const { tenantId } = useTenantId();
  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "reception-appts"],
    queryFn: () => healthcareApi.appointments.list(tenantId!, { page_size: 10 }),
    enabled: !!tenantId,
  });
  const waitQ = useQuery({
    queryKey: ["healthcare", tenantId, "waiting-list"],
    queryFn: () => healthcareApi.waitingList.list(tenantId!),
    enabled: !!tenantId,
  });
  const visitsQ = useQuery({
    queryKey: ["healthcare", tenantId, "visit-sessions-queue"],
    queryFn: () => healthcareApi.visitSessions.list(tenantId!, { status: "queued" }),
    enabled: !!tenantId,
  });

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

  return (
    <div>
      <PageHeader title="داشبورد پذیرش" description="صف، نوبت‌ها و لیست انتظار." />
      <AggregateStatsRow
        stats={[
          { label: "نوبت‌های امروز", value: apptsQ.data?.total ?? 0 },
          { label: "لیست انتظار", value: waitQ.data?.length ?? 0 },
          { label: "در صف ویزیت", value: visitsQ.data?.length ?? 0 },
        ]}
      />
    </div>
  );
}

export function ReceptionQueue() {
  const { tenantId } = useTenantId();
  const { patientName, doctorName } = useHealthcareLookups();
  const visitsQ = useQuery({
    queryKey: ["healthcare", tenantId, "queue"],
    queryFn: () => healthcareApi.visitSessions.list(tenantId!),
    enabled: !!tenantId,
  });

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

  return (
    <div>
      <PageHeader title="صف نوبت" description="جلسات ویزیت فعال." />
      <div className="space-y-3">
        {(visitsQ.data ?? []).map((v) => (
          <QueueRow
            key={v.id}
            position={v.queue_position}
            title={patientName(v.patient_id)}
            subtitle={doctorName(v.doctor_id)}
            status={v.status}
          />
        ))}
      </div>
      {(visitsQ.data ?? []).length === 0 ? <EmptyState title="صف خالی است" /> : null}
    </div>
  );
}

export function ReceptionWalkIn() {
  const { tenantId } = useTenantId();
  const waitQ = useQuery({
    queryKey: ["healthcare", tenantId, "walk-in"],
    queryFn: () => healthcareApi.waitingList.list(tenantId!),
    enabled: !!tenantId,
  });
  const { patientName, doctorName } = useHealthcareLookups();

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

  return (
    <div>
      <PageHeader title="مراجعه حضوری" description="لیست انتظار waiting-list API." />
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          {
            key: "patient_id",
            header: "بیمار",
            render: (r) => patientName(String(r.patient_id)),
          },
          {
            key: "doctor_id",
            header: "پزشک",
            render: (r) => (r.doctor_id ? doctorName(String(r.doctor_id)) : "—"),
          },
          { key: "priority", header: "اولویت" },
        ]}
        rows={(waitQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="مراجعه‌ای در انتظار نیست" />}
      />
    </div>
  );
}

export function ReceptionCalendar() {
  const { tenantId } = useTenantId();
  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "reception-calendar"],
    queryFn: () => healthcareApi.appointments.list(tenantId!, { page_size: 100 }),
    enabled: !!tenantId,
  });
  const { doctorName } = useHealthcareLookups();

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

  return (
    <div>
      <PageHeader title="تقویم نوبت" description={`${apptsQ.data?.total ?? 0} نوبت`} />
      <div className="space-y-3">
        {(apptsQ.data?.items ?? []).map((a) => (
          <AppointmentCard key={a.id} appointment={a} doctorName={doctorName(a.doctor_id)} />
        ))}
      </div>
    </div>
  );
}

export function ReceptionDoctors() {
  const { doctors, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;

  return (
    <div>
      <PageHeader title="پزشکان" description="لیست پزشکان workspace." />
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {doctors.map((d) => (
          <DoctorCard key={d.id} doctor={d} />
        ))}
      </div>
      {doctors.length === 0 ? <EmptyState title="پزشکی ثبت نشده" /> : null}
    </div>
  );
}

export function ReceptionPatients() {
  const { patients, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;

  return (
    <div>
      <PageHeader title="بیماران" description="لیست بیماران workspace." />
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {patients.map((p) => (
          <PatientCard key={p.id} patient={p} />
        ))}
      </div>
      {patients.length === 0 ? <EmptyState title="بیماری ثبت نشده" /> : null}
    </div>
  );
}

export function ReceptionCheckIn() {
  const { tenantId } = useTenantId();
  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "check-in"],
    queryFn: () =>
      healthcareApi.appointments.list(tenantId!, { status: "confirmed", page_size: 50 }),
    enabled: !!tenantId,
  });
  const { doctorName, patientName } = useHealthcareLookups();

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

  return (
    <div>
      <PageHeader title="پذیرش" description="نوبت‌های تأییدشده آماده پذیرش." />
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          {
            key: "patient_id",
            header: "بیمار",
            render: (r) => patientName(String(r.patient_id)),
          },
          {
            key: "doctor_id",
            header: "پزشک",
            render: (r) => doctorName(String(r.doctor_id)),
          },
          {
            key: "scheduled_start",
            header: "زمان",
            render: (r) => new Date(String(r.scheduled_start)).toLocaleString("fa-IR"),
          },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <Badge tone="success">{String(r.status)}</Badge>,
          },
        ]}
        rows={(apptsQ.data?.items ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="نوبت تأییدشده‌ای نیست" />}
      />
    </div>
  );
}

export function ReceptionCheckOut() {
  const { tenantId } = useTenantId();
  const visitsQ = useQuery({
    queryKey: ["healthcare", tenantId, "check-out"],
    queryFn: () => healthcareApi.visitSessions.list(tenantId!, { status: "in_progress" }),
    enabled: !!tenantId,
  });
  const { patientName } = useHealthcareLookups();

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

  return (
    <div>
      <PageHeader title="ترخیص" description="ویزیت‌های در حال انجام." />
      <div className="space-y-3">
        {(visitsQ.data ?? []).map((v) => (
          <QueueRow
            key={v.id}
            position={v.queue_position}
            title={patientName(v.patient_id)}
            subtitle={v.code}
            status={v.status}
          />
        ))}
      </div>
      {(visitsQ.data ?? []).length === 0 ? <EmptyState title="ویزیت فعالی نیست" /> : null}
    </div>
  );
}

export function ReceptionPayments() {
  return (
    <ExternalProvidersByKind
      kind="accounting"
      title="پرداخت پذیرش"
      description="یکپارچگی حسابداری برای پرداخت."
      accountingLink
    />
  );
}

export function ReceptionReports() {
  return <AnalyticsPage title="گزارش پذیرش" />;
}
