"use client";

import Link from "next/link";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { apiGet } from "@/lib/api";
import type { SubscriptionFeatureKey } from "@/src/modules/subscriptions/subscription-entitlements";

type FeatureState = {
  key: SubscriptionFeatureKey;
  label: string;
  planIncluded: boolean;
  status: "Allowed" | "Locked" | "Billing hold" | "Paused";
  workspaceAdminMode: "Show" | "Show locked message" | "Hide from daily workflow";
  superAdminAction: string;
};

type EntitlementResponse = {
  workspace: { id: string; name: string };
  entitlements: {
    planName: string;
    subscriptionStatus: string;
    overallStatus: "Allowed" | "Needs review" | "Blocked";
    workspaceAdminMessage: string;
    superAdminMessage: string;
    featureStates: FeatureState[];
  };
};

const fallbackLabels: Record<SubscriptionFeatureKey, string> = {
  dispatch: "Dispatch",
  documents: "Documents",
  billing: "Billing",
  notifications: "Notifications",
  businessPhone: "Business phone",
  routePlanning: "Route planning",
  loadBoard: "Load board",
  reports: "Reports",
  cori: "CORI",
};

function blockedTitle(state?: FeatureState) {
  if (state?.status === "Billing hold") return "This feature is paused by billing.";
  if (state?.status === "Paused") return "This feature is paused.";
  return "This feature is not included in this plan.";
}

function blockedMessage(label: string, planName?: string) {
  return `${label} is not available on the current ${planName ?? "workspace"} plan. Ask your admin to review the subscription.`;
}

export function PlanFeatureGate({
  feature,
  children,
  title,
  description,
}: {
  feature: SubscriptionFeatureKey;
  children: ReactNode;
  title?: string;
  description?: string;
}) {
  const [snapshot, setSnapshot] = useState<EntitlementResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    setLoading(true);
    apiGet<EntitlementResponse>("/api/subscription/entitlements")
      .then((data) => {
        if (!active) return;
        setSnapshot(data);
        setError(null);
      })
      .catch((err) => {
        if (!active) return;
        setError(err instanceof Error ? err.message : "Unable to check this workspace plan");
      })
      .finally(() => {
        if (active) setLoading(false);
      });

    return () => {
      active = false;
    };
  }, []);

  const state = useMemo(() => snapshot?.entitlements.featureStates.find((item) => item.key === feature), [snapshot, feature]);

  if (loading) {
    return (
      <div className="rounded-2xl border bg-white p-6 text-sm text-gray-600 shadow-sm">
        Checking plan access…
      </div>
    );
  }

  if (error) {
    return (
      <div className="rounded-2xl border border-amber-200 bg-amber-50 p-6 shadow-sm">
        <div className="text-base font-semibold text-gray-900">Plan check unavailable</div>
        <p className="mt-2 text-sm leading-6 text-gray-700">This page could not confirm the workspace plan yet. Super Admin can review entitlement status in /admin.</p>
      </div>
    );
  }

  if (!state || state.status === "Allowed") return <>{children}</>;

  const label = title ?? state.label ?? fallbackLabels[feature];

  return (
    <div className="space-y-6">
      <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-500">Plan access</div>
            <h1 className="mt-2 text-2xl font-semibold text-slate-950">{blockedTitle(state)}</h1>
            <p className="mt-2 max-w-3xl text-sm leading-6 text-slate-600">{description ?? blockedMessage(label, snapshot?.entitlements.planName)}</p>
          </div>
          <span className="w-fit rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{state.status}</span>
        </div>
        <div className="mt-4 grid gap-3 md:grid-cols-3">
          <div className="rounded-xl border bg-slate-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Current plan</div>
            <div className="mt-1 text-lg font-semibold text-slate-950">{snapshot?.entitlements.planName ?? "Workspace plan"}</div>
          </div>
          <div className="rounded-xl border bg-slate-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Feature</div>
            <div className="mt-1 text-lg font-semibold text-slate-950">{label}</div>
          </div>
          <div className="rounded-xl border bg-slate-50 p-4">
            <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">What to do</div>
            <div className="mt-1 text-sm font-medium leading-6 text-slate-700">Ask your admin to review the subscription.</div>
          </div>
        </div>
        <div className="mt-4 flex flex-wrap gap-2">
          <Link href="/company" className="rounded-xl border bg-white px-4 py-2 text-sm font-medium text-slate-700">Open Company Settings</Link>
          <Link href="/dashboard" className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-medium text-white">Back to Dashboard</Link>
        </div>
      </section>
    </div>
  );
}
