'use client';

import { useEffect, useMemo, useState } from 'react';
import { Suspense } from 'react';
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 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('Invalid invitation link');
      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('This invitation is already accepted. You can log in now.');
        }
      } catch (e: any) {
        setError(e?.message || 'Could not load invitation');
      } finally {
        setLoading(false);
      }
    })();
  }, [token]);

  async function onAccept() {
    if (!token) return;
    setError('');
    setSuccess('');
    if (!name.trim()) {
      setError('Name is required');
      return;
    }
    if (password.length < 8) {
      setError('Password must be at least 8 characters');
      return;
    }
    if (password !== confirmPassword) {
      setError('Passwords do not match');
      return;
    }

    setSubmitting(true);
    try {
      await staffApi.acceptInvite({
        token,
        name: name.trim(),
        password,
      });
      setSuccess('Invitation Accepted. Redirecting to login...');
      setTimeout(() => {
        router.replace('/login');
      }, 1000);
    } catch (e: any) {
      setError(e?.message || 'Could not accept invitation');
    } finally {
      setSubmitting(false);
    }
  }

  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">Accept invitation</h1>

        {loading ? (
          <p className="text-sm text-text-secondary">Loading invitation...</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>
                  Organization: <span className="text-text-primary">{inviteInfo.organizationName}</span>
                </p>
                <p>
                  Email: <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="Name" value={name} onChange={(e) => setName(e.target.value)} />
                <Input
                  label="Create password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />
                <Input
                  label="Confirm password"
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                />
                <Button type="button" fullWidth isLoading={submitting} onClick={() => void onAccept()}>
                  Activate account
                </Button>
              </div>
            )}

            <p className="text-xs text-text-muted">
              Already have access? <Link href="/login" className="text-primary">Go to login</Link>
            </p>
          </>
        )}
      </div>
    </div>
  );
}

export default function AcceptInvitePage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen app-web-bg flex items-center justify-center">
          <p className="text-sm text-text-secondary">Loading invitation...</p>
        </div>
      }
    >
      <AcceptInviteContent />
    </Suspense>
  );
}
