'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 { staffApi } from '@/lib/api/staff';

function AcceptInviteContent() {
  const t = useTranslations('auth');
  const params = useSearchParams();
  const router = useRouter();
  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';
  } | 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);
        setName(res.data.name || '');
        if (res.data.status === 'ACCEPTED') {
          setSuccess(t('invitationAlreadyAccepted'));
        }
      } catch (e: unknown) {
        const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
        setError(message || t('errorLoadInvitation'));
      } finally {
        setLoading(false);
      }
    })();
  }, [token, t]);

  async function onAccept() {
    if (!token) return;
    setError('');
    setSuccess('');
    if (!name.trim()) {
      setError(t('nameRequired'));
      return;
    }
    if (password.length < 8) {
      setError(t('passwordMinLength8'));
      return;
    }
    if (password !== confirmPassword) {
      setError(t('passwordsDoNotMatch'));
      return;
    }

    setSubmitting(true);
    try {
      await staffApi.acceptInvite({
        token,
        name: name.trim(),
        password,
      });
      setSuccess(t('invitationAcceptedRedirect'));
      setTimeout(() => {
        router.replace('/login');
      }, 1000);
    } catch (e: unknown) {
      const message = e && typeof e === 'object' && 'message' in e ? String(e.message) : '';
      setError(message || t('errorAcceptInvitation'));
    } finally {
      setSubmitting(false);
    }
  }

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

  return (
    <div className="min-h-screen app-web-bg flex items-center justify-center p-4">
      <div className="w-full max-w-md surface-card p-6 space-y-5">
        <h1 className="text-xl font-semibold text-text-primary">{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">
                <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={() => void onAccept()}>
                  {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-screen app-web-bg flex items-center justify-center">
      <p className="text-sm text-text-secondary">{t('loadingInvitation')}</p>
    </div>
  );
}

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