import React from 'react';
import { Loader2, PanelLeftClose, PanelRightOpen } from 'lucide-react';

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

const DEV_TENANT_KEYS = [
  { key: 'cust-standard-empty', label: 'Endkunde – Standard (kein Event)' },
  { key: 'cust-starter-wedding', label: 'Endkunde – Starter (Hochzeit)' },
  { key: 'reseller-s-active', label: 'Reseller S – 3 aktive Events' },
  { key: 'reseller-s-full', label: 'Reseller S – voll belegt (5/5)' },
] 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);
  const [collapsed, setCollapsed] = React.useState<boolean>(() => {
    if (typeof window === 'undefined') {
      return false;
    }

    try {
      return window.localStorage.getItem('fotospiel-dev-switcher-collapsed') === '1';
    } catch (error) {
      console.warn('[DevAuth] Failed to read collapse state', error);
      return false;
    }
  });

  React.useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }

    try {
      window.localStorage.setItem('fotospiel-dev-switcher-collapsed', collapsed ? '1' : '0');
    } catch (error) {
      console.warn('[DevAuth] Failed to persist collapse state', error);
    }
  }, [collapsed]);

  if (!helper) {
    return null;
  }

  if (collapsed) {
    return (
      <button
        type="button"
        className="pointer-events-auto fixed bottom-4 right-4 z-[1000] flex items-center gap-2 rounded-full border border-amber-200 bg-white/95 px-4 py-2 text-sm font-medium text-amber-700 shadow-lg shadow-amber-200/60 transition hover:bg-amber-50"
        onClick={() => setCollapsed(false)}
      >
        <PanelRightOpen className="h-4 w-4" />
        Demo tenants
      </button>
    );
  }

  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">
        <div className="flex items-center gap-2">
          <strong className="text-amber-800">Demo tenants</strong>
          <span className="text-xs uppercase tracking-wide text-amber-600">Dev mode</span>
        </div>
        <button
          type="button"
          onClick={() => setCollapsed(true)}
          className="inline-flex h-7 w-7 items-center justify-center rounded-full border border-amber-200 bg-white text-amber-600 transition hover:bg-amber-50"
          aria-label="Switcher minimieren"
        >
          <PanelLeftClose className="h-4 w-4" />
        </button>
      </div>
      <p className="text-xs text-amber-700">
        Select a seeded tenant to mint Sanctum PATs 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>
  );
}

export default DevTenantSwitcher;
