"use client";

import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import {
  PageHeader,
  LoadingState,
  ErrorState,
  DataTable,
  EmptyState,
  Badge,
  Button,
} from "@/src/shared/ui";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useHealthcarePatientContext } from "@/src/modules/healthcare/hooks/useHealthcarePatientContext";
import { useHealthcareLookups } from "@/src/modules/healthcare/hooks/useHealthcareLookups";
import {
  AppointmentCard,
  PatientCard,
  PrescriptionCard,
  StatWidget,
} from "@/src/modules/healthcare/design-system";
import {
  AggregateStatsRow,
  AnalyticsPage,
  ExternalProvidersByKind,
  HealthcarePageError,
  HealthcarePageLoader,
  ServiceMetaBadges,
  SettingsListPage,
} from "./shared";

function PatientGate({ children }: { children: (ctx: ReturnType<typeof useHealthcarePatientContext>) => React.ReactNode }) {
  const ctx = useHealthcarePatientContext();
  if (ctx.isLoading) return <HealthcarePageLoader label="در حال بارگذاری پروفایل بیمار…" />;
  if (ctx.error) return <HealthcarePageError error={ctx.error} onRetry={() => ctx.refetch()} />;
  if (!ctx.tenantId || !ctx.patientId) {
    return <ErrorState message="پروفایل بیمار برای این workspace یافت نشد." />;
  }
  return <>{children(ctx)}</>;
}

export function PatientDashboard() {
  return (
    <PatientGate>
      {(ctx) => <PatientDashboardInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} patient={ctx.patient!} />}
    </PatientGate>
  );
}

function PatientDashboardInner({
  tenantId,
  patientId,
  patient,
}: {
  tenantId: string;
  patientId: string;
  patient: { display_name: string };
}) {
  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, patientId, "portal-appointments"],
    queryFn: () => healthcareApi.patientPortal.appointments(tenantId, patientId),
  });
  const docsQ = useQuery({
    queryKey: ["healthcare", tenantId, patientId, "portal-docs"],
    queryFn: () => healthcareApi.patientPortal.documents(tenantId, patientId),
  });
  const { doctorName } = useHealthcareLookups();

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

  const upcoming = (apptsQ.data?.items ?? []).filter(
    (a) => new Date(a.scheduled_start) >= new Date()
  );

  return (
    <div>
      <PageHeader
        title={`سلام ${patient.display_name}`}
        description="داشبورد بیمار — نوبت‌ها و پرونده از API واقعی."
        actions={<ServiceMetaBadges />}
      />
      <AggregateStatsRow
        stats={[
          { label: "نوبت‌های آینده", value: upcoming.length },
          { label: "کل نوبت‌ها", value: apptsQ.data?.total ?? 0 },
          { label: "اسناد", value: docsQ.data?.length ?? 0 },
        ]}
      />
      <section className="mt-8 space-y-3">
        <h2 className="font-semibold text-secondary">نوبت‌های پیش‌رو</h2>
        {upcoming.length === 0 ? (
          <EmptyState
            title="نوبت آینده‌ای ندارید"
            action={
              <Link href="/healthcare/patient/appointments/book">
                <Button>رزرو نوبت</Button>
              </Link>
            }
          />
        ) : (
          upcoming.slice(0, 5).map((a) => (
            <AppointmentCard key={a.id} appointment={a} doctorName={doctorName(a.doctor_id)} />
          ))
        )}
      </section>
    </div>
  );
}

function PatientAppointmentsList({ upcoming }: { upcoming: boolean }) {
  return (
    <PatientGate>
      {(ctx) => (
        <PatientAppointmentsListInner
          tenantId={ctx.tenantId!}
          patientId={ctx.patientId!}
          upcoming={upcoming}
        />
      )}
    </PatientGate>
  );
}

function PatientAppointmentsListInner({
  tenantId,
  patientId,
  upcoming,
}: {
  tenantId: string;
  patientId: string;
  upcoming: boolean;
}) {
  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, patientId, "appointments", upcoming],
    queryFn: () => healthcareApi.patientPortal.appointments(tenantId, patientId),
  });
  const { doctorName } = useHealthcareLookups();

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

  const now = new Date();
  const items = (apptsQ.data?.items ?? []).filter((a) =>
    upcoming ? new Date(a.scheduled_start) >= now : new Date(a.scheduled_start) < now
  );

  return (
    <div>
      <PageHeader
        title={upcoming ? "نوبت‌های آینده" : "سوابق نوبت"}
        description="لیست نوبت‌ها از patient-portal API."
      />
      <div className="space-y-3">
        {items.length === 0 ? (
          <EmptyState title="موردی یافت نشد" />
        ) : (
          items.map((a) => (
            <AppointmentCard key={a.id} appointment={a} doctorName={doctorName(a.doctor_id)} />
          ))
        )}
      </div>
    </div>
  );
}

export function PatientAppointmentsUpcoming() {
  return <PatientAppointmentsList upcoming />;
}

export function PatientAppointmentsPast() {
  return <PatientAppointmentsList upcoming={false} />;
}

export function PatientAppointmentsBook() {
  return (
    <PatientGate>
      {(ctx) => (
        <PatientBookInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />
      )}
    </PatientGate>
  );
}

function PatientBookInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const { doctors, clinics } = useHealthcareLookups();
  const typesQ = useQuery({
    queryKey: ["healthcare", tenantId, "appointment-types"],
    queryFn: () => healthcareApi.appointmentTypes.list(tenantId),
  });

  if (typesQ.isLoading) return <HealthcarePageLoader />;

  return (
    <div>
      <PageHeader
        title="رزرو نوبت"
        description="انتخاب پزشک و کلینیک — رزرو از طریق patient-portal."
        actions={
          <Link href="/healthcare/site/book">
            <Button variant="outline">رزرو عمومی</Button>
          </Link>
        }
      />
      <div className="grid gap-4 sm:grid-cols-2">
        <StatWidget label="پزشکان فعال" value={doctors.filter((d) => d.status === "active").length} />
        <StatWidget label="کلینیک‌ها" value={clinics.length} />
      </div>
      <div className="mt-6">
        <DataTable
          columns={[
            { key: "display_name", header: "پزشک" },
            { key: "specialty", header: "تخصص", render: (r) => String(r.specialty ?? "—") },
            { key: "code", header: "کد" },
          ]}
          rows={doctors as unknown as Record<string, unknown>[]}
          empty={<EmptyState title="پزشکی ثبت نشده" />}
        />
      </div>
      <section className="mt-6">
        <h2 className="mb-3 font-semibold text-secondary">انواع نوبت</h2>
        <DataTable
          columns={[
            { key: "name", header: "نام" },
            { key: "default_duration_minutes", header: "مدت (دقیقه)" },
            { key: "status", header: "وضعیت" },
          ]}
          rows={(typesQ.data ?? []) as unknown as Record<string, unknown>[]}
          empty={<EmptyState title="نوع نوبتی تعریف نشده" />}
        />
      </section>
    </div>
  );
}

export function PatientMedicalHistory() {
  return (
    <PatientGate>
      {(ctx) => <PatientMedicalHistoryInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />}
    </PatientGate>
  );
}

function PatientMedicalHistoryInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const patientsQ = useQuery({
    queryKey: ["healthcare", tenantId, "patient", patientId],
    queryFn: () => healthcareApi.patients.get(tenantId, patientId),
  });

  if (patientsQ.isLoading) return <HealthcarePageLoader />;
  if (patientsQ.error) return <HealthcarePageError error={patientsQ.error} onRetry={() => patientsQ.refetch()} />;

  const p = patientsQ.data!;

  return (
    <div>
      <PageHeader title="سوابق پزشکی" description="اطلاعات پروفایل بیمار از API." />
      <DataTable
        columns={[
          { key: "field", header: "فیلد" },
          { key: "value", header: "مقدار" },
        ]}
        rows={[
          { field: "نام", value: p.display_name },
          { field: "کد", value: p.code },
          { field: "وضعیت", value: p.status },
          { field: "تاریخ تولد", value: p.date_of_birth ?? "—" },
          { field: "جنسیت", value: p.gender ?? "—" },
        ]}
      />
    </div>
  );
}

export function PatientPrescriptions() {
  return (
    <PatientGate>
      {(ctx) => <PatientPrescriptionsInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />}
    </PatientGate>
  );
}

function PatientPrescriptionsInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const rxQ = useQuery({
    queryKey: ["healthcare", tenantId, "prescriptions", patientId],
    queryFn: () => healthcareApi.prescriptionOrders.list(tenantId),
    select: (rows) => rows.filter((r) => r.patient_id === patientId),
  });

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

  return (
    <div>
      <PageHeader title="نسخه‌ها" description="نسخه‌های مرتبط با بیمار." />
      <div className="space-y-3">
        {(rxQ.data ?? []).length === 0 ? (
          <EmptyState title="نسخه‌ای ثبت نشده" />
        ) : (
          (rxQ.data ?? []).map((o) => <PrescriptionCard key={o.id} order={o} />)
        )}
      </div>
    </div>
  );
}

export function PatientLabResults() {
  return (
    <PatientGate>
      {(ctx) => <PatientLabResultsInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />}
    </PatientGate>
  );
}

function PatientLabResultsInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const docsQ = useQuery({
    queryKey: ["healthcare", tenantId, patientId, "documents"],
    queryFn: () => healthcareApi.patientPortal.documents(tenantId, patientId),
  });

  if (docsQ.isLoading) return <HealthcarePageLoader />;
  if (docsQ.error) return <HealthcarePageError error={docsQ.error} onRetry={() => docsQ.refetch()} />;

  const immunizationDocs = (docsQ.data ?? []).filter(
    (d) => d.document_type === "immunization" || d.document_type === "lab"
  );

  return (
    <div>
      <PageHeader
        title="نتایج آزمایش"
        description="اسناد بالینی و immunization از patient-portal documents."
      />
      <DataTable
        columns={[
          { key: "title", header: "عنوان" },
          { key: "code", header: "کد" },
          { key: "document_type", header: "نوع", render: (r) => String(r.document_type ?? "—") },
        ]}
        rows={immunizationDocs as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="نتیجه آزمایشی ثبت نشده" />}
      />
    </div>
  );
}

export function PatientInvoices() {
  return (
    <ExternalProvidersByKind
      kind="accounting"
      title="صورتحساب"
      description="ارائه‌دهندگان حسابداری متصل — جزئیات مالی در ماژول حسابداری."
      accountingLink
    />
  );
}

export function PatientPayments() {
  return (
    <ExternalProvidersByKind
      kind="accounting"
      title="پرداخت‌ها"
      description="یکپارچگی پرداخت از external-providers نوع accounting."
      accountingLink
    />
  );
}

export function PatientProfile() {
  return (
    <PatientGate>
      {(ctx) => <PatientProfileInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />}
    </PatientGate>
  );
}

function PatientProfileInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const profileQ = useQuery({
    queryKey: ["healthcare", tenantId, patientId, "portal-me"],
    queryFn: () => healthcareApi.patientPortal.me(tenantId, patientId),
  });
  const patientQ = useQuery({
    queryKey: ["healthcare", tenantId, "patient", patientId],
    queryFn: () => healthcareApi.patients.get(tenantId, patientId),
  });

  if (profileQ.isLoading || patientQ.isLoading) return <HealthcarePageLoader />;
  if (profileQ.error) return <HealthcarePageError error={profileQ.error} onRetry={() => profileQ.refetch()} />;

  return (
    <div>
      <PageHeader title="پروفایل" description="پروفایل patient-portal و اطلاعات بیمار." />
      {patientQ.data ? <PatientCard patient={patientQ.data} /> : null}
      <div className="mt-6">
        <DataTable
          columns={[
            { key: "field", header: "فیلد" },
            { key: "value", header: "مقدار" },
          ]}
          rows={[
            { field: "زبان ترجیحی", value: profileQ.data?.preferred_language ?? "—" },
            { field: "کلینیک ترجیحی", value: profileQ.data?.preferred_clinic_id ?? "—" },
          ]}
        />
      </div>
    </div>
  );
}

export function PatientFamily() {
  const { tenantId } = useHealthcarePatientContext();
  const patientsQ = useQuery({
    queryKey: ["healthcare", tenantId, "family-patients"],
    queryFn: () => healthcareApi.patients.list(tenantId!),
    enabled: !!tenantId,
  });

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

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

export function PatientNotifications() {
  return (
    <PatientGate>
      {(ctx) => <PatientNotificationsInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />}
    </PatientGate>
  );
}

function PatientNotificationsInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const prefsQ = useQuery({
    queryKey: ["healthcare", tenantId, patientId, "notification-prefs"],
    queryFn: () => healthcareApi.patientPortal.notificationPreferences(tenantId, patientId),
  });

  if (prefsQ.isLoading) return <HealthcarePageLoader />;
  if (prefsQ.error) return <HealthcarePageError error={prefsQ.error} onRetry={() => prefsQ.refetch()} />;

  return (
    <div>
      <PageHeader title="اعلان‌ها" description="ترجیحات اعلان patient-portal." />
      <DataTable
        columns={[
          { key: "channel", header: "کانال" },
          { key: "template_key", header: "قالب" },
          {
            key: "enabled",
            header: "فعال",
            render: (r) => (
              <Badge tone={r.enabled ? "success" : "default"}>{r.enabled ? "بله" : "خیر"}</Badge>
            ),
          },
        ]}
        rows={(prefsQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="ترجیحی ثبت نشده" />}
      />
    </div>
  );
}

export function PatientMessages() {
  return (
    <PatientGate>
      {(ctx) => (
        <PatientMessagesInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />
      )}
    </PatientGate>
  );
}

function PatientMessagesInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const logsQ = useQuery({
    queryKey: ["healthcare", tenantId, "audit", "patient", patientId],
    queryFn: () => healthcareApi.audit.list(tenantId, "patient", patientId),
  });

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

  return (
    <div>
      <PageHeader title="پیام‌ها" description="رویدادهای audit مرتبط با بیمار." />
      <DataTable
        columns={[
          { key: "action", 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 PatientFavorites() {
  return <SettingsListPage title="علاقه‌مندی‌ها" description="تنظیمات ذخیره‌شده workspace (settings API)." />;
}

export function PatientReviews() {
  return (
    <PatientGate>
      {(ctx) => <PatientReviewsInner tenantId={ctx.tenantId!} patientId={ctx.patientId!} />}
    </PatientGate>
  );
}

function PatientReviewsInner({ tenantId, patientId }: { tenantId: string; patientId: string }) {
  const docsQ = useQuery({
    queryKey: ["healthcare", tenantId, patientId, "review-docs"],
    queryFn: () => healthcareApi.patientPortal.documents(tenantId, patientId),
  });

  if (docsQ.isLoading) return <HealthcarePageLoader />;
  if (docsQ.error) return <HealthcarePageError error={docsQ.error} onRetry={() => docsQ.refetch()} />;

  return (
    <div>
      <PageHeader title="نظرات" description="اسناد و بازخورد ذخیره‌شده بیمار." />
      <DataTable
        columns={[
          { key: "title", header: "عنوان" },
          { key: "code", header: "کد" },
          { key: "document_type", header: "نوع", render: (r) => String(r.document_type ?? "—") },
        ]}
        rows={(docsQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="نظری ثبت نشده" />}
      />
    </div>
  );
}

export function PatientSettings() {
  return <SettingsListPage title="تنظیمات بیمار" description="تنظیمات کلینیک/workspace." />;
}
