import React from 'react';
import { Loader2 } from 'lucide-react';

import { Button } from '@/components/ui/button';

const DEV_TENANT_KEYS = [
  { key: 'lumen', label: 'Lumen Moments' },
  { key: 'storycraft', label: 'Storycraft Weddings' },
  { key: 'viewfinder', label: 'Viewfinder Studios' },
  { key: 'pixel', label: 'Pixel & Co (dormant)' },
] as const;

declare global {
  interface Window {
    fotospielDemoAuth?: {
      clients: Record<string, string>;
      loginAs: (tenantKey: string) => Promise<void>;
    };
  }
}

export function DevTenantSwitcher() {
  const helper = window.fotospielDemoAuth;
  const [loggingIn, setLoggingIn] = React.useState<string | null>(null);

  if (!helper) {
    return null;
  }

  async function handleLogin(key: string) {
    if (!helper) return;
    setLoggingIn(key);
    try {
      await helper.loginAs(key);
    } catch (error) {
      console.error('[DevAuth] Switch failed', error);
      setLoggingIn(null);
    }
  }

  return (
    <div className="pointer-events-auto fixed bottom-4 right-4 z-[1000] flex max-w-xs flex-col gap-2 rounded-xl border border-amber-200 bg-white/95 p-3 text-sm shadow-xl shadow-amber-200/60">
      <div className="flex items-center justify-between gap-2">
        <strong className="text-amber-800">Demo tenants</strong>
        <span className="text-xs uppercase tracking-wide text-amber-600">Dev mode</span>
      </div>
      <p className="text-xs text-amber-700">
        Select a seeded tenant to mint OAuth tokens and jump straight into their admin space. Available only in development builds.
      </p>
      <div className="space-y-1">
        {DEV_TENANT_KEYS.map(({ key, label }) => (
          <Button
            key={key}
            variant="outline"
            className="w-full border-amber-200 text-amber-800 hover:bg-amber-50"
            disabled={Boolean(loggingIn)}
            onClick={() => void handleLogin(key)}
          >
            {loggingIn === key ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Verbinde...
              </>
            ) : (
              label
            )}
          </Button>
        ))}
      </div>
      <p className="text-[10px] text-amber-600">
        Console: <code>fotospielDemoAuth.loginAs('lumen')</code>
      </p>
    </div>
  );
}
