import { useState, useEffect, useRef } from 'react';
import { useLogto } from '@logto/react';
import { Card, Input, Button, FormField, Alert } from '@cameleer/design-system';
import cameleerLogo from '@cameleer/design-system/assets/cameleer-logo.svg';
import { api } from '../api/client';
import { toSlug } from '../utils/slug';
import styles from './OnboardingPage.module.css';

interface TenantResponse {
  id: string;
  name: string;
  slug: string;
  status: string;
}

export function OnboardingPage() {
  const { signIn } = useLogto();
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [slugAvailable, setSlugAvailable] = useState<boolean | null>(null);
  const [checkingSlug, setCheckingSlug] = useState(false);
  const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined);

  const slug = toSlug(name);

  useEffect(() => {
    setSlugAvailable(null);
    if (!slug) return;

    setCheckingSlug(true);
    clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(async () => {
      try {
        const res = await api.get<{ available: boolean }>(`/onboarding/slug-available?slug=${encodeURIComponent(slug)}`);
        setSlugAvailable(res.available);
      } catch {
        setSlugAvailable(null);
      } finally {
        setCheckingSlug(false);
      }
    }, 400);

    return () => clearTimeout(debounceRef.current);
  }, [slug]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);
    try {
      await api.post<TenantResponse>('/onboarding/tenant', { name, slug });
      // Tenant created — force a fresh OIDC sign-in so the Logto SDK gets
      // new tokens that include the org membership just created. The existing
      // Logto session cookie means the user won't see a login form — Logto
      // auto-approves and redirects back with fresh tokens.
      await signIn(`${window.location.origin}/platform/callback`);
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      if (msg.includes('409')) {
        setError('This organization name is already taken. Try a different organization name.');
      } else {
        setError(msg || 'Failed to create tenant');
      }
      setLoading(false);
    }
  }

  return (
    <div className={styles.page}>
      <div className={styles.wrapper}>
        <Card className={styles.card}>
          <div className={styles.inner}>
            <div className={styles.logo}>
              <img src={cameleerLogo} alt="" className={styles.logoImg} />
              Welcome to Cameleer
            </div>
            <p className={styles.subtitle}>
              Set up your workspace to start monitoring your Camel routes.
            </p>

            {error && (
              <div className={styles.error}>
                <Alert variant="error">{error}</Alert>
              </div>
            )}

            <form onSubmit={handleSubmit} className={styles.form} noValidate>
              <FormField label="Organization name" htmlFor="onboard-name" required>
                <Input
                  id="onboard-name"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="Acme Corp"
                  autoFocus
                  disabled={loading}
                  required
                />
              </FormField>

              <FormField label="URL slug" htmlFor="onboard-slug" required
                hint={
                  !slug ? 'Auto-generated from name. Appears in your dashboard URL.'
                    : checkingSlug ? 'Checking availability...'
                    : slugAvailable === true ? 'Available'
                    : 'Auto-generated from name. Appears in your dashboard URL.'
                }
                error={slugAvailable === false ? 'This organization name is already taken. Try a different name.' : undefined}
              >
                <Input
                  id="onboard-slug"
                  value={slug}
                  placeholder="acme-corp"
                  readOnly
                />
              </FormField>

              <Button
                variant="primary"
                type="submit"
                loading={loading}
                disabled={loading || !name || !slug || slugAvailable === false}
                className={styles.submit}
              >
                {loading ? 'Creating...' : 'Create workspace'}
              </Button>
            </form>
          </div>
        </Card>
      </div>
    </div>
  );
}
