"use client";

import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { HC } from "@/src/modules/healthcare/constants/permissions";
import {
  HealthcareResourceWorkspace,
  type ResourceConfig,
} from "@/src/modules/healthcare/components/crud/HealthcareResourceWorkspace";

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

const profileOptions = [
  { value: "pending", label: "در انتظار" },
  { value: "active", label: "فعال" },
  { value: "inactive", label: "غیرفعال" },
];

export function ClinicsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "clinics",
    title: props.title ?? "کلینیک‌ها",
    description: "مدیریت کلینیک‌ها — CRUD کامل متصل به API.",
    viewPermission: HC.CLINICS_VIEW,
    managePermission: HC.CLINICS_MANAGE,
    queryKey: ["healthcare", "clinics"],
    listFn: (tid, p) => healthcareApi.clinics.list(tid, p.page ?? 1, p.pageSize ?? 50),
    createFn: (tid, body) => healthcareApi.clinics.create(tid, body as Parameters<typeof healthcareApi.clinics.create>[1]),
    updateFn: (tid, id, body) => healthcareApi.clinics.update(tid, id, body as Parameters<typeof healthcareApi.clinics.update>[2]),
    deleteFn: (tid, id) => healthcareApi.clinics.delete(tid, id),
    auditEntityType: "clinic",
    auditFn: (tid, et, eid) => healthcareApi.audit.list(tid, et, eid),
    fields: [
      { name: "code", label: "کد", required: true, form: (m) => m === "create" },
      { name: "name", label: "نام", required: true },
      { name: "description", label: "توضیح", type: "textarea" },
      { name: "status", label: "وضعیت", type: "select", options: lifecycleOptions },
      { name: "legal_name", label: "نام حقوقی" },
      { name: "timezone", label: "Timezone", placeholder: "Asia/Tehran" },
      { name: "language", label: "زبان", placeholder: "fa" },
      { name: "currency_code", label: "ارز", placeholder: "IRR" },
    ],
    createLabel: "کلینیک جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function BranchesResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "branches",
    title: props.title ?? "شعب / اتاق‌ها",
    description: "مدیریت شعب فیزیکی کلینیک.",
    viewPermission: HC.BRANCHES_VIEW,
    managePermission: HC.BRANCHES_MANAGE,
    queryKey: ["healthcare", "branches"],
    listFn: (tid, p) => healthcareApi.branches.list(tid, p.page ?? 1, p.pageSize ?? 50),
    createFn: (tid, body) => healthcareApi.branches.create(tid, body as Parameters<typeof healthcareApi.branches.create>[1]),
    updateFn: (tid, id, body) => healthcareApi.branches.update(tid, id, body as Parameters<typeof healthcareApi.branches.update>[2]),
    deleteFn: (tid, id) => healthcareApi.branches.delete(tid, id),
    auditEntityType: "branch",
    auditFn: (tid, et, eid) => healthcareApi.audit.list(tid, et, eid),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true, table: false },
      { name: "code", label: "کد", required: true, form: (m) => m === "create" },
      { name: "name", label: "نام", required: true },
      { name: "description", label: "توضیح", type: "textarea" },
      { name: "status", label: "وضعیت", type: "select", options: lifecycleOptions },
    ],
    createLabel: "شعبه جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function DepartmentsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "departments",
    title: props.title ?? "بخش‌ها",
    viewPermission: HC.DEPARTMENTS_VIEW,
    managePermission: HC.DEPARTMENTS_MANAGE,
    queryKey: ["healthcare", "departments"],
    listFn: (tid, p) => healthcareApi.departments.list(tid, p.page ?? 1, p.pageSize ?? 50),
    createFn: (tid, body) => healthcareApi.departments.create(tid, body as Parameters<typeof healthcareApi.departments.create>[1]),
    updateFn: (tid, id, body) => healthcareApi.departments.update(tid, id, body as Parameters<typeof healthcareApi.departments.update>[2]),
    deleteFn: (tid, id) => healthcareApi.departments.delete(tid, id),
    auditEntityType: "department",
    auditFn: (tid, et, eid) => healthcareApi.audit.list(tid, et, eid),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true, table: false },
      { name: "code", label: "کد", required: true, form: (m) => m === "create" },
      { name: "name", label: "نام", required: true },
      { name: "specialty", label: "تخصص" },
      { name: "description", label: "توضیح", type: "textarea" },
      { name: "status", label: "وضعیت", type: "select", options: lifecycleOptions },
    ],
    createLabel: "بخش جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function DoctorsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "doctors",
    title: props.title ?? "پزشکان",
    viewPermission: HC.DOCTORS_VIEW,
    managePermission: HC.DOCTORS_MANAGE,
    queryKey: ["healthcare", "doctors"],
    listFn: (tid, p) => healthcareApi.doctors.list(tid, p.page ?? 1, p.pageSize ?? 50),
    createFn: (tid, body) => healthcareApi.doctors.create(tid, body as Parameters<typeof healthcareApi.doctors.create>[1]),
    updateFn: (tid, id, body) => healthcareApi.doctors.update(tid, id, body as Parameters<typeof healthcareApi.doctors.update>[2]),
    deleteFn: (tid, id) => healthcareApi.doctors.delete(tid, id),
    auditEntityType: "doctor",
    auditFn: (tid, et, eid) => healthcareApi.audit.list(tid, et, eid),
    fields: [
      { name: "user_id", label: "User ID", required: true, form: (m) => m === "create" },
      { name: "code", label: "کد", required: true, form: (m) => m === "create" },
      { name: "display_name", label: "نام نمایشی", required: true },
      { name: "clinic_id", label: "کلینیک", type: "clinic" },
      { name: "specialty", label: "تخصص" },
      { name: "license_number", label: "شماره نظام" },
      { name: "status", label: "وضعیت", type: "select", options: profileOptions },
    ],
    createLabel: "پزشک جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function PatientsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "patients",
    title: props.title ?? "بیماران",
    viewPermission: HC.PATIENTS_VIEW,
    managePermission: HC.PATIENTS_MANAGE,
    queryKey: ["healthcare", "patients"],
    listFn: (tid, p) => healthcareApi.patients.list(tid, p.page ?? 1, p.pageSize ?? 50),
    createFn: (tid, body) => healthcareApi.patients.create(tid, body as Parameters<typeof healthcareApi.patients.create>[1]),
    updateFn: (tid, id, body) => healthcareApi.patients.update(tid, id, body as Parameters<typeof healthcareApi.patients.update>[2]),
    deleteFn: (tid, id) => healthcareApi.patients.delete(tid, id),
    auditEntityType: "patient",
    auditFn: (tid, et, eid) => healthcareApi.audit.list(tid, et, eid),
    fields: [
      { name: "user_id", label: "User ID", required: true, form: (m) => m === "create" },
      { name: "code", label: "کد", required: true, form: (m) => m === "create" },
      { name: "display_name", label: "نام", required: true },
      { name: "date_of_birth", label: "تاریخ تولد", placeholder: "YYYY-MM-DD" },
      { name: "gender", label: "جنسیت", type: "select", options: [{ value: "male", label: "مرد" }, { value: "female", label: "زن" }] },
      { name: "status", label: "وضعیت", type: "select", options: profileOptions },
    ],
    createLabel: "ثبت بیمار",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function PharmaciesResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "pharmacies",
    title: props.title ?? "داروخانه‌ها",
    viewPermission: HC.PHARMACY_VIEW,
    managePermission: HC.PHARMACY_MANAGE,
    queryKey: ["healthcare", "pharmacies"],
    listFn: (tid) => healthcareApi.pharmacies.list(tid),
    createFn: (tid, body) => healthcareApi.pharmacies.create(tid, body),
    fields: [
      { name: "code", label: "کد", required: true },
      { name: "name", label: "نام", required: true },
      { name: "status", label: "وضعیت", type: "select", options: lifecycleOptions },
    ],
    createLabel: "داروخانه جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function ExternalProvidersResourcePage(props: { title?: string; kind?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: `external-providers-${props.kind ?? "all"}`,
    title: props.title ?? "ارائه‌دهندگان خارجی",
    viewPermission: HC.EXTERNAL_PROVIDERS_VIEW,
    managePermission: HC.EXTERNAL_PROVIDERS_MANAGE,
    queryKey: ["healthcare", "external-providers", props.kind ?? "all"],
    listFn: async (tid) => {
      const rows = await healthcareApi.externalProviders.list(tid);
      return props.kind ? rows.filter((r) => r.provider_kind === props.kind) : rows;
    },
    createFn: (tid, body) => healthcareApi.externalProviders.create(tid, body as Parameters<typeof healthcareApi.externalProviders.create>[1]),
    updateFn: (tid, id, body) => healthcareApi.externalProviders.update(tid, id, body as Parameters<typeof healthcareApi.externalProviders.update>[2]),
    deleteFn: (tid, id) => healthcareApi.externalProviders.delete(tid, id),
    fields: [
      { name: "code", label: "کد", required: true, form: (m) => m === "create" },
      { name: "name", label: "نام", required: true },
      { name: "provider_kind", label: "نوع", type: "select", options: [
        { value: "accounting", label: "حسابداری" },
        { value: "crm", label: "CRM" },
        { value: "communication", label: "ارتباطات" },
        { value: "delivery", label: "تحویل" },
      ]},
      { name: "adapter_key", label: "آداپتر", required: true },
      { name: "status", label: "وضعیت", type: "select", options: [
        { value: "registered", label: "ثبت" },
        { value: "active", label: "فعال" },
        { value: "inactive", label: "غیرفعال" },
      ]},
      { name: "priority", label: "اولویت", type: "number" },
    ],
    createLabel: "ارائه‌دهنده جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function StaffAssignmentsResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "staff-assignments",
    title: props.title ?? "تخصیص پرسنل",
    viewPermission: HC.CLINIC_ADMIN_VIEW,
    managePermission: HC.CLINIC_ADMIN_MANAGE,
    queryKey: ["healthcare", "staff-assignments"],
    listFn: (tid) => healthcareApi.staffAssignments.list(tid),
    createFn: (tid, body) => healthcareApi.staffAssignments.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true },
      { name: "doctor_id", label: "پزشک/عضو", type: "doctor", required: true },
      { name: "code", label: "کد", required: true },
      { name: "role_code", label: "نقش", required: true, placeholder: "receptionist" },
    ],
    createLabel: "تخصیص جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function ClinicServicesResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "clinic-services",
    title: props.title ?? "خدمات کلینیک",
    viewPermission: HC.CLINIC_ADMIN_VIEW,
    queryKey: ["healthcare", "clinic-services"],
    listFn: (tid) => healthcareApi.clinicServices.list(tid),
    createFn: (tid, body) => healthcareApi.clinicServices.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true },
      { name: "code", label: "کد", required: true },
      { name: "name", label: "نام", required: true },
      { name: "duration_minutes", label: "مدت (دقیقه)", type: "number", required: true },
      { name: "status", label: "وضعیت", type: "select", options: lifecycleOptions },
    ],
    createLabel: "خدمت جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}

export function ClinicPoliciesResourcePage(props: { title?: string; readOnly?: boolean }) {
  const config: ResourceConfig = {
    storageKey: "clinic-policies",
    title: props.title ?? "سیاست‌های کلینیک",
    viewPermission: HC.CLINIC_ADMIN_VIEW,
    queryKey: ["healthcare", "clinic-policies"],
    listFn: (tid) => healthcareApi.clinicPolicies.list(tid),
    createFn: (tid, body) => healthcareApi.clinicPolicies.create(tid, body),
    fields: [
      { name: "clinic_id", label: "کلینیک", type: "clinic", required: true },
      { name: "code", label: "کد", required: true },
      { name: "name", label: "نام", required: true },
      { name: "kind", label: "نوع", required: true },
      { name: "booking_lead_time_hours", label: "Lead time (h)", type: "number" },
      { name: "cancellation_window_hours", label: "Cancellation (h)", type: "number" },
    ],
    createLabel: "سیاست جدید",
  };
  return <HealthcareResourceWorkspace config={config} readOnly={props.readOnly} />;
}
