import { useMemo, useSyncExternalStore } from 'react';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { Offline } from '@/components/ui/feedback/EmptyState/illustrations/Offline';
import { Button } from '@/components/ui/primitives/Button';
import { QrCodeCard } from '@/components/ui/domain/QrCodeCard';
import { readVisitedDealSnapshot, readWalletQrSnapshot } from '@/lib/offline/offlineContinuity';

interface Props {
  title: string;
  body: string;
}

type OfflineSnapshot = {
  deal: ReturnType<typeof readVisitedDealSnapshot>;
  qr: ReturnType<typeof readWalletQrSnapshot>;
};

const EMPTY_SNAPSHOT: OfflineSnapshot = { deal: null, qr: null };

// useSyncExternalStore hydration flag: server/hydration render = false, client = true.
// Storage reads happen only after hydration so the prerendered HTML never mismatches.
const useHydrated = () =>
  useSyncExternalStore(
    () => () => {},
    () => true,
    () => false,
  );

export function SystemPageOffline({ title, body }: Props) {
  const hydrated = useHydrated();
  const snapshot = useMemo<OfflineSnapshot>(
    () =>
      hydrated ? { deal: readVisitedDealSnapshot(), qr: readWalletQrSnapshot() } : EMPTY_SNAPSHOT,
    [hydrated],
  );

  return (
    <div className="mx-auto flex min-h-[60dvh] w-full max-w-3xl flex-col gap-6 px-4 py-16">
      <EmptyState illustration={<Offline />} title={title} titleLevel={1} description={body} />
      {snapshot.deal && (
        <section className="bg-surface-base border-border-default rounded-2xl border p-4 shadow-md">
          <p className="text-text-primary text-sm font-semibold">{snapshot.deal.title}</p>
          <p className="text-text-secondary mt-1 text-sm">{snapshot.deal.vendorName}</p>
          <div className="mt-4">
            <Button asChild variant="secondary" size="md">
              <a href={snapshot.deal.href}>{snapshot.deal.title}</a>
            </Button>
          </div>
        </section>
      )}
      {snapshot.qr && (
        <section className="bg-surface-base border-border-default rounded-2xl border p-4 shadow-md">
          <p className="text-text-primary text-sm font-semibold">{snapshot.qr.dealTitle}</p>
          <p className="text-text-secondary mt-1 text-sm">{snapshot.qr.businessName}</p>
          <div className="mt-4 flex justify-center">
            <QrCodeCard qrPngUrl={snapshot.qr.qrPngUrl} expiryIso={snapshot.qr.expiresAt} />
          </div>
        </section>
      )}
    </div>
  );
}
