'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { ArrowRight, GitBranch, Loader2, ExternalLink, AlertCircle } from 'lucide-react';
import { listBranches, type Branch } from '@client/api/branches';
import { useAuth } from '@client/contexts/AuthContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { qrToDataUrl, type QrStyle } from '@client/utils/qr';

interface BranchExtra extends Branch {
  slug?: string;
  storefront_enabled?: boolean;
  qr_style_json?: Record<string, unknown>;
}

export default function StorefrontHubPage() {
  const { t } = useLanguage();
  usePageHeader(
    t('storefront.hub.title', 'QR Storefront'),
    t('storefront.hub.subtitle', 'Per-table QR codes and customer-facing storefront'),
  );
  const { userRecord, sessionBranchId } = useAuth();
  const router = useRouter();
  const searchParams = useSearchParams();
  const restaurantSlug = (userRecord?.restaurants?.slug as string | undefined) ?? '';
  // Use the *literal* JWT session branch (`sessionBranchId`), NOT the legacy
  // `userRecord.branch_id` coalesce — otherwise an owner in "All branches"
  // mode would silently get auto-redirected to their pinned default branch's
  // storefront instead of the hub picker.
  const activeBranchId = sessionBranchId;
  // Auto-redirect to the active branch's editor; `?all=1` is the escape hatch
  // used by the editor's "Back to QR Storefront" link to surface the hub.
  const escapeHubRedirect = searchParams?.get('all') === '1';
  const shouldAutoRedirect = !!activeBranchId && !escapeHubRedirect;
  const [branches, setBranches] = useState<BranchExtra[]>([]);
  const [loading, setLoading] = useState(true);
  const [thumbs, setThumbs] = useState<Record<string, string>>({});

  useEffect(() => {
    if (shouldAutoRedirect && activeBranchId) {
      router.replace(`/storefront/${activeBranchId}`);
      return;
    }
    (async () => {
      try {
        const res = await listBranches({ limit: '100' });
        setBranches(res.branches as BranchExtra[]);
      } finally {
        setLoading(false);
      }
    })();
  }, [activeBranchId, shouldAutoRedirect, router]);

  // Build live QR thumbnails for branches that have a slug, using the saved style.
  useEffect(() => {
    if (typeof window === 'undefined' || !restaurantSlug) return;
    let cancelled = false;
    (async () => {
      const next: Record<string, string> = {};
      await Promise.all(
        branches.map(async (b) => {
          if (!b.slug) return;
          const url = `${window.location.origin}/r/${restaurantSlug}/${b.slug}`;
          const style: QrStyle = {
            fg: (b.qr_style_json?.fg as string) ?? '#111827',
            bg: (b.qr_style_json?.bg as string) ?? '#ffffff',
            margin: (b.qr_style_json?.margin as number) ?? 2,
            ecc: ((b.qr_style_json?.ecc as 'L' | 'M' | 'Q' | 'H') ?? 'M'),
            logo_data_url: (b.qr_style_json?.logo_data_url as string | null) ?? null,
          };
          try {
            next[b.id] = await qrToDataUrl(url, style, 96);
          } catch {
            /* skip thumbnail on failure */
          }
        })
      );
      if (!cancelled) setThumbs(next);
    })();
    return () => { cancelled = true; };
  }, [branches, restaurantSlug]);

  if (loading) {
    return (
      <div className="p-8 flex items-center text-slate-500">
        <Loader2 className="animate-spin mr-2" /> {t('common.loading', 'Loading…')}
      </div>
    );
  }

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <p className="text-sm text-slate-600 mb-6">
        {t('storefront.hub.intro', 'Choose a branch to design its QR, edit storefront settings, and download print-ready cards.')}
      </p>

      {branches.length === 0 ? (
        <div className="bg-white border border-slate-200 rounded-xl p-8 text-center text-slate-500 text-sm">
          {t('storefront.hub.empty', 'No branches yet.')}{' '}
          <Link href="/branch-management" className="text-orange-600 font-semibold">
            {t('storefront.hub.createBranch', 'Create one in Branches')}
          </Link>{' '}
          {t('storefront.hub.first', 'first.')}
        </div>
      ) : (
        <div className="space-y-2">
          {branches.map((b) => {
            const enabled = !!b.storefront_enabled;
            const publicUrl = restaurantSlug && b.slug ? `/r/${restaurantSlug}/${b.slug}` : null;
            const thumb = thumbs[b.id];
            return (
              <div key={b.id} className="bg-white border border-slate-200 rounded-xl p-4 flex items-center gap-4">
                {/* QR thumbnail or "needs setup" placeholder */}
                <div
                  className="w-20 h-20 rounded-lg border border-slate-200 flex items-center justify-center shrink-0 overflow-hidden"
                  style={{ background: (b.qr_style_json?.bg as string) ?? '#ffffff' }}
                >
                  {b.slug && thumb ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={thumb} alt={t('storefront.hub.qrAlt', 'QR code')} className="w-full h-full object-contain p-1" />
                  ) : !restaurantSlug ? (
                    <div className="flex flex-col items-center text-amber-600 text-[10px] font-semibold text-center px-1">
                      <AlertCircle size={16} />
                      <span className="mt-0.5">{t('storefront.hub.restaurantSlugMissing', 'Set restaurant slug')}</span>
                    </div>
                  ) : b.slug ? (
                    <Loader2 size={18} className="animate-spin text-slate-300" />
                  ) : (
                    <div className="flex flex-col items-center text-amber-600 text-[10px] font-semibold text-center px-1">
                      <AlertCircle size={16} />
                      <span className="mt-0.5">{t('storefront.hub.needsSetup', 'Needs setup')}</span>
                    </div>
                  )}
                </div>

                <div className="flex-1 min-w-0">
                  <p className="font-semibold text-slate-900 flex items-center gap-2">
                    <GitBranch size={14} className="text-slate-400" /> {b.name}
                  </p>
                  <p className="text-xs text-slate-500 truncate">{b.address || '—'}</p>
                  <p className="text-[11px] mt-1">
                    <span className={`px-2 py-0.5 rounded-full font-semibold ${enabled ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600'}`}>
                      {enabled ? t('storefront.hub.enabled', 'Enabled') : t('storefront.hub.disabled', 'Disabled')}
                    </span>
                    {b.slug
                      ? <span className="text-slate-400 ml-2">/{b.slug}</span>
                      : <span className="text-amber-600 ml-2">{t('storefront.hub.noSlug', 'no slug')}</span>}
                  </p>
                </div>

                {publicUrl && (
                  <a
                    href={publicUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-1 text-xs font-semibold text-slate-600 hover:text-slate-800 px-2 py-1.5"
                  >
                    {t('storefront.hub.preview', 'Preview')} <ExternalLink size={12} />
                  </a>
                )}
                <Link
                  href={`/storefront/${b.id}`}
                  className="inline-flex items-center gap-1.5 bg-orange-500 hover:bg-orange-600 text-white rounded-lg px-3 py-2 text-xs font-semibold"
                >
                  {b.slug
                    ? t('storefront.hub.openEditor', 'Edit QR & storefront')
                    : t('storefront.hub.setUp', 'Set up')}
                  <ArrowRight size={12} />
                </Link>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
