"use client";

import { useQuery } from "@tanstack/react-query";
import { PageHeader, EmptyState, ErrorState } from "@/src/shared/ui";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useHealthcareDoctorContext } from "@/src/modules/healthcare/hooks/useHealthcareDoctorContext";
import {
  AppointmentsResourcePage,
  AppointmentsCalendarPage,
  AvailabilityWindowsResourcePage,
  SchedulesResourcePage,
  PrescriptionOrdersResourcePage,
  MedicalRecordsResourcePage,
  SettingsResourcePage,
  ExternalProvidersResourcePage,
  PatientsResourcePage,
} from "@/src/modules/healthcare/components/entities";
import {
  AggregateStatsRow,
  AnalyticsPage,
  HealthcarePageError,
  HealthcarePageLoader,
  ServiceMetaBadges,
} from "./shared";
import { AppointmentCard } from "@/src/modules/healthcare/design-system";

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

export function DoctorDashboard() {
  return (
    <DoctorGate>
      {(ctx) => <DoctorDashboardInner tenantId={ctx.tenantId!} doctorId={ctx.doctorId!} doctor={ctx.doctor!} />}
    </DoctorGate>
  );
}

function DoctorDashboardInner({
  tenantId,
  doctorId,
  doctor,
}: {
  tenantId: string;
  doctorId: string;
  doctor: { display_name: string };
}) {
  const dashQ = useQuery({
    queryKey: ["healthcare", tenantId, doctorId, "dashboard"],
    queryFn: () => healthcareApi.doctorPanel.dashboard(tenantId, doctorId),
  });

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

  const d = dashQ.data!;

  return (
    <div>
      <PageHeader
        title={`داشبورد ${doctor.display_name}`}
        description="آمار امروز و نوبت‌های پیش‌رو."
        actions={<ServiceMetaBadges />}
      />
      <AggregateStatsRow
        stats={[
          { label: "صف", value: d.queued_count },
          { label: "در حال ویزیت", value: d.in_progress_count },
          { label: "تکمیل امروز", value: d.completed_today_count },
        ]}
      />
      <section className="mt-8 space-y-3">
        <h2 className="font-semibold text-secondary">نوبت‌های پیش‌رو</h2>
        {d.upcoming_appointments.length === 0 ? (
          <EmptyState title="نوبت پیش‌رویی نیست" />
        ) : (
          d.upcoming_appointments.map((a) => (
            <AppointmentCard key={a.id} appointment={a} doctorName={doctor.display_name} />
          ))
        )}
      </section>
    </div>
  );
}

export function DoctorScheduleToday() {
  return (
    <DoctorGate>
      {(ctx) => <AppointmentsCalendarPage title="برنامه امروز" doctorId={ctx.doctorId!} mode="day" />}
    </DoctorGate>
  );
}

export function DoctorScheduleCalendar() {
  return (
    <DoctorGate>
      {(ctx) => <AppointmentsCalendarPage title="تقویم نوبت‌ها" doctorId={ctx.doctorId!} mode="week" />}
    </DoctorGate>
  );
}

export function DoctorAvailability() {
  return (
    <DoctorGate>
      {(ctx) => (
        <div className="space-y-8">
          <AvailabilityWindowsResourcePage title="پنجره‌های availability" doctorId={ctx.doctorId!} />
          <SchedulesResourcePage title="برنامه هفتگی" doctorId={ctx.doctorId!} />
        </div>
      )}
    </DoctorGate>
  );
}

export function DoctorLeaves() {
  return (
    <DoctorGate>
      {(ctx) => <AvailabilityWindowsResourcePage title="مرخصی / блок availability" doctorId={ctx.doctorId!} readOnly />}
    </DoctorGate>
  );
}

export function DoctorAppointments() {
  return (
    <DoctorGate>
      {(ctx) => <AppointmentsResourcePage title="نوبت‌های من" doctorId={ctx.doctorId!} />}
    </DoctorGate>
  );
}

export function DoctorPatients() {
  return <PatientsResourcePage title="بیماران" readOnly />;
}

export function DoctorMedicalRecords() {
  return <MedicalRecordsResourcePage title="پرونده پزشکی" />;
}

export function DoctorPrescriptions() {
  return (
    <DoctorGate>
      {(ctx) => <PrescriptionOrdersResourcePage title="نسخه‌ها" doctorId={ctx.doctorId!} />}
    </DoctorGate>
  );
}

export function DoctorReports() {
  return (
    <DoctorGate>
      {() => <AnalyticsPage title="گزارش پزشک" />}
    </DoctorGate>
  );
}

export const DoctorAnalytics = () => <AnalyticsPage title="آنالیتیکس پزشک" />;
export const DoctorIncome = () => <ExternalProvidersResourcePage kind="accounting" title="درآمد / حسابداری" />;
export const DoctorNotifications = () => <ExternalProvidersResourcePage kind="communication" title="اعلان‌ها" />;
export const DoctorMessages = () => <ExternalProvidersResourcePage kind="communication" title="پیام‌ها" />;
export const DoctorSettings = () => <SettingsResourcePage title="تنظیمات پزشک" />;
