'use client';

import Link from 'next/link';
import { useParams } from 'next/navigation';
import { signIn, useSession } from 'next-auth/react';
import { useCallback, useEffect, useState } from 'react';

import { partnerStackServices } from '@/lib/corporate-site-data';

type ProductInfo = {
  slug: string;
  name: string;
  description?: string;
  shortDescription?: string;
  category?: string;
};

type EntitlementRow = {
  entitlementKey: string;
  status: string;
};

type SubscribeResult = {
  subscription: { status: string; offerName: string };
  entitlements: EntitlementRow[];
  fulfillmentMode: string;
  keycloakSynced: boolean;
};

export default function MarketplaceEntitlementPage() {
  const params = useParams<{ slug: string }>();
  const slug = params?.slug || '';
  const { status } = useSession();
  const [product, setProduct] = useState<ProductInfo | null>(null);
  const [existing, setExisting] = useState<EntitlementRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const partnerMeta = partnerStackServices.find((s) => s.href?.includes(slug));

  const loadProduct = useCallback(async () => {
    const res = await fetch(`/api/marketplace/products/${slug}`, {
      credentials: 'include',
    });
    if (!res.ok) {
      throw new Error('Product not found');
    }
    const data = (await res.json()) as { product: ProductInfo };
    setProduct(data.product);
  }, [slug]);

  const loadEntitlements = useCallback(async () => {
    const res = await fetch('/api/marketplace/me', { credentials: 'include' });
    if (res.status === 401) return;
    if (!res.ok) return;
    const data = (await res.json()) as { entitlements?: EntitlementRow[] };
    setExisting(data.entitlements || []);
  }, []);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        await loadProduct();
        if (status === 'authenticated') {
          await loadEntitlements();
        }
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [loadProduct, loadEntitlements, status]);

  async function handleSubscribe() {
    setSubmitting(true);
    setError(null);
    setMessage(null);
    try {
      const res = await fetch('/api/marketplace/subscribe', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ productSlug: slug }),
      });
      const data = (await res.json()) as SubscribeResult & { error?: string };
      if (!res.ok) {
        throw new Error(data.error || 'Subscribe request failed');
      }
      setExisting(data.entitlements || []);
      if (data.fulfillmentMode === 'self_service') {
        setMessage('Subscription active. Entitlements are provisioned for your workspace.');
      } else if (data.fulfillmentMode === 'request_only') {
        setMessage('Request submitted. An operator will review and provision access.');
      } else {
        setMessage(
          'Subscription request recorded (contract/PO-first). An operator will activate entitlements and Keycloak flags.'
        );
      }
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Subscribe failed');
    } finally {
      setSubmitting(false);
    }
  }

  if (loading) {
    return (
      <main className="mx-auto max-w-3xl px-6 py-16 text-sovereign-ivory">
        <p className="text-sovereign-silver">Loading marketplace entitlement…</p>
      </main>
    );
  }

  if (error && !product) {
    return (
      <main className="mx-auto max-w-3xl px-6 py-16 text-sovereign-ivory">
        <h1 className="text-2xl font-semibold">Product not found</h1>
        <p className="mt-4 text-sovereign-silver">{error}</p>
        <Link href="/marketplace" className="mt-6 inline-block text-teal-400 hover:underline">
          Back to marketplace
        </Link>
      </main>
    );
  }

  const activeKeys = existing.map((e) => e.entitlementKey);
  const hasPending = existing.some((e) => e.status === 'PENDING' || e.status === 'REQUEST_ONLY');
  const hasActive = existing.some((e) => e.status === 'ACTIVE');

  return (
    <main className="mx-auto max-w-3xl px-6 py-16 text-sovereign-ivory">
      <Link href="/marketplace" className="text-sm text-teal-400 hover:underline">
        ← Marketplace
      </Link>
      <h1 className="mt-6 text-3xl font-semibold">{product?.name || partnerMeta?.name || slug}</h1>
      <p className="mt-2 text-sovereign-silver">
        {product?.shortDescription || product?.description || partnerMeta?.description}
      </p>

      {partnerMeta?.serviceUrl ? (
        <p className="mt-4 text-sm text-sovereign-silver">
          Service endpoint:{' '}
          <a
            href={partnerMeta.serviceUrl}
            className="text-teal-400 hover:underline"
            target="_blank"
            rel="noopener noreferrer"
          >
            {partnerMeta.serviceUrl.replace(/^https?:\/\//, '')}
          </a>
        </p>
      ) : null}

      <section className="mt-10 rounded-xl border border-white/10 bg-white/5 p-6">
        <h2 className="text-lg font-medium">Entitlement status</h2>
        {existing.length === 0 ? (
          <p className="mt-3 text-sovereign-silver">No entitlements for this workspace yet.</p>
        ) : (
          <ul className="mt-3 space-y-2 text-sm">
            {existing.map((row) => (
              <li key={row.entitlementKey} className="flex justify-between gap-4">
                <span className="font-mono text-teal-300">{row.entitlementKey}</span>
                <span>{row.status}</span>
              </li>
            ))}
          </ul>
        )}

        {status !== 'authenticated' ? (
          <button
            type="button"
            onClick={() => signIn(undefined, { callbackUrl: `/marketplace/entitlements/${slug}` })}
            className="mt-6 rounded-lg bg-teal-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-teal-500"
          >
            Sign in to subscribe
          </button>
        ) : hasActive ? (
          <p className="mt-6 text-emerald-400">Active entitlements: {activeKeys.join(', ')}</p>
        ) : hasPending ? (
          <p className="mt-6 text-amber-300">Pending operator activation.</p>
        ) : (
          <button
            type="button"
            disabled={submitting}
            onClick={handleSubscribe}
            className="mt-6 rounded-lg bg-teal-600 px-5 py-2.5 text-sm font-medium text-white hover:bg-teal-500 disabled:opacity-60"
          >
            {submitting ? 'Submitting…' : 'Request subscription'}
          </button>
        )}

        {message && <p className="mt-4 text-emerald-400">{message}</p>}
        {error && <p className="mt-4 text-red-400">{error}</p>}
      </section>

      <p className="mt-8 text-xs text-sovereign-silver">
        Contract/PO-first billing — automated Stripe checkout is on the roadmap. Operator Keycloak grants
        run via <code className="rounded bg-black/30 px-1">grant-marketplace-entitlements-keycloak.sh</code>.
      </p>
    </main>
  );
}
