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

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

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

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

export function HospitalDepartments() {
  const { tenantId } = useTenantId();
  const deptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "hospital-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="departments API." />
      <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 HospitalDoctors() {
  const { doctors, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;
  return (
    <div>
      <PageHeader title="پزشکان بیمارستان" />
      <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 HospitalBeds() {
  const { tenantId } = useTenantId();
  const branchesQ = useQuery({
    queryKey: ["healthcare", tenantId, "hospital-beds"],
    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)." />
      <DataTable
        columns={[
          { key: "code", header: "کد تخت/واحد" },
          { key: "name", header: "نام بخش" },
          {
            key: "status",
            header: "وضعیت",
            render: (r) => <Badge tone={r.status === "active" ? "success" : "default"}>{String(r.status)}</Badge>,
          },
        ]}
        rows={(branchesQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="تختی ثبت نشده" />}
      />
    </div>
  );
}

export function HospitalClinics() {
  const { clinics, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;
  return (
    <div>
      <PageHeader title="کلینیک‌های زیرمجموعه" description="clinics API." />
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {clinics.map((c) => (
          <ClinicCard key={c.id} clinic={c} href={`/healthcare/site/clinic/${c.id}`} />
        ))}
      </div>
    </div>
  );
}

export function HospitalAppointments() {
  const { tenantId } = useTenantId();
  const apptsQ = useQuery({
    queryKey: ["healthcare", tenantId, "hospital-appts"],
    queryFn: () => healthcareApi.appointments.list(tenantId!, { page_size: 100 }),
    enabled: !!tenantId,
  });
  const { doctorName } = useHealthcareLookups();

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

  return (
    <div>
      <PageHeader title="نوبت‌های بیمارستان" description={`${apptsQ.data?.total ?? 0} نوبت`} />
      <div className="space-y-3">
        {(apptsQ.data?.items ?? []).map((a) => (
          <AppointmentCard key={a.id} appointment={a} doctorName={doctorName(a.doctor_id)} />
        ))}
      </div>
    </div>
  );
}

export function HospitalStaff() {
  const { tenantId } = useTenantId();
  const staffQ = useQuery({
    queryKey: ["healthcare", tenantId, "hospital-staff"],
    queryFn: () => healthcareApi.staffAssignments.list(tenantId!),
    enabled: !!tenantId,
  });
  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: "نقش" },
        ]}
        rows={(staffQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="پرسنلی ثبت نشده" />}
      />
    </div>
  );
}

export function HospitalResources() {
  const { tenantId } = useTenantId();
  const hoursQ = useQuery({
    queryKey: ["healthcare", tenantId, "operating-hours"],
    queryFn: () => healthcareApi.operatingHoursPolicies.list(tenantId!),
    enabled: !!tenantId,
  });
  const configQ = useQuery({
    queryKey: ["healthcare", tenantId, "configurations"],
    queryFn: () => healthcareApi.configurations.list(tenantId!),
    enabled: !!tenantId,
  });

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

  return (
    <div>
      <PageHeader title="منابع بیمارستان" description="سیاست ساعات کاری و پیکربندی." />
      <h2 className="mb-3 font-semibold text-secondary">ساعات کاری</h2>
      <DataTable
        columns={[
          { key: "name", header: "نام" },
          { key: "timezone", header: "منطقه زمانی" },
        ]}
        rows={(hoursQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="سیاستی ثبت نشده" />}
      />
      <h2 className="mb-3 mt-8 font-semibold text-secondary">پیکربندی</h2>
      <DataTable
        columns={[
          { key: "code", header: "کد" },
          { key: "timezone", header: "TZ" },
          { key: "language", header: "زبان" },
        ]}
        rows={(configQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="پیکربندی ثبت نشده" />}
      />
    </div>
  );
}

export function HospitalReports() {
  return <AnalyticsPage title="گزارش بیمارستان" />;
}
