'use client';

import { useEffect, useState, use } from 'react';
import { Loader2, FileDown, ArrowLeft } from 'lucide-react';
import Link from 'next/link';
import { useAuth } from '@client/contexts/AuthContext';
import { getBranch, type Branch } from '@client/api/branches';

export default function PrintQrPage({ params }: { params: Promise<{ id: string }> }) {
  const { id: branchId } = use(params);
  const { userRecord } = useAuth();
  const restaurantName = (userRecord?.restaurants?.name as string | undefined) ?? '';

  const [branch, setBranch] = useState<Branch | null>(null);
  const [loading, setLoading] = useState(true);
  const [downloading, setDownloading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    (async () => {
      try {
        const b = await getBranch(branchId);
        setBranch(b.branch);
      } catch (e) {
        setError((e as Error).message ?? 'Failed to load branch');
      } finally {
        setLoading(false);
      }
    })();
  }, [branchId]);

  const downloadPdf = async () => {
    setDownloading(true);
    setError(null);
    try {
      const res = await fetch(`/api/branches/${branchId}/qr-pdf`, { credentials: 'include' });
      if (!res.ok) {
        const j = (await res.json().catch(() => ({}))) as { error?: string };
        throw new Error(j.error || 'Failed to generate PDF');
      }
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `qr-${branch?.name ?? 'tables'}.pdf`;
      document.body.appendChild(a);
      a.click();
      setTimeout(() => { URL.revokeObjectURL(url); a.remove(); }, 0);
    } catch (e) {
      setError((e as Error).message ?? 'Failed to download PDF');
    } finally {
      setDownloading(false);
    }
  };

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

  return (
    <div className="max-w-2xl mx-auto p-6">
      <Link
        href={`/branch-management/${branchId}/tables`}
        className="inline-flex items-center gap-1 text-sm text-slate-500 hover:text-slate-900 mb-4"
      >
        <ArrowLeft size={14} /> Back to tables
      </Link>

      <h1 className="text-2xl font-bold text-slate-900">Print QR codes</h1>
      <p className="text-sm text-slate-500 mt-1">
        Generates a print-ready PDF — one A6 card per active table for {restaurantName}
        {branch?.name ? ` · ${branch.name}` : ''}.
      </p>

      <div className="mt-6 rounded-xl border border-slate-200 bg-white p-6">
        <p className="text-sm text-slate-600">
          Each card includes the table number, your branding, the QR code that auto-fills the table on
          the storefront, and a &ldquo;Scan to order&rdquo; caption. Use A6 paper or trim from A4.
        </p>

        {error && (
          <div className="mt-3 rounded-lg bg-rose-50 border border-rose-200 px-3 py-2 text-sm text-rose-700">
            {error}
          </div>
        )}

        <button
          onClick={downloadPdf}
          disabled={downloading}
          className="mt-4 inline-flex items-center gap-2 bg-orange-500 hover:bg-orange-600 disabled:bg-slate-300 text-white text-sm font-semibold px-4 py-2.5 rounded-lg"
        >
          {downloading ? <Loader2 size={16} className="animate-spin" /> : <FileDown size={16} />}
          {downloading ? 'Building PDF…' : 'Download QR PDF'}
        </button>
      </div>
    </div>
  );
}
