"use client";

import Link from "next/link";
import { useEffect, Suspense } from "react";
import { useRouter, useParams, useSearchParams } from "next/navigation";
import { AuthGuard } from "@/components/AuthGuard";
import { LoadingState, PageHeader, Card, CardContent, Button } from "@/src/shared/ui";
import { HEALTHCARE_PORTALS, type HealthcarePortalId } from "@/src/modules/healthcare/constants/portals";
import { cn } from "@/lib/utils";
import { ChevronLeft } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useTenantId } from "@/hooks/useTenantId";
import { StatWidget } from "@/src/modules/healthcare/design-system";
import { AggregateStatsRow, HealthcarePageLoader } from "./shared";

export function HealthcareHub() {
  return (
    <AuthGuard>
      <HealthcareHubInner />
    </AuthGuard>
  );
}

function HealthcareHubInner() {
  const { tenantId } = useTenantId();
  const healthQ = useQuery({
    queryKey: ["healthcare", "health"],
    queryFn: () => healthcareApi.health(),
  });

  return (
    <div className="mx-auto max-w-6xl px-4 py-10 sm:px-6">
      <PageHeader
        title="تربت هلث"
        description="پورتال مورد نظر را انتخاب کنید."
        actions={
          healthQ.data ? (
            <span className="text-xs text-[var(--muted)]">v{healthQ.data.version}</span>
          ) : null
        }
      />
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        {HEALTHCARE_PORTALS.map((portal) => {
          const Icon = portal.icon;
          return (
            <Link key={portal.id} href={portal.basePath}>
              <Card className="h-full transition-all hover:border-[var(--health-accent)]/40 hover:shadow-[var(--shadow-md)]">
                <CardContent className="flex h-full flex-col gap-4 pt-6">
                  <div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[var(--health-accent-soft)] text-[var(--health-accent)]">
                    <Icon className="h-6 w-6" />
                  </div>
                  <div>
                    <p className="text-lg font-semibold text-secondary">{portal.label}</p>
                    <p className="mt-1 text-sm text-[var(--muted)]">{portal.description}</p>
                  </div>
                  <span className="mt-auto text-xs text-[var(--health-accent)]">ورود ←</span>
                </CardContent>
              </Card>
            </Link>
          );
        })}
      </div>
      <div className="mt-8 flex flex-wrap gap-3">
        <Link href="/healthcare/site">
          <Button variant="outline">سایت عمومی</Button>
        </Link>
        <Link href="/dashboard">
          <Button variant="ghost">workspace</Button>
        </Link>
      </div>
      {!tenantId ? (
        <p className="mt-6 text-sm text-[var(--muted)]">tenant فعال لازم است.</p>
      ) : null}
    </div>
  );
}

function AuthLoginRedirectInner() {
  const sp = useSearchParams();
  const router = useRouter();
  const returnUrl = sp.get("returnUrl") ?? "/healthcare/hub";

  useEffect(() => {
    router.replace(`/login?returnUrl=${encodeURIComponent(returnUrl)}`);
  }, [router, returnUrl]);

  return <LoadingState label="در حال انتقال به ورود…" />;
}

export function HealthcareAuthLogin() {
  return (
    <Suspense fallback={<LoadingState />}>
      <AuthLoginRedirectInner />
    </Suspense>
  );
}

const PORTAL_IDS: HealthcarePortalId[] = [
  "patient",
  "doctor",
  "reception",
  "clinic",
  "hospital",
  "pharmacy",
  "admin",
];

export function HealthcareMobilePortal() {
  const params = useParams();
  const portal = String(params.portal) as HealthcarePortalId;
  const meta = HEALTHCARE_PORTALS.find((p) => p.id === portal);
  const { tenantId } = useTenantId();

  const statsQ = useQuery({
    queryKey: ["healthcare", tenantId, "mobile-stats", portal],
    queryFn: async () => {
      const [clinics, doctors, patients, appts] = await Promise.all([
        healthcareApi.clinics.list(tenantId!),
        healthcareApi.doctors.list(tenantId!),
        healthcareApi.patients.list(tenantId!),
        healthcareApi.appointments.list(tenantId!, { page_size: 1 }),
      ]);
      return {
        clinics: clinics.length,
        doctors: doctors.length,
        patients: patients.length,
        appointments: appts.total,
      };
    },
    enabled: !!tenantId && !!meta,
  });

  if (!meta || !PORTAL_IDS.includes(portal)) {
    return (
      <div className="p-6 text-center">
        <p className="text-secondary">پورتال نامعتبر</p>
        <Link href="/healthcare/hub" className="mt-4 inline-block">
          <Button>بازگشت</Button>
        </Link>
      </div>
    );
  }

  const Icon = meta.icon;

  return (
    <AuthGuard>
      <div className="min-h-screen bg-[var(--canvas)] p-4 pb-24">
        <div className="mb-6 flex items-center gap-3">
          <Link href="/healthcare/hub">
            <Button variant="ghost" size="icon">
              <ChevronLeft className="h-5 w-5" />
            </Button>
          </Link>
          <div className="flex items-center gap-3">
            <div className="rounded-xl bg-[var(--health-accent-soft)] p-2 text-[var(--health-accent)]">
              <Icon className="h-5 w-5" />
            </div>
            <div>
              <p className="font-semibold text-secondary">{meta.label}</p>
              <p className="text-xs text-[var(--muted)]">{meta.description}</p>
            </div>
          </div>
        </div>

        {!tenantId || statsQ.isLoading ? (
          <HealthcarePageLoader />
        ) : (
          <AggregateStatsRow
            stats={[
              { label: "کلینیک", value: statsQ.data?.clinics ?? 0 },
              { label: "پزشک", value: statsQ.data?.doctors ?? 0 },
              { label: "بیمار", value: statsQ.data?.patients ?? 0 },
              { label: "نوبت", value: statsQ.data?.appointments ?? 0 },
            ]}
          />
        )}

        <Link
          href={meta.basePath}
          className={cn(
            "mt-8 flex w-full items-center justify-center rounded-2xl bg-[var(--health-accent)] px-4 py-4 text-white font-medium shadow-[var(--shadow-md)]"
          )}
        >
          ورود به داشبورد کامل
        </Link>
      </div>
    </AuthGuard>
  );
}
