"use client";

import Link from "next/link";
import { useRouter, useSearchParams, useParams } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { useEffect, Suspense } from "react";
import {
  PageHeader,
  Button,
  Card,
  CardContent,
  Badge,
  LoadingState,
  ErrorState,
  EmptyState,
} from "@/src/shared/ui";
import { healthcareApi } from "@/src/modules/healthcare/services/healthcare-api";
import { useTenantId } from "@/hooks/useTenantId";
import { getStoredToken } from "@/lib/auth";
import {
  ClinicCard,
  DoctorCard,
  SearchResultRow,
  StatWidget,
  TimelineItem,
} from "@/src/modules/healthcare/design-system";
import { HealthcarePageError, HealthcarePageLoader, useHealthcareServiceMeta } from "./shared";

function AuthGateCTA({ returnPath }: { returnPath: string }) {
  return (
    <div className="mx-auto max-w-lg py-20 text-center">
      <h1 className="text-2xl font-bold text-secondary">ورود لازم است</h1>
      <p className="mt-3 text-[var(--muted)]">برای دسترسی به این بخش باید وارد حساب workspace شوید.</p>
      <Link href={`/login?returnUrl=${encodeURIComponent(returnPath)}`} className="mt-6 inline-block">
        <Button size="lg">ورود / ثبت‌نام</Button>
      </Link>
    </div>
  );
}

function usePublicTenantQueries(enabled: boolean) {
  const { tenantId } = useTenantId();
  const active = enabled && !!tenantId;

  const doctorsQ = useQuery({
    queryKey: ["healthcare", tenantId, "public-doctors"],
    queryFn: () => healthcareApi.doctors.list(tenantId!),
    enabled: active,
  });
  const clinicsQ = useQuery({
    queryKey: ["healthcare", tenantId, "public-clinics"],
    queryFn: () => healthcareApi.clinics.list(tenantId!),
    enabled: active,
  });
  const capsQ = useQuery({
    queryKey: ["healthcare", "capabilities"],
    queryFn: () => healthcareApi.capabilities(),
  });

  return { tenantId, doctorsQ, clinicsQ, capsQ, active };
}

export function PublicHome() {
  const { capsQ } = useHealthcareServiceMeta();
  const features = Object.entries(capsQ.data?.features ?? {}).filter(([, v]) => v).slice(0, 6);

  return (
    <div>
      <section className="relative overflow-hidden border-b border-[var(--border)] bg-gradient-to-b from-[var(--health-accent-soft)] to-[var(--canvas)] px-4 py-20 sm:px-6">
        <div className="mx-auto max-w-4xl text-center">
          <Badge tone="default" className="mb-4">
            SaaS سلامت — تربت هلث
          </Badge>
          <h1 className="text-4xl font-bold tracking-tight text-secondary sm:text-5xl">
            نوبت‌دهی، پرونده و مدیریت کلینیک
          </h1>
          <p className="mx-auto mt-4 max-w-2xl text-lg text-[var(--muted)]">
            پلتفرم یکپارچه برای بیمار، پزشک، پذیرش و مدیر — متصل به API واقعی healthcare.
          </p>
          <div className="mt-8 flex flex-wrap items-center justify-center gap-3">
            <Link href="/login?returnUrl=/healthcare/hub">
              <Button size="lg">ورود به پورتال</Button>
            </Link>
            <Link href="/healthcare/site/book">
              <Button size="lg" variant="outline">
                رزرو نوبت
              </Button>
            </Link>
          </div>
        </div>
      </section>
      {features.length > 0 ? (
        <section className="mx-auto max-w-6xl px-4 py-16 sm:px-6">
          <h2 className="mb-6 text-center text-xl font-semibold text-secondary">قابلیت‌های فعال</h2>
          <div className="flex flex-wrap justify-center gap-2">
            {features.map(([k]) => (
              <Badge key={k} tone="success">
                {k}
              </Badge>
            ))}
          </div>
        </section>
      ) : null}
    </div>
  );
}

export function PublicFeatures() {
  const { capsQ } = useHealthcareServiceMeta();
  if (capsQ.isLoading) return <HealthcarePageLoader />;

  return (
    <div className="mx-auto max-w-4xl px-4 py-12 sm:px-6">
      <PageHeader title="امکانات" description={`فاز ${capsQ.data?.phase} — ${capsQ.data?.commercial_product}`} />
      <ul className="mt-8 grid gap-3 sm:grid-cols-2">
        {Object.entries(capsQ.data?.features ?? {}).map(([key, on]) => (
          <li
            key={key}
            className="flex items-center justify-between rounded-2xl border border-[var(--border)] bg-[var(--surface)] px-4 py-3"
          >
            <span className="text-secondary">{key}</span>
            <Badge tone={on ? "success" : "default"}>{on ? "فعال" : "آینده"}</Badge>
          </li>
        ))}
      </ul>
    </div>
  );
}

export function PublicPricing() {
  const { capsQ, metricsQ } = useHealthcareServiceMeta();
  if (capsQ.isLoading) return <HealthcarePageLoader />;

  return (
    <div className="mx-auto max-w-4xl px-4 py-12 sm:px-6">
      <PageHeader title="قیمت‌گذاری" description="بر اساس قابلیت‌های فعال سرویس." />
      <Card className="mt-8">
        <CardContent className="space-y-4 pt-6">
          <p className="text-secondary font-semibold">{capsQ.data?.commercial_product}</p>
          <p className="text-sm text-[var(--muted)]">فاز: {capsQ.data?.phase}</p>
          <p className="text-sm text-[var(--muted)]">
            حالت یکپارچگی: {capsQ.data?.independence.integration_mode}
          </p>
          {metricsQ.data?.note ? (
            <p className="text-xs text-[var(--muted)]">{metricsQ.data.note}</p>
          ) : null}
          <Link href="/login?returnUrl=/healthcare/hub">
            <Button>شروع با workspace</Button>
          </Link>
        </CardContent>
      </Card>
    </div>
  );
}

export function PublicFaq() {
  const { capsQ } = useHealthcareServiceMeta();
  const items = [
    {
      q: "آیا standalone کار می‌کند؟",
      a: capsQ.data?.independence.standalone ? "بله — standalone فعال است." : "خیر — نیاز به superapp.",
    },
    {
      q: "یکپارچگی‌ها",
      a: (capsQ.data?.independence.integrations ?? []).join("، ") || "—",
    },
    {
      q: "نسخه سرویس",
      a: capsQ.data?.version ?? "—",
    },
  ];

  return (
    <div className="mx-auto max-w-3xl px-4 py-12 sm:px-6">
      <PageHeader title="سوالات متداول" />
      <div className="mt-8 space-y-4">
        {items.map((item) => (
          <Card key={item.q}>
            <CardContent className="pt-5">
              <p className="font-semibold text-secondary">{item.q}</p>
              <p className="mt-2 text-sm text-[var(--muted)]">{item.a}</p>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
}

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

  if (healthQ.isLoading) return <HealthcarePageLoader />;

  return (
    <div className="mx-auto max-w-3xl px-4 py-12 sm:px-6">
      <PageHeader title="درباره تربت هلث" description="سرویس SaaS سلامت تربت‌یار." />
      <Card className="mt-8">
        <CardContent className="space-y-3 pt-6 text-sm text-[var(--muted)]">
          <p>
            سرویس: <strong className="text-secondary">{healthQ.data?.service}</strong>
          </p>
          <p>
            نسخه: <strong className="text-secondary">{healthQ.data?.version}</strong>
          </p>
          <p>وضعیت: {healthQ.data?.status}</p>
        </CardContent>
      </Card>
    </div>
  );
}

export function PublicContact() {
  const { capsQ } = useHealthcareServiceMeta();
  return (
    <div className="mx-auto max-w-3xl px-4 py-12 sm:px-6">
      <PageHeader title="تماس" description="برای دسترسی به workspace با پشتیبانی تربت‌یار تماس بگیرید." />
      <Card className="mt-8">
        <CardContent className="space-y-3 pt-6">
          <p className="text-sm text-[var(--muted)]">محصول: {capsQ.data?.commercial_product}</p>
          <Link href="/login?returnUrl=/healthcare/site/contact">
            <Button>ورود workspace</Button>
          </Link>
        </CardContent>
      </Card>
    </div>
  );
}

function AuthenticatedSearchPage({
  title,
  type,
}: {
  title: string;
  type: "doctor" | "clinic" | "hospital";
}) {
  const pathname = `/healthcare/site/find-${type === "hospital" ? "hospital" : type}`;
  const authed = !!getStoredToken();
  const { doctorsQ, clinicsQ, active } = usePublicTenantQueries(authed);

  if (!authed) return <AuthGateCTA returnPath={pathname} />;
  if (!active || doctorsQ.isLoading || clinicsQ.isLoading) return <HealthcarePageLoader />;
  if (doctorsQ.error) return <HealthcarePageError error={doctorsQ.error} onRetry={() => doctorsQ.refetch()} />;

  return (
    <div className="mx-auto max-w-4xl px-4 py-12 sm:px-6">
      <PageHeader title={title} description="نتایج از API واقعی — پس از ورود." />
      {type === "doctor" ? (
        <div className="mt-8 grid gap-4 sm:grid-cols-2">
          {(doctorsQ.data ?? []).map((d) => (
            <DoctorCard key={d.id} doctor={d} href={`/healthcare/site/doctor/${d.id}`} />
          ))}
        </div>
      ) : (
        <div className="mt-8 grid gap-4 sm:grid-cols-2">
          {(clinicsQ.data ?? []).map((c) => (
            <ClinicCard
              key={c.id}
              clinic={c}
              href={`/healthcare/site/${type === "hospital" ? "hospital" : "clinic"}/${c.id}`}
            />
          ))}
        </div>
      )}
      {(type === "doctor" ? doctorsQ.data : clinicsQ.data)?.length === 0 ? (
        <EmptyState title="نتیجه‌ای یافت نشد" />
      ) : null}
    </div>
  );
}

export function PublicFindDoctor() {
  return <AuthenticatedSearchPage title="یافتن پزشک" type="doctor" />;
}

export function PublicFindClinic() {
  return <AuthenticatedSearchPage title="یافتن کلینیک" type="clinic" />;
}

export function PublicFindHospital() {
  return <AuthenticatedSearchPage title="یافتن بیمارستان" type="hospital" />;
}

function PublicSearchInner() {
  const sp = useSearchParams();
  const q = (sp.get("q") ?? "").trim().toLowerCase();
  const authed = !!getStoredToken();
  const { doctorsQ, clinicsQ, active } = usePublicTenantQueries(authed);

  if (!authed) return <AuthGateCTA returnPath={`/healthcare/site/search?q=${encodeURIComponent(q)}`} />;
  if (!active || doctorsQ.isLoading || clinicsQ.isLoading) return <HealthcarePageLoader />;

  const doctors = (doctorsQ.data ?? []).filter(
    (d) => !q || d.display_name.toLowerCase().includes(q) || (d.specialty ?? "").toLowerCase().includes(q)
  );
  const clinics = (clinicsQ.data ?? []).filter(
    (c) => !q || c.name.toLowerCase().includes(q) || c.code.toLowerCase().includes(q)
  );

  return (
    <div className="mx-auto max-w-4xl px-4 py-12 sm:px-6">
      <PageHeader title="جستجو" description={q ? `نتایج برای «${q}»` : "همه نتایج"} />
      <div className="mt-8 space-y-3">
        {doctors.map((d) => (
          <SearchResultRow
            key={d.id}
            title={d.display_name}
            meta={d.specialty ?? "پزشک"}
            href={`/healthcare/site/doctor/${d.id}`}
          />
        ))}
        {clinics.map((c) => (
          <SearchResultRow
            key={c.id}
            title={c.name}
            meta={c.code}
            href={`/healthcare/site/clinic/${c.id}`}
          />
        ))}
      </div>
      {doctors.length === 0 && clinics.length === 0 ? <EmptyState title="نتیجه‌ای یافت نشد" /> : null}
    </div>
  );
}

export function PublicSearch() {
  return (
    <Suspense fallback={<LoadingState />}>
      <PublicSearchInner />
    </Suspense>
  );
}

export function PublicDoctorProfile() {
  const params = useParams();
  const id = String(params.id);
  const { tenantId } = useTenantId();
  const doctorQ = useQuery({
    queryKey: ["healthcare", tenantId, "doctor", id],
    queryFn: () => healthcareApi.doctors.get(tenantId!, id),
    enabled: !!tenantId && !!id,
  });

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

  return (
    <div className="mx-auto max-w-3xl px-4 py-12 sm:px-6">
      <DoctorCard doctor={doctorQ.data!} />
      <Link href="/healthcare/site/book" className="mt-6 inline-block">
        <Button>رزرو نوبت</Button>
      </Link>
    </div>
  );
}

export function PublicClinicProfile() {
  const params = useParams();
  const id = String(params.id);
  const { tenantId } = useTenantId();
  const clinicQ = useQuery({
    queryKey: ["healthcare", tenantId, "clinic", id],
    queryFn: () => healthcareApi.clinics.get(tenantId!, id),
    enabled: !!tenantId && !!id,
  });

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

  return (
    <div className="mx-auto max-w-3xl px-4 py-12 sm:px-6">
      <ClinicCard clinic={clinicQ.data!} />
    </div>
  );
}

export function PublicHospitalProfile() {
  return <PublicClinicProfile />;
}

export function PublicBook() {
  const authed = !!getStoredToken();
  const { tenantId } = useTenantId();
  const typesQ = useQuery({
    queryKey: ["healthcare", tenantId, "book-types"],
    queryFn: () => healthcareApi.appointmentTypes.list(tenantId!),
    enabled: authed && !!tenantId,
  });
  const doctorsQ = useQuery({
    queryKey: ["healthcare", tenantId, "book-doctors"],
    queryFn: () => healthcareApi.doctors.list(tenantId!),
    enabled: authed && !!tenantId,
  });

  if (!authed) return <AuthGateCTA returnPath="/healthcare/site/book" />;
  if (!tenantId || typesQ.isLoading || doctorsQ.isLoading) return <HealthcarePageLoader />;

  return (
    <div className="mx-auto max-w-4xl px-4 py-12 sm:px-6">
      <PageHeader title="رزرو نوبت" description="انتخاب پزشک و نوع نوبت — booking از patient-portal." />
      <div className="mt-8 grid gap-4 sm:grid-cols-2">
        <StatWidget label="پزشکان" value={doctorsQ.data?.length ?? 0} />
        <StatWidget label="انواع نوبت" value={typesQ.data?.length ?? 0} />
      </div>
      <div className="mt-8 grid gap-4 sm:grid-cols-2">
        {(doctorsQ.data ?? []).map((d) => (
          <DoctorCard key={d.id} doctor={d} />
        ))}
      </div>
      <Link href="/healthcare/patient/appointments/book" className="mt-8 inline-block">
        <Button>ادامه در پورتال بیمار</Button>
      </Link>
    </div>
  );
}

export function PublicBookSuccess() {
  return (
    <div className="mx-auto max-w-lg px-4 py-20 text-center sm:px-6">
      <h1 className="text-2xl font-bold text-secondary">درخواست ثبت شد</h1>
      <p className="mt-3 text-[var(--muted)]">وضعیت نوبت را از پورتال بیمار یا tracking پیگیری کنید.</p>
      <Link href="/healthcare/patient/appointments/upcoming" className="mt-6 inline-block">
        <Button>نوبت‌های من</Button>
      </Link>
    </div>
  );
}

export function PublicTracking() {
  const params = useParams();
  const id = String(params.id);
  const { tenantId } = useTenantId();
  const apptQ = useQuery({
    queryKey: ["healthcare", tenantId, "tracking", id],
    queryFn: () => healthcareApi.appointments.get(tenantId!, id),
    enabled: !!tenantId && !!id,
  });

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

  const a = apptQ.data!;
  const steps = [
    { title: "ثبت", time: a.created_at, active: true },
    { title: "زمان‌بندی", time: a.scheduled_start, active: a.status !== "draft" },
    { title: "وضعیت", time: a.updated_at, active: ["confirmed", "completed"].includes(a.status) },
  ];

  return (
    <div className="mx-auto max-w-lg px-4 py-12 sm:px-6">
      <PageHeader title={`پیگیری ${a.code}`} description={`وضعیت: ${a.status}`} />
      <div className="mt-8">
        {steps.map((s) => (
          <TimelineItem
            key={s.title}
            title={s.title}
            time={new Date(s.time).toLocaleString("fa-IR")}
            active={s.active}
          />
        ))}
      </div>
    </div>
  );
}
