'use client';

import { useEffect, useState, useMemo, use } from 'react';
import Link from 'next/link';
import { ArrowLeft, Plus, Trash2, Pencil, QrCode, Printer, Layers, Loader2, AlertCircle, ExternalLink, Settings } from 'lucide-react';
import { toast } from 'sonner';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useAuth } from '@client/contexts/AuthContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { listTables, createTable, bulkCreateTables, updateTable, deleteTable, type RestaurantTable } from '@client/api/tables';
import { getBranch, type Branch } from '@client/api/branches';
import QrDesigner from '@client/components/storefront/QrDesigner';
import ConfirmModal from '@client/components/ui/ConfirmModal';
import type { QrStyle } from '@client/utils/qr';

interface BranchExtra extends Branch {
  slug?: string;
  storefront_enabled?: boolean;
  accepts_dine_in?: boolean;
  accepts_takeaway?: boolean;
  accepts_delivery?: boolean;
  min_order_value?: number;
  storefront_message?: string | null;
  qr_style_json?: Record<string, unknown>;
}

export default function BranchTablesPage({ params }: { params: Promise<{ id: string }> }) {
  const { id: branchId } = use(params);
  const { setPageHeader } = usePageHeader();
  const { userRecord } = useAuth();
  const { t } = useLanguage();
  const restaurantSlug = (userRecord?.restaurants?.slug as string | undefined) ?? '';

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [branch, setBranch] = useState<BranchExtra | null>(null);
  const [tables, setTables] = useState<RestaurantTable[]>([]);

  // Forms
  const [formNumber, setFormNumber] = useState('');
  const [formCapacity, setFormCapacity] = useState('4');
  const [formLabel, setFormLabel] = useState('');
  const [formZone, setFormZone] = useState('');
  const [bulkPrefix, setBulkPrefix] = useState('');
  const [bulkStart, setBulkStart] = useState('1');
  const [bulkEnd, setBulkEnd] = useState('10');
  const [bulkCapacity, setBulkCapacity] = useState('4');
  const [bulkZone, setBulkZone] = useState('');
  const [editing, setEditing] = useState<RestaurantTable | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<RestaurantTable | null>(null);
  const [activeQr, setActiveQr] = useState<RestaurantTable | null>(null);

  useEffect(() => {
    setPageHeader('Tables', branch?.name || 'Manage tables for this branch');
  }, [setPageHeader, branch?.name]);

  const refresh = async () => {
    setLoading(true);
    setError(null);
    try {
      const [b, t] = await Promise.all([
        getBranch(branchId),
        listTables(branchId),
      ]);
      setBranch(b.branch as BranchExtra);
      setTables(t.tables ?? []);
    } catch (e) {
      setError((e as Error).message ?? 'Failed to load');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { refresh(); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [branchId]);

  const branchSlug = branch?.slug || '';
  const baseStorefrontUrl = useMemo(() => {
    if (typeof window === 'undefined' || !restaurantSlug || !branchSlug) return '';
    return `${window.location.origin}/r/${restaurantSlug}/${branchSlug}`;
  }, [restaurantSlug, branchSlug]);

  const tableUrl = (t: RestaurantTable) => `${baseStorefrontUrl}?table=${encodeURIComponent(t.table_number)}`;

  const onAdd = async () => {
    if (!formNumber.trim()) { toast.error('Table number is required'); return; }
    try {
      await createTable({
        branch_id: branchId,
        table_number: formNumber.trim(),
        label: formLabel.trim() || undefined,
        capacity: Number(formCapacity) || 1,
        zone: formZone.trim() || undefined,
      });
      toast.success(`Table ${formNumber} created`);
      setFormNumber(''); setFormLabel(''); setFormCapacity('4'); setFormZone('');
      refresh();
    } catch (e) {
      toast.error((e as Error).message ?? 'Failed to create table');
    }
  };

  const onBulkAdd = async () => {
    const s = parseInt(bulkStart, 10), e = parseInt(bulkEnd, 10);
    if (!Number.isFinite(s) || !Number.isFinite(e) || e < s) { toast.error('Invalid range'); return; }
    try {
      const r = await bulkCreateTables({
        branch_id: branchId, start: s, end: e,
        prefix: bulkPrefix.trim() || undefined,
        capacity: Number(bulkCapacity) || 4,
        zone: bulkZone.trim() || undefined,
      });
      toast.success(`${r.created} of ${r.requested} table(s) added`);
      refresh();
    } catch (err) {
      toast.error((err as Error).message ?? 'Bulk create failed');
    }
  };

  const onSaveEdit = async () => {
    if (!editing) return;
    try {
      await updateTable(editing.id, {
        table_number: editing.table_number,
        label: editing.label,
        capacity: editing.capacity,
        zone: editing.zone,
        is_active: editing.is_active,
      });
      toast.success('Table updated');
      setEditing(null);
      refresh();
    } catch (e) {
      toast.error((e as Error).message ?? 'Update failed');
    }
  };

  const onDelete = async () => {
    if (!confirmDelete) return;
    try {
      await deleteTable(confirmDelete.id);
      toast.success(`Table ${confirmDelete.table_number} removed`);
      setConfirmDelete(null);
      refresh();
    } catch (e) {
      toast.error((e as Error).message ?? 'Delete failed');
    }
  };

  const branchQrStyle: QrStyle = useMemo(() => ({
    fg: (branch?.qr_style_json?.fg as string) ?? '#111827',
    bg: (branch?.qr_style_json?.bg as string) ?? '#ffffff',
    margin: (branch?.qr_style_json?.margin as number) ?? 2,
    ecc: ((branch?.qr_style_json?.ecc as 'L' | 'M' | 'Q' | 'H') ?? 'M'),
  }), [branch?.qr_style_json]);

  const printAll = () => {
    if (typeof window === 'undefined') return;
    window.open(`/branch-management/${branchId}/tables/print`, '_blank');
  };

  if (loading) {
    return <div className="p-8 flex items-center justify-center text-slate-500"><Loader2 className="animate-spin mr-2" /> Loading…</div>;
  }
  if (error || !branch) {
    return <div className="p-8 text-red-600 flex items-center gap-2"><AlertCircle size={18} /> {error ?? 'Branch not found'}</div>;
  }

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

      <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">{branch.name}</h1>
          <p className="text-sm text-slate-500">{branch.address}</p>
        </div>
        {baseStorefrontUrl && (
          <a href={baseStorefrontUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1.5 text-sm font-semibold text-orange-600 hover:text-orange-700">
            Open storefront <ExternalLink size={14} />
          </a>
        )}
      </div>

      <Link
        href={`/storefront/${branchId}`}
        className="mb-6 flex items-center justify-between gap-3 bg-orange-50 border border-orange-200 hover:bg-orange-100 text-orange-800 rounded-xl p-3"
      >
        <div className="flex items-center gap-2 text-sm">
          <Settings size={16} />
          <span className="font-semibold">
            {t('tables.banner.editStorefront', 'Edit QR design & storefront settings')}
          </span>
          <span className="text-orange-700/80 hidden sm:inline">
            {t('tables.banner.movedTo', '— moved to QR Storefront')}
          </span>
        </div>
        <span className="text-xs font-semibold underline">{t('tables.banner.open', 'Open')}</span>
      </Link>

      <div className="space-y-6">
          <section className="bg-white border border-slate-200 rounded-xl p-4">
            <h2 className="font-semibold text-slate-900 mb-3">Add a single table</h2>
            <div className="grid grid-cols-1 md:grid-cols-5 gap-2">
              <input className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Table number *" value={formNumber} onChange={(e) => setFormNumber(e.target.value)} />
              <input className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Label (e.g. Patio 1)" value={formLabel} onChange={(e) => setFormLabel(e.target.value)} />
              <input className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Zone (e.g. Patio)" value={formZone} onChange={(e) => setFormZone(e.target.value)} />
              <input type="number" min={1} className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Seats" value={formCapacity} onChange={(e) => setFormCapacity(e.target.value)} />
              <button onClick={onAdd} className="bg-orange-500 hover:bg-orange-600 text-white rounded-lg px-3 py-2 text-sm font-semibold flex items-center justify-center gap-1.5">
                <Plus size={14} /> Add
              </button>
            </div>
          </section>

          <section className="bg-white border border-slate-200 rounded-xl p-4">
            <h2 className="font-semibold text-slate-900 mb-3 flex items-center gap-2"><Layers size={16} /> Bulk create</h2>
            <div className="grid grid-cols-2 md:grid-cols-6 gap-2">
              <input className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Prefix (e.g. T)" value={bulkPrefix} onChange={(e) => setBulkPrefix(e.target.value)} />
              <input type="number" className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Start" value={bulkStart} onChange={(e) => setBulkStart(e.target.value)} />
              <input type="number" className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="End" value={bulkEnd} onChange={(e) => setBulkEnd(e.target.value)} />
              <input type="number" min={1} className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Default seats" value={bulkCapacity} onChange={(e) => setBulkCapacity(e.target.value)} />
              <input className="rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Zone (optional)" value={bulkZone} onChange={(e) => setBulkZone(e.target.value)} />
              <button onClick={onBulkAdd} className="bg-slate-900 hover:bg-slate-800 text-white rounded-lg px-3 py-2 text-sm font-semibold">Create range</button>
            </div>
            <p className="text-xs text-slate-500 mt-2">Skips numbers that already exist.</p>
          </section>

          <section className="bg-white border border-slate-200 rounded-xl">
            <div className="flex items-center justify-between p-4 border-b border-slate-100">
              <h2 className="font-semibold text-slate-900">{tables.length} table(s)</h2>
              <button disabled={tables.length === 0 || !baseStorefrontUrl} onClick={printAll} className="inline-flex items-center gap-1.5 bg-white border border-slate-200 hover:bg-slate-50 text-slate-700 text-xs font-semibold px-3 py-2 rounded-lg disabled:opacity-50">
                <Printer size={14} /> Print all QR codes
              </button>
            </div>
            {tables.length === 0 ? (
              <div className="p-8 text-center text-slate-500 text-sm">No tables yet. Add one above.</div>
            ) : (
              <div className="divide-y divide-slate-100">
                {tables.map((t) => (
                  <div key={t.id} className="p-4 flex items-center gap-3">
                    <div className="flex-1 min-w-0">
                      <p className="font-semibold text-slate-900">Table {t.table_number} {t.label ? <span className="text-slate-400 font-normal">— {t.label}</span> : null}</p>
                      <p className="text-xs text-slate-500">Seats {t.capacity}{t.zone ? ` • ${t.zone}` : ''}{!t.is_active ? ' • Inactive' : ''}</p>
                    </div>
                    <button onClick={() => setActiveQr(t)} className="inline-flex items-center gap-1.5 text-xs font-semibold text-slate-700 bg-white border border-slate-200 hover:bg-slate-50 px-3 py-1.5 rounded-lg" title="Show QR">
                      <QrCode size={14} /> QR
                    </button>
                    <button onClick={() => setEditing(t)} className="inline-flex items-center gap-1.5 text-xs font-semibold text-slate-700 bg-white border border-slate-200 hover:bg-slate-50 px-3 py-1.5 rounded-lg">
                      <Pencil size={12} /> Edit
                    </button>
                    <button onClick={() => setConfirmDelete(t)} className="inline-flex items-center gap-1.5 text-xs font-semibold text-red-600 bg-white border border-red-200 hover:bg-red-50 px-3 py-1.5 rounded-lg">
                      <Trash2 size={12} /> Delete
                    </button>
                  </div>
                ))}
              </div>
            )}
          </section>
        </div>

      {/* Edit modal */}
      {editing && (
        <Modal onClose={() => setEditing(null)} title={`Edit table ${editing.table_number}`}>
          <div className="space-y-3">
            <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Table number" value={editing.table_number} onChange={(e) => setEditing({ ...editing, table_number: e.target.value })} />
            <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Label" value={editing.label ?? ''} onChange={(e) => setEditing({ ...editing, label: e.target.value })} />
            <input className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Zone (e.g. Patio)" value={editing.zone ?? ''} onChange={(e) => setEditing({ ...editing, zone: e.target.value })} />
            <input type="number" min={1} className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm" placeholder="Seats" value={editing.capacity} onChange={(e) => setEditing({ ...editing, capacity: Number(e.target.value) })} />
            <Toggle label="Active" checked={editing.is_active} onChange={(v) => setEditing({ ...editing, is_active: v })} />
            <div className="flex justify-end gap-2 pt-2">
              <button onClick={() => setEditing(null)} className="px-4 py-2 text-sm font-semibold text-slate-600">Cancel</button>
              <button onClick={onSaveEdit} className="bg-orange-500 hover:bg-orange-600 text-white rounded-lg px-4 py-2 text-sm font-semibold">Save</button>
            </div>
          </div>
        </Modal>
      )}

      {/* QR preview modal */}
      {activeQr && baseStorefrontUrl && (
        <Modal onClose={() => setActiveQr(null)} title={`QR for table ${activeQr.table_number}`}>
          <QrDesigner
            url={tableUrl(activeQr)}
            style={branchQrStyle}
            filename={`qr-${branchSlug}-table-${activeQr.table_number}`}
            caption={`Table ${activeQr.table_number}${activeQr.label ? ` — ${activeQr.label}` : ''}`}
          />
        </Modal>
      )}

      <ConfirmModal
        isOpen={!!confirmDelete}
        onClose={() => setConfirmDelete(null)}
        onConfirm={onDelete}
        title="Delete table"
        description={confirmDelete ? `Delete table ${confirmDelete.table_number}? This cannot be undone.` : ''}
        confirmLabel="Delete"
        variant="danger"
      />
    </div>
  );
}

function Toggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (v: boolean) => void }) {
  return (
    <label className="flex items-center justify-between gap-4 py-1 cursor-pointer">
      <span className="text-sm text-slate-700">{label}</span>
      <button
        type="button"
        onClick={() => onChange(!checked)}
        className={`relative w-11 h-6 rounded-full transition-colors ${checked ? 'bg-orange-500' : 'bg-slate-300'}`}
      >
        <span className={`absolute top-0.5 left-0.5 w-5 h-5 rounded-full bg-white shadow transition-transform ${checked ? 'translate-x-5' : ''}`} />
      </button>
    </label>
  );
}

function Modal({ onClose, title, children }: { onClose: () => void; title: string; children: React.ReactNode }) {
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="bg-white rounded-xl max-w-lg w-full max-h-[90vh] overflow-hidden flex flex-col">
        <div className="flex items-center justify-between p-4 border-b border-slate-100">
          <h3 className="font-bold text-slate-900">{title}</h3>
          <button onClick={onClose} className="text-slate-400 text-xl leading-none">×</button>
        </div>
        <div className="overflow-y-auto p-4">{children}</div>
      </div>
    </div>
  );
}
