'use client';

import { useEffect, useMemo, useState } from 'react';
import { Suspense } from 'react';
import { useTranslations } from 'next-intl';
import { Link, useRouter } from '@/i18n/navigation';
import { useSearchParams } from 'next/navigation';
import { Button } from '@/components/ui/shared/Button';
import { Input } from '@/components/ui/shared/Input';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { staffApi } from '@/lib/api/staff';
import { useAuth } from '@/lib/hooks/useAuth';
import { navigateIntoAppIfOrgSelected } from '@/lib/auth/postAuthRedirect';

function AcceptInviteContent() {
  const t = useTranslations('auth');
  const tErrors = useTranslations('errors');
  const params = useSearchParams();
  const router = useRouter();
  const { login } = useAuth();
  const token = useMemo(() => params.get('token') || '', [params]);

  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [inviteInfo, setInviteInfo] = useState<{
    email: string;
    name: string;
    organizationName: string;
    expiresAt: string;
    status: 'PENDING' | 'ACCEPTED';
    mode: 'join' | 'password_setup';
  } | null>(null);

  const [name, setName] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  useEffect(() => {
    if (!token) {
      setLoading(false);
      setError(t('invalidInvitationLink'));
      return;
    }

    void (async () => {
      setLoading(true);
      setError('');
      try {
        const res = await staffApi.previewInvite(token);
        setInviteInfo({
          ...res.data,
          mode: res.data.mode === 'password_setup' ? 'password_setup' : 'join',
        });
        setName(res.data.name || '');
        if (res.data.status === 'ACCEPTED') {
          setSuccess(
            res.data.mode === 'password_setup'
              ? t('passwordSetupAlreadyDone')
              : t('invitationAlreadyAccepted'),
          );
        }
      } catch (e: unknown) {
        setError(getUserFacingError(e, tErrors, t('errorLoadInvitation')));
      } finally {
        setLoading(false);
      }
    })();
  }, [token, t]);

  async function onAccept() {
    if (!token) return;
    setError('');
    setSuccess('');
    const isPasswordSetup = inviteInfo?.mode === 'password_setup';
    const nameToSubmit = isPasswordSetup ? (inviteInfo?.name || '').trim() : name.trim();
    if (!isPasswordSetup && !nameToSubmit) {
      setError(t('nameRequired'));
      return;
    }
    if (password.length < 8) {
      setError(t('passwordMinLength8'));
      return;
    }
    if (password !== confirmPassword) {
      setError(t('passwordsDoNotMatch'));
      return;
    }

    setSubmitting(true);
    let accepted = false;
    try {
      await staffApi.acceptInvite({
        token,
        name: nameToSubmit || inviteInfo?.name || '',
        password,
      });
      accepted = true;
      const email = inviteInfo?.email?.trim();
      if (!email) {
        throw new Error('missing-invite-email');
      }
      const { organizations } = await login(email, password);
      navigateIntoAppIfOrgSelected((href) => router.replace(href), organizations.length);
    } catch (e: unknown) {
      if (accepted) {
        setSuccess(t('invitationAcceptedSignInFailed'));
        setTimeout(() => {
          router.replace('/login');
        }, 1500);
      } else {
        setError(getUserFacingError(e, tErrors, t('errorAcceptInvitation')));
      }
    } finally {
      setSubmitting(false);
    }
  }

  const passwordToggleLabels = {
    show: t('showPassword'),
    hide: t('hidePassword'),
  };

  return (
    <div className="min-h-[100dvh] app-web-bg flex items-center justify-center px-4 py-8">
      <div className="w-full max-w-md surface-card p-4 sm:p-6 space-y-5">
        <h1 className="text-lg sm:text-xl font-semibold text-text-primary">
          {inviteInfo?.mode === 'password_setup' ? t('setPasswordTitle') : t('acceptInviteTitle')}
        </h1>

        {loading ? (
          <p className="text-sm text-text-secondary">{t('loadingInvitation')}</p>
        ) : (
          <>
            {inviteInfo && (
              <div className="rounded-[var(--radius-md)] border border-border/70 bg-background-secondary/70 px-3 py-2 text-sm text-text-secondary space-y-1">
                <p>
                  {t('organizationLabel')}{' '}
                  <span className="text-text-primary">{inviteInfo.organizationName}</span>
                </p>
                <p>
                  {t('emailLabel')}{' '}
                  <span className="text-text-primary">{inviteInfo.email}</span>
                </p>
              </div>
            )}

            {error && (
              <div className="rounded-[var(--radius-md)] border border-red-500/40 bg-red-500/10 px-3 py-2 text-sm text-red-300">
                {error}
              </div>
            )}
            {success && (
              <div className="rounded-[var(--radius-md)] border border-primary/30 bg-primary-soft/40 px-3 py-2 text-sm text-text-primary">
                {success}
              </div>
            )}

            {inviteInfo?.status !== 'ACCEPTED' && (
              <div className="space-y-3">
                {inviteInfo?.mode !== 'password_setup' && (
                  <Input label={t('labelName')} value={name} onChange={(e) => setName(e.target.value)} />
                )}
                <Input
                  label={t('labelCreatePassword')}
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  passwordToggleLabels={passwordToggleLabels}
                />
                <Input
                  label={t('labelConfirmPassword')}
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  passwordToggleLabels={passwordToggleLabels}
                />
                <Button type="button" fullWidth isLoading={submitting} onClick={() => onAccept()}>
                  {inviteInfo?.mode === 'password_setup' ? t('setPasswordSubmit') : t('activateAccount')}
                </Button>
              </div>
            )}

            <p className="text-xs text-text-muted">
              {t('alreadyHaveAccess')}{' '}
              <Link href="/login" className="text-primary">{t('goToLogin')}</Link>
            </p>
          </>
        )}
      </div>
    </div>
  );
}

function AcceptInviteFallback() {
  const t = useTranslations('auth');
  return (
    <div className="min-h-[100dvh] app-web-bg flex items-center justify-center px-4">
      <p className="text-sm text-text-secondary">{t('loadingInvitation')}</p>
    </div>
  );
}

export default function AcceptInvitePage() {
  return (
    <Suspense fallback={<AcceptInviteFallback />}>
      <AcceptInviteContent />
    </Suspense>
  );
}
