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

export function ClinicDashboard() {
  const { tenantId } = useTenantId();
  const { clinics, doctors, patients, isLoading } = useHealthcareLookups();
  const deptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "clinic-depts"],
    queryFn: () => healthcareApi.departments.list(tenantId!),
    enabled: !!tenantId,
  });

  if (!tenantId || isLoading) return <HealthcarePageLoader />;

  return (
    <div>
      <PageHeader title="داشبورد کلینیک" description="نمای کلی مدیریت کلینیک." />
      <AggregateStatsRow
        stats={[
          { label: "کلینیک‌ها", value: clinics.length },
          { label: "پزشکان", value: doctors.length },
          { label: "بیماران", value: patients.length },
          { label: "بخش‌ها", value: deptsQ.data?.length ?? 0 },
        ]}
      />
    </div>
  );
}

export function ClinicDoctors() {
  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>
    </div>
  );
}

export function ClinicReceptionists() {
  const { tenantId } = useTenantId();
  const staffQ = useQuery({
    queryKey: ["healthcare", tenantId, "staff-assignments"],
    queryFn: () => healthcareApi.staffAssignments.list(tenantId!),
    enabled: !!tenantId,
    select: (rows) => rows.filter((s) => s.role_code.includes("reception") || s.role_code.includes("staff")),
  });
  const { doctorName } = useHealthcareLookups();

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

  return (
    <div>
      <PageHeader title="پذیرش" description="تخصیص پرسنل staff-assignments API." />
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          {
            key: "doctor_id",
            header: "عضو",
            render: (r) => doctorName(String(r.doctor_id)),
          },
          { key: "role_code", header: "نقش" },
          {
            key: "is_primary",
            header: "اصلی",
            render: (r) => (
              <Badge tone={r.is_primary ? "success" : "default"}>
                {r.is_primary ? "بله" : "خیر"}
              </Badge>
            ),
          },
        ]}
        rows={(staffQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="پرسنلی تخصیص نیافته" />}
      />
    </div>
  );
}

export function ClinicDepartments() {
  const { tenantId } = useTenantId();
  const deptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "departments"],
    queryFn: () => healthcareApi.departments.list(tenantId!),
    enabled: !!tenantId,
  });

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

  return (
    <div>
      <PageHeader title="بخش‌ها" description="بخش‌های درمانی کلینیک." />
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          { key: "specialty", header: "تخصص", render: (r) => String(r.specialty ?? "—") },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <Badge tone="default">{String(r.status)}</Badge>,
          },
        ]}
        rows={(deptsQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="بخشی ثبت نشده" />}
      />
    </div>
  );
}

export function ClinicRooms() {
  const { tenantId } = useTenantId();
  const branchesQ = useQuery({
    queryKey: ["healthcare", tenantId, "rooms-branches"],
    queryFn: () => healthcareApi.branches.list(tenantId!),
    enabled: !!tenantId,
  });

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

  return (
    <div>
      <PageHeader title="اتاق‌ها" description="شعب و فضاهای فیزیکی (branches API)." />
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          { key: "description", header: "توضیح", render: (r) => String(r.description ?? "—") },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <Badge tone="default">{String(r.status)}</Badge>,
          },
        ]}
        rows={(branchesQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="اتاق/شعبی ثبت نشده" />}
      />
    </div>
  );
}

export function ClinicSchedules() {
  const { tenantId } = useTenantId();
  const schedQ = useQuery({
    queryKey: ["healthcare", tenantId, "schedules"],
    queryFn: () => healthcareApi.schedules.list(tenantId!),
    enabled: !!tenantId,
  });
  const { doctorName } = useHealthcareLookups();

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

  return (
    <div>
      <PageHeader title="برنامه‌ها" description="برنامه هفتگی پزشکان." />
      <DataTable
        columns={[
          { key: "name", header: "نام" },
          {
            key: "doctor_id",
            header: "پزشک",
            render: (r) => doctorName(String(r.doctor_id)),
          },
          { key: "day_of_week", header: "روز" },
          { key: "start_time", header: "شروع" },
          { key: "end_time", header: "پایان" },
        ]}
        rows={(schedQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="برنامه‌ای ثبت نشده" />}
      />
    </div>
  );
}

export function ClinicResources() {
  const { tenantId } = useTenantId();
  const servicesQ = useQuery({
    queryKey: ["healthcare", tenantId, "clinic-services"],
    queryFn: () => healthcareApi.clinicServices.list(tenantId!),
    enabled: !!tenantId,
  });
  const policiesQ = useQuery({
    queryKey: ["healthcare", tenantId, "clinic-policies"],
    queryFn: () => healthcareApi.clinicPolicies.list(tenantId!),
    enabled: !!tenantId,
  });

  if (!tenantId || servicesQ.isLoading) return <HealthcarePageLoader />;

  return (
    <div>
      <PageHeader title="منابع" description="خدمات و سیاست‌های کلینیک." />
      <h2 className="mb-3 font-semibold text-secondary">خدمات</h2>
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "name", header: "نام" },
          { key: "duration_minutes", header: "مدت" },
        ]}
        rows={(servicesQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="خدمتی ثبت نشده" />}
      />
      <h2 className="mb-3 mt-8 font-semibold text-secondary">سیاست‌ها</h2>
      <DataTable
        columns={[
          { key: "name", header: "نام" },
          { key: "kind", header: "نوع" },
          { key: "booking_lead_time_hours", header: "Lead (h)" },
        ]}
        rows={(policiesQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="سیاستی ثبت نشده" />}
      />
    </div>
  );
}

export function ClinicPatients() {
  const { patients, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;
  return (
    <div>
      <PageHeader title="بیماران" description="بیماران کلینیک." />
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {patients.map((p) => (
          <PatientCard key={p.id} patient={p} />
        ))}
      </div>
    </div>
  );
}

export function ClinicReports() {
  return <AnalyticsPage title="گزارش کلینیک" />;
}

export function ClinicCrmIntegration() {
  return (
    <ExternalProvidersByKind
      kind="crm"
      title="یکپارچگی CRM"
      description="ارائه‌دهندگان CRM متصل."
    />
  );
}

export function ClinicAccountingIntegration() {
  return (
    <ExternalProvidersByKind
      kind="accounting"
      title="یکپارچگی حسابداری"
      description="ارائه‌دهندگان حسابداری."
      accountingLink
    />
  );
}
