'use client';

import { Suspense, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { createWorkspaceFromEntry } from '@/lib/workspaces';
import { isAuthenticated } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';

function firstParam(params: URLSearchParams, names: string[]): string | null {
  for (const name of names) {
    const value = params.get(name)?.trim();
    if (value) return value;
  }
  return null;
}

function parseQuestions(params: URLSearchParams): string[] {
  const repeated = [
    ...params.getAll('question'),
    ...params.getAll('auto_question'),
  ]
    .map((q) => q.trim())
    .filter(Boolean);
  if (repeated.length > 0) return repeated;

  const raw = params.get('questions')?.trim();
  if (!raw) return [];

  try {
    const parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return parsed.map((q) => String(q).trim()).filter(Boolean);
    }
  } catch {
    // Fall through to delimiter parsing.
  }

  return raw
    .split(/\r?\n|\|\|/)
    .map((q) => q.trim())
    .filter(Boolean);
}

function WorkspaceEntryContent() {
  const router = useRouter();
  const { t } = useTranslation();
  const searchParams = useSearchParams();
  const startedRef = useRef(false);
  const [error, setError] = useState<string | null>(null);

  const request = useMemo(() => {
    const params = new URLSearchParams(searchParams.toString());
    const ticketId = firstParam(params, ['ticket_id', 'ticket', 'issue_id', 'alert_id']);
    const alertType = firstParam(params, ['alert_type', 'source']) ?? 'o11y';
    const clusterId = firstParam(params, ['cluster_id', 'cluster']);
    const forceNew = ['1', 'true', 'yes'].includes((params.get('new') ?? '').trim().toLowerCase());
    const idempotencyKey = forceNew
      ? null
      : firstParam(params, ['idempotency_key', 'dedupe_key'])
        ?? `entry:${alertType}:${clusterId ?? ''}:${ticketId ?? ''}`;

    return {
      ticketId,
      alertType,
      clusterId,
      callbackUrl: firstParam(params, ['callback_url']),
      idempotencyKey,
      autoQuestions: parseQuestions(params),
      forceNew,
    };
  }, [searchParams]);

  const missingContextError = request.ticketId || request.clusterId
    ? null
    : t('workspaceNew.missingContextError');
  const visibleError = error ?? missingContextError;

  useEffect(() => {
    if (startedRef.current) return;

    const ticketId = request.ticketId;
    const clusterId = request.clusterId;
    if (!ticketId && !clusterId) return;

    if (!isAuthenticated()) {
      const current = window.location.pathname + window.location.search;
      router.replace(`/login?redirect=${encodeURIComponent(current)}`);
      return;
    }

    startedRef.current = true;
    (async () => {
      try {
        const result = await createWorkspaceFromEntry({
          ticketId: ticketId ?? undefined,
          alertType: request.alertType,
          clusterId: clusterId ?? undefined,
          autoQuestions: request.autoQuestions,
          callbackUrl: request.callbackUrl ?? undefined,
          idempotencyKey: request.idempotencyKey ?? undefined,
          forceNew: request.forceNew,
        });
        router.replace(`/workspace/${encodeURIComponent(result.workspaceId)}`);
      } catch (err) {
        startedRef.current = false;
        setError(err instanceof Error ? err.message : t('workspaceNew.failedDefault'));
      }
    })();
  }, [request, router]);

  return (
    <div
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: '#f6f7fb',
        color: '#1f2937',
        padding: 24,
      }}
    >
      <div
        style={{
          width: 420,
          maxWidth: '100%',
          background: '#fff',
          border: '1px solid #e5e7eb',
          borderRadius: 8,
          boxShadow: '0 8px 28px rgba(15, 23, 42, 0.08)',
          padding: 28,
          textAlign: 'center',
        }}
      >
        {!visibleError ? (
          <>
            <div
              style={{
                width: 36,
                height: 36,
                border: '3px solid #e0e0ef',
                borderTopColor: '#5c5fbc',
                borderRadius: '50%',
                animation: 'spin 0.8s linear infinite',
                margin: '0 auto 16px',
              }}
            />
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 6 }}>
              {t('workspaceNew.preparing')}
            </div>
            <div style={{ fontSize: 13, color: '#6b7280' }}>
              {request.ticketId
                ? t('workspaceNew.bindingTicket', { ticket: request.ticketId })
                : t('workspaceNew.bindingCluster', { cluster: request.clusterId ?? '' })}
            </div>
          </>
        ) : (
          <>
            <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 8 }}>
              {t('workspaceNew.unable')}
            </div>
            <div style={{ fontSize: 13, color: '#b91c1c', lineHeight: 1.5 }}>
              {visibleError}
            </div>
          </>
        )}
      </div>
      <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

export default function WorkspaceEntryPage() {
  return (
    <Suspense fallback={null}>
      <WorkspaceEntryContent />
    </Suspense>
  );
}
