"use client";

import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { PageHeader, DataTable, EmptyState, Badge, Button } 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 { ClinicCard, DoctorCard, PatientCard, StatWidget } from "@/src/modules/healthcare/design-system";
import {
  AggregateStatsRow,
  AnalyticsPage,
  HealthcarePageError,
  HealthcarePageLoader,
  MonitoringPage,
  ServiceMetaBadges,
  SettingsListPage,
} from "./shared";

export function AdminDashboard() {
  const { tenantId } = useTenantId();
  const { clinics, doctors, patients, isLoading } = useHealthcareLookups();
  const pharmQ = useQuery({
    queryKey: ["healthcare", tenantId, "admin-pharmacies"],
    queryFn: () => healthcareApi.pharmacies.list(tenantId!),
    enabled: !!tenantId,
  });

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

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

export function AdminOrganizations() {
  const { clinics, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;
  return (
    <div>
      <PageHeader
        title="سازمان‌ها"
        description="سازمان‌های درمانی — mapped از 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/admin/clinics`} />
        ))}
      </div>
      {clinics.length === 0 ? <EmptyState title="سازمانی ثبت نشده" /> : null}
    </div>
  );
}

export function AdminClinics() {
  const { tenantId } = useTenantId();
  const clinicsQ = useQuery({
    queryKey: ["healthcare", tenantId, "admin-clinics"],
    queryFn: () => healthcareApi.clinics.list(tenantId!),
    enabled: !!tenantId,
  });

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

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

export function AdminDoctors() {
  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} href={`/healthcare/site/doctor/${d.id}`} />
        ))}
      </div>
    </div>
  );
}

export function AdminPatients() {
  const { patients, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;
  return (
    <div>
      <PageHeader title="بیماران" />
      <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 AdminPharmacies() {
  const { tenantId } = useTenantId();
  const pharmQ = useQuery({
    queryKey: ["healthcare", tenantId, "pharmacies"],
    queryFn: () => healthcareApi.pharmacies.list(tenantId!),
    enabled: !!tenantId,
  });

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

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

export function AdminUsers() {
  const { doctors, patients, isLoading } = useHealthcareLookups();
  if (isLoading) return <HealthcarePageLoader />;

  const rows = [
    ...doctors.map((d) => ({
      id: d.id,
      name: d.display_name,
      role: "پزشک",
      code: d.code,
      status: d.status,
    })),
    ...patients.map((p) => ({
      id: p.id,
      name: p.display_name,
      role: "بیمار",
      code: p.code,
      status: p.status,
    })),
  ];

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

export function AdminPermissions() {
  const { tenantId } = useTenantId();
  const permQ = useQuery({
    queryKey: ["healthcare", tenantId, "permissions"],
    queryFn: () => healthcareApi.permissions.catalog(tenantId!),
    enabled: !!tenantId,
  });

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

  return (
    <div>
      <PageHeader
        title="دسترسی‌ها"
        description={`${permQ.data?.count ?? 0} permission — prefix: ${permQ.data?.prefix}`}
      />
      <DataTable
        columns={[{ key: "permission", header: "Permission" }]}
        rows={(permQ.data?.permissions ?? []).map((p) => ({ permission: p }))}
        empty={<EmptyState title="دسترسی‌ای تعریف نشده" />}
      />
    </div>
  );
}

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

export function AdminAnalytics() {
  return <AnalyticsPage title="آنالیتیکس" />;
}

export function AdminLogs() {
  const { tenantId } = useTenantId();
  const { clinics } = useHealthcareLookups();
  const clinicId = clinics[0]?.id;

  const logsQ = useQuery({
    queryKey: ["healthcare", tenantId, "admin-logs", clinicId],
    queryFn: () => healthcareApi.audit.list(tenantId!, "clinic", clinicId!),
    enabled: !!tenantId && !!clinicId,
  });

  if (!tenantId) return <HealthcarePageLoader />;
  if (!clinicId) {
    return (
      <div>
        <PageHeader title="لاگ سیستم" description="برای مشاهده لاگ، ابتدا کلینیک ایجاد کنید." />
        <EmptyState title="کلینیکی وجود ندارد" />
      </div>
    );
  }
  if (logsQ.isLoading) return <HealthcarePageLoader />;
  if (logsQ.error) return <HealthcarePageError error={logsQ.error} onRetry={() => logsQ.refetch()} />;

  return (
    <div>
      <PageHeader title="لاگ سیستم" description={`audit logs — entity: clinic/${clinicId}`} />
      <DataTable
        columns={[
          { key: "action", header: "عملیات" },
          { key: "entity_type", header: "نوع" },
          { key: "message", header: "پیام", render: (r) => String(r.message ?? "—") },
          {
            key: "created_at",
            header: "زمان",
            render: (r) => new Date(String(r.created_at)).toLocaleString("fa-IR"),
          },
        ]}
        rows={(logsQ.data ?? []) as unknown as Record<string, unknown>[]}
        empty={<EmptyState title="لاگی ثبت نشده" />}
      />
    </div>
  );
}

export function AdminMonitoring() {
  return <MonitoringPage />;
}

export function AdminSettings() {
  return <SettingsListPage title="تنظیمات سیستم" description="settings API." />;
}
