"use client";

import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { HC } from "@/src/modules/healthcare/constants/permissions";
import { useTenantId } from "@/hooks/useTenantId";
import { useHealthcareLookups } from "@/src/modules/healthcare/hooks/useHealthcareLookups";
import {
  HealthcareResourceWorkspace,
  type ResourceConfig,
} from "@/src/modules/healthcare/components/crud/HealthcareResourceWorkspace";
import {
  PageHeader,
  AppointmentCalendar,
  Tabs,
  type CalendarAppointment,
} from "@/src/shared/ui";
import { HealthcarePageLoader, HealthcarePageError } from "@/src/modules/healthcare/pages/shared";

const lifecycleStatusOptions = [
  { value: "draft", label: "پیش‌نویس" },
  { value: "active", label: "فعال" },
  { value: "inactive", label: "غیرفعال" },
];

export function AppointmentsResourcePage(props: {
  title?: string;
  readOnly?: boolean;
  doctorId?: string;
  patientId?: string;
  defaultStatus?: string;
}) {
  const config: ResourceConfig = {
    storageKey: `appointments-${props.doctorId ?? "all"}-${props.patientId ?? "all"}`,
    title: props.title ?? "نوبت‌ها",
    description: "رزرو، تأیید، لغو و تغییر زمان نوبت.",
    viewPermission: HC.APPOINTMENTS_VIEW,
    managePermission: HC.APPOINTMENTS_MANAGE,
    queryKey: ["healthcare", "appointments", props.doctorId ?? "", props.patientId ?? ""],
    listFn: (tid, p) =>
      healthcareApi.appointments.list(tid, {
        page: p.page ?? 1,
        page_size: p.pageSize ?? 50,
        status: p.status,
        doctor_id: props.doctorId,
        patient_id: props.patientId,
      }),
    createFn: (tid, body) => healthcareApi.appointments.book(tid, body),
    defaultStatusFilter: props.defaultStatus,
    auditEntityType: "appointment",
    auditFn: (tid, et, eid) => healthcareApi.audit.list(tid, et, eid),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true, table: false },
      { name: "doctor_id", label: "پزشک", type: "doctor", required: true },
      { name: "patient_id", label: "بیمار", type: "patient", required: true },
      { name: "code", label: "کد", form: (m) => m === "create" },
      { name: "scheduled_start", label: "شروع", type: "datetime-local", required: true },
      { name: "scheduled_end", label: "پایان", type: "datetime-local", required: true },
      { name: "status", label: "وضعیت" },
      { name: "notes", label: "یادداشت", type: "textarea", table: false },
    ],
    mapCreateBody: (v) => ({
      clinic_id: v.clinic_id,
      doctor_id: v.doctor_id,
      patient_id: v.patient_id,
      code: v.code || `APT-${Date.now()}`,
      scheduled_start: new Date(v.scheduled_start).toISOString(),
      scheduled_end: new Date(v.scheduled_end).toISOString(),
      notes: v.notes || undefined,
    }),
    workflowActions: [
      {
        id: "confirm",
        label: "تأیید",
        visible: (r) => r.status === "draft" || r.status === "pending",
        confirmTitle: "تأیید نوبت",
        run: (r, tid) =>
          healthcareApi.appointments.confirm(tid, String(r.id), { version: Number(r.version) }),
      },
      {
        id: "cancel",
        label: "لغو",
        variant: "danger",
        visible: (r) => !["cancelled", "completed", "no_show"].includes(String(r.status)),
        confirmTitle: "لغو نوبت",
        run: (r, tid) =>
          healthcareApi.appointments.cancel(tid, String(r.id), { version: Number(r.version) }),
      },
      {
        id: "no-show",
        label: "عدم حضور",
        variant: "outline",
        visible: (r) => r.status === "confirmed",
        run: (r, tid) =>
          healthcareApi.appointments.noShow(tid, String(r.id), { version: Number(r.version) }),
      },
    ],
    createLabel: "رزرو نوبت",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function AppointmentsCalendarPage(props: {
  title?: string;
  doctorId?: string;
  mode?: "week" | "day";
}) {
  const { tenantId } = useTenantId();
  const { doctorName, patientName } = useHealthcareLookups();
  const [mode, setMode] = useState<"week" | "day">(props.mode ?? "week");

  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "calendar", props.doctorId, mode],
    queryFn: () =>
      healthcareApi.appointments.list(tenantId!, {
        doctor_id: props.doctorId,
        page_size: 200,
      }),
    enabled: !!tenantId,
  });

  const calendarItems: CalendarAppointment[] = useMemo(
    () =>
      (apptsQ.data?.items ?? []).map((a) => ({
        id: a.id,
        title: patientName(a.patient_id),
        subtitle: doctorName(a.doctor_id),
        start: a.scheduled_start,
        end: a.scheduled_end,
        status: a.status,
      })),
    [apptsQ.data, patientName, doctorName]
  );

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

  return (
    <div>
      <PageHeader title={props.title ?? "تقویم نوبت"} description={`${apptsQ.data?.total ?? 0} نوبت`} />
      <Tabs
        items={[
          { id: "week", label: "هفته" },
          { id: "day", label: "امروز" },
        ]}
        value={mode}
        onChange={(id) => setMode(id as "week" | "day")}
        className="mb-4"
      />
      <AppointmentCalendar appointments={calendarItems} mode={mode} />
    </div>
  );
}

export function WaitingListResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "waiting-list",
    title: props.title ?? "لیست انتظار / مراجعه حضوری",
    viewPermission: HC.APPOINTMENTS_VIEW,
    managePermission: HC.APPOINTMENTS_MANAGE,
    queryKey: ["healthcare", "waiting-list"],
    listFn: (tid) => healthcareApi.waitingList.list(tid),
    createFn: (tid, body) => healthcareApi.waitingList.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true, table: false },
      { name: "patient_id", label: "بیمار", type: "patient", required: true },
      { name: "doctor_id", label: "پزشک", type: "doctor" },
      { name: "code", label: "کد", required: true },
      { name: "preferred_date", label: "تاریخ ترجیحی", placeholder: "YYYY-MM-DD" },
      { name: "priority", label: "اولویت", type: "number" },
    ],
    createLabel: "افزودن به لیست انتظار",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function VisitSessionsResourcePage(props: {
  title?: string;
  readOnly?: boolean;
  doctorId?: string;
  defaultStatus?: string;
}) {
  const config: ResourceConfig = {
    storageKey: `visit-sessions-${props.doctorId ?? "all"}`,
    title: props.title ?? "جلسات ویزیت / صف",
    viewPermission: HC.VISIT_SESSIONS_MANAGE,
    queryKey: ["healthcare", "visit-sessions", props.doctorId ?? ""],
    listFn: (tid, p) =>
      healthcareApi.visitSessions.list(tid, {
        doctor_id: props.doctorId,
        status: p.status ?? props.defaultStatus,
      }),
    createFn: (tid, body) => healthcareApi.visitSessions.create(tid, body),
    defaultStatusFilter: props.defaultStatus,
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true, table: false },
      { name: "doctor_id", label: "پزشک", type: "doctor", required: true },
      { name: "patient_id", label: "بیمار", type: "patient", required: true },
      { name: "appointment_id", label: "نوبت ID" },
      { name: "code", label: "کد", required: true },
      { name: "status", label: "وضعیت" },
      { name: "queue_position", label: "صف", type: "number" },
    ],
    workflowActions: [
      {
        id: "start",
        label: "شروع ویزیت",
        visible: (r) => r.status === "queued",
        run: (r, tid) => healthcareApi.visitSessions.start(tid, String(r.id), { version: Number(r.version) }),
      },
      {
        id: "finish",
        label: "پایان",
        visible: (r) => r.status === "in_progress",
        run: (r, tid) => healthcareApi.visitSessions.finish(tid, String(r.id), { version: Number(r.version) }),
      },
      {
        id: "call-next",
        label: "فراخوان",
        visible: (r) => r.status === "queued",
        run: (r, tid) => healthcareApi.visitSessions.callNext(tid, String(r.id), { version: Number(r.version) }),
      },
      {
        id: "defer",
        label: "موکول",
        variant: "outline",
        visible: (r) => r.status === "queued" || r.status === "in_progress",
        run: (r, tid) => healthcareApi.visitSessions.defer(tid, String(r.id), { version: Number(r.version) }),
      },
    ],
    createLabel: "ایجاد جلسه ویزیت",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function SchedulesResourcePage(props: { title?: string; doctorId?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: `schedules-${props.doctorId ?? "all"}`,
    title: props.title ?? "برنامه هفتگی",
    viewPermission: HC.SCHEDULES_VIEW,
    managePermission: HC.SCHEDULES_MANAGE,
    queryKey: ["healthcare", "schedules", props.doctorId ?? ""],
    listFn: async (tid) => {
      const rows = await healthcareApi.schedules.list(tid);
      return props.doctorId ? rows.filter((s) => s.doctor_id === props.doctorId) : rows;
    },
    createFn: (tid, body) => healthcareApi.schedules.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true, table: false },
      { name: "doctor_id", label: "پزشک", type: "doctor", required: true },
      { name: "code", label: "کد", required: true },
      { name: "name", label: "نام", required: true },
      { name: "day_of_week", label: "روز", type: "select", options: [
        { value: "monday", label: "دوشنبه" },
        { value: "tuesday", label: "سه‌شنبه" },
        { value: "wednesday", label: "چهارشنبه" },
        { value: "thursday", label: "پنج‌شنبه" },
        { value: "friday", label: "جمعه" },
        { value: "saturday", label: "شنبه" },
        { value: "sunday", label: "یکشنبه" },
      ]},
      { name: "start_time", label: "شروع", placeholder: "09:00" },
      { name: "end_time", label: "پایان", placeholder: "17:00" },
      { name: "slot_duration_minutes", label: "مدت اسلات", type: "number" },
    ],
    createLabel: "برنامه جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function AvailabilityWindowsResourcePage(props: { title?: string; doctorId?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: `availability-${props.doctorId ?? "all"}`,
    title: props.title ?? "پنجره‌های availability",
    viewPermission: HC.SCHEDULES_VIEW,
    queryKey: ["healthcare", "availability", props.doctorId ?? ""],
    listFn: async (tid) => {
      const rows = await healthcareApi.availabilityWindows.list(tid);
      return props.doctorId ? rows.filter((w) => w.doctor_id === props.doctorId) : rows;
    },
    createFn: (tid, body) => healthcareApi.availabilityWindows.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true, table: false },
      { name: "doctor_id", label: "پزشک", type: "doctor", required: true },
      { name: "code", label: "کد", required: true },
      { name: "starts_at", label: "شروع", type: "datetime-local", required: true },
      { name: "ends_at", label: "پایان", type: "datetime-local", required: true },
    ],
    mapCreateBody: (v) => ({
      ...v,
      starts_at: new Date(v.starts_at).toISOString(),
      ends_at: new Date(v.ends_at).toISOString(),
      is_bookable: true,
    }),
    createLabel: "پنجره جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function PrescriptionOrdersResourcePage(props: {
  title?: string;
  status?: string;
  readOnly?: boolean;
  doctorId?: string;
}) {
  const { tenantId } = useTenantId();
  const pharmQ = useQuery({
    queryKey: ["healthcare", tenantId, "pharmacies-lookup"],
    queryFn: () => healthcareApi.pharmacies.list(tenantId!),
    enabled: !!tenantId,
  });

  const config: ResourceConfig = {
    storageKey: `prescriptions-${props.status ?? "all"}`,
    title: props.title ?? "نسخه‌ها",
    viewPermission: HC.PHARMACY_VIEW,
    managePermission: HC.PRESCRIPTION_ORDERS_FULFILL,
    queryKey: ["healthcare", "prescription-orders", props.status ?? ""],
    listFn: async (tid, p) => {
      const rows = await healthcareApi.prescriptionOrders.list(tid);
      let list = rows as Record<string, unknown>[];
      const st = p.status ?? props.status;
      if (st) list = list.filter((r) => r.status === st);
      if (props.doctorId) list = list.filter((r) => r.doctor_id === props.doctorId);
      return list;
    },
    createFn: (tid, body) => healthcareApi.prescriptionOrders.create(tid, body),
    defaultStatusFilter: props.status,
    pharmacies: pharmQ.data ?? [],
    fields: [
      { name: "pharmacy_id", label: "داروخانه", type: "pharmacy", required: true },
      { name: "patient_id", label: "بیمار", type: "patient", required: true },
      { name: "doctor_id", label: "پزشک", type: "doctor", required: true },
      { name: "code", label: "کد", required: true },
      { name: "status", label: "وضعیت" },
    ],
    workflowActions: [
      { id: "accept", label: "پذیرش", visible: (r) => r.status === "submitted", run: (r, tid) => healthcareApi.prescriptionOrders.accept(tid, String(r.id), { version: Number(r.version) }) },
      { id: "prepare", label: "آماده‌سازی", visible: (r) => r.status === "accepted", run: (r, tid) => healthcareApi.prescriptionOrders.prepare(tid, String(r.id), { version: Number(r.version) }) },
      { id: "ready", label: "آماده", visible: (r) => r.status === "preparing", run: (r, tid) => healthcareApi.prescriptionOrders.markReady(tid, String(r.id), { version: Number(r.version) }) },
      { id: "pickup", label: "تحویل", visible: (r) => r.status === "ready", run: (r, tid) => healthcareApi.prescriptionOrders.completePickup(tid, String(r.id), { version: Number(r.version) }) },
      { id: "cancel", label: "لغو", variant: "danger", visible: (r) => !["completed", "cancelled"].includes(String(r.status)), run: (r, tid) => healthcareApi.prescriptionOrders.cancel(tid, String(r.id), { version: Number(r.version) }) },
    ],
    createLabel: "نسخه جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function DeliveryIntegrationsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "delivery-integrations",
    title: props.title ?? "یکپارچگی تحویل",
    viewPermission: HC.DELIVERY_VIEW,
    managePermission: HC.DELIVERY_MANAGE,
    queryKey: ["healthcare", "delivery-integrations"],
    listFn: (tid) => healthcareApi.deliveryIntegrations.list(tid),
    createFn: (tid, body) => healthcareApi.deliveryIntegrations.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic" },
      { name: "pharmacy_id", label: "داروخانه", type: "pharmacy" },
      { name: "code", label: "کد", required: true },
      { name: "name", label: "نام", required: true },
      { name: "delivery_merchant_ref", label: "Merchant Ref", required: true },
      { name: "status", label: "وضعیت", type: "select", options: lifecycleStatusOptions },
    ],
    createLabel: "یکپارچگی جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function DeliveryJobIntentsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "delivery-jobs",
    title: props.title ?? "درخواست‌های ارسال",
    viewPermission: HC.DELIVERY_VIEW,
    queryKey: ["healthcare", "delivery-jobs"],
    listFn: (tid) => healthcareApi.deliveryJobIntents.list(tid),
    fields: [
      { name: "code", label: "کد" },
      { name: "status", label: "وضعیت" },
      { name: "delivery_job_ref", label: "ارجاع تحویل" },
      { name: "prescription_order_id", label: "نسخه ID" },
    ],
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}
