'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/stores/auth';
import { Button } from '@/components/ui/button';
import { SellerQueryProvider as StaffQueryProvider } from '../(seller)/providers';
import { useSelectedMembership } from '@/lib/stores/store-context';

export default function StaffLayout({ children }: { children: React.ReactNode }) {
  const router = useRouter();
  const { user, isLoading, memberships, selectStore, refreshMemberships, logout, commandGeneration } = useAuthStore();
  const selected = useSelectedMembership();
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function retryAccess() {
    setBusy(true);
    setError(null);
    try { await refreshMemberships(); }
    catch { setError('Unable to refresh store access. Please try again.'); }
    finally { setBusy(false); }
  }

  async function signOut() {
    setBusy(true);
    try { await logout(); router.replace('/login'); }
    catch { setError('Unable to sign out. Please try again.'); }
    finally { setBusy(false); }
  }
  useEffect(() => {
    if (!isLoading && !user) router.replace('/login?next=/staff');
  }, [isLoading, user, router]);
  if (isLoading || !user) return <p role="status">Loading staff access…</p>;
  if (memberships === null || !memberships.length) return (
    <main className="mx-auto max-w-lg space-y-4 px-4 py-12">
      <h1 className="text-2xl font-bold">Staff access</h1>
      <p role={memberships === null ? 'alert' : undefined}>
        {memberships === null ? 'Unable to verify store access. Please try again.' : 'No active store memberships. Ask your store manager for an invitation.'}
      </p>
      {error && <p role="alert">{error}</p>}
      <Button onClick={retryAccess} disabled={busy}>Retry store access</Button>
      <div className="flex items-center gap-4">
        <Link href="/" className="text-forest-700 underline">Marketplace</Link>
        <Button variant="ghost" onClick={signOut} disabled={busy}>Sign out</Button>
      </div>
    </main>
  );

  return (
    <div className="min-h-screen bg-slate-50">
      <header className="border-b border-slate-200 bg-white px-4 py-4">
        <div className="mx-auto flex max-w-3xl flex-wrap items-center justify-between gap-4">
          <Link href="/staff" className="font-semibold text-forest-700">Alqove Staff</Link>
          {memberships.length > 1 || !selected ? (
            <label className="flex items-center gap-2 text-sm font-medium">
              Store
              <select
                value={selected?.store_id ?? ''}
                onChange={(event) => selectStore(event.target.value)}
                className="min-h-11 max-w-56 rounded border border-slate-300 bg-white px-3"
              >
                <option value="" disabled>Choose a store</option>
                {memberships.map((membership) => (
                  <option key={membership.id} value={membership.store_id}>
                    {membership.store_name ?? membership.store_id}
                  </option>
                ))}
              </select>
            </label>
          ) : <span className="text-sm text-slate-600">{selected.store_name ?? selected.store_id}</span>}
          <Button variant="ghost" onClick={signOut} disabled={busy}>Sign out</Button>
        </div>
        {selected && (
          <nav aria-label="Staff" className="mx-auto mt-4 flex max-w-3xl gap-2 overflow-x-auto text-sm">
            {[
              ['/staff', 'Home'], ['/staff/schedule', 'My schedule'],
              ['/staff/clock', 'Clock'], ['/staff/hours', 'My hours'],
            ].map(([href, label]) => (
              <Link key={href} href={href} className="inline-flex min-h-11 items-center whitespace-nowrap rounded px-3 font-medium text-forest-700 hover:bg-forest-50 focus-visible:outline-2">{label}</Link>
            ))}
          </nav>
        )}
      </header>
      <StaffQueryProvider key={`${commandGeneration}:${user.id}:${selected?.store_id}:${selected?.capabilities.join(',')}`}>
        <main className="mx-auto max-w-3xl px-4 py-8">
          {error && <p role="alert" className="mb-4 text-red-700">{error}</p>}
          {selected ? children : <p>Select an active store to continue.</p>}
        </main>
      </StaffQueryProvider>
    </div>
  );
}
