'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import { useTranslation } from 'react-i18next';
import { apiClient } from '@/infrastructure/api/api-client';

interface InviteInfo {
  email: string;
  tenantName: string;
  role: string;
  expiresAt: string;
}

interface AcceptResponse {
  accessToken: string;
  refreshToken: string;
  user: { id: string; email: string; name: string; roles: string[]; tenantId: string };
}

export default function AcceptInvitePage() {
  const router = useRouter();
  const params = useParams();
  const token = params.token as string;
  const { t } = useTranslation('auth');
  const { t: tc } = useTranslation('common');

  const [invite, setInvite] = useState<InviteInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [name, setName] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState<string | null>(null);

  useEffect(() => {
    async function validateInvite() {
      try {
        const data = await apiClient<InviteInfo>(`/api/v1/auth/invite/${token}`);
        setInvite(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : t('inviteInvalid'));
      } finally {
        setLoading(false);
      }
    }
    validateInvite();
  }, [token, t]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      setSubmitError(tc('passwordsNoMatch'));
      return;
    }

    setIsSubmitting(true);
    setSubmitError(null);

    try {
      const data = await apiClient<AcceptResponse>('/api/v1/auth/accept-invite', {
        method: 'POST',
        body: { token, password, name },
      });

      localStorage.setItem('access_token', data.accessToken);
      localStorage.setItem('refresh_token', data.refreshToken);
      localStorage.setItem('user', JSON.stringify(data.user));

      try {
        const payload = JSON.parse(atob(data.accessToken.split('.')[1]));
        if (payload.tenantId) {
          localStorage.setItem('current_tenant', JSON.stringify({ id: payload.tenantId }));
        }
      } catch { /* ignore */ }

      router.push('/dashboard');
    } catch (err) {
      setSubmitError(err instanceof Error ? err.message : 'Failed to accept invitation');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="w-full max-w-md p-8 bg-card rounded-lg border text-center">
        <p className="text-muted-foreground">{t('validatingInvite')}</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="w-full max-w-md p-8 bg-card rounded-lg border text-center space-y-4">
        <h1 className="text-xl font-bold text-red-500">{t('inviteInvalid')}</h1>
        <p className="text-muted-foreground">{error}</p>
        <Link
          href="/login"
          className="inline-block px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm hover:opacity-90"
        >
          {t('backToLogin')}
        </Link>
      </div>
    );
  }

  return (
    <div className="w-full max-w-md p-8 space-y-6 bg-card rounded-lg border">
      <div className="text-center">
        <img src="/icons/logo.svg" alt="iAgent" className="w-20 h-20 mx-auto mb-2" />
        <h1 className="text-3xl font-bold">{t('appTitle')}</h1>
        <p className="text-muted-foreground mt-2">{t('inviteTitle')}</p>
      </div>

      <div className="bg-muted/50 rounded-md p-4 space-y-1 text-sm">
        <p>
          <span className="text-muted-foreground">{t('organizationName')}:</span>{' '}
          <span className="font-medium">{invite?.tenantName}</span>
        </p>
        <p>
          <span className="text-muted-foreground">{t('inviteEmail')}</span>{' '}
          <span className="font-medium">{invite?.email}</span>
        </p>
        <p>
          <span className="text-muted-foreground">{t('inviteRole')}</span>{' '}
          <span className="font-medium capitalize">{invite?.role}</span>
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-1">{t('fullName')}</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full px-3 py-2 bg-input border rounded-md text-sm"
            placeholder={t('fullNamePlaceholder')}
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">{t('password')}</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            className="w-full px-3 py-2 bg-input border rounded-md text-sm"
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">{t('confirmPassword')}</label>
          <input
            type="password"
            value={confirmPassword}
            onChange={(e) => setConfirmPassword(e.target.value)}
            className="w-full px-3 py-2 bg-input border rounded-md text-sm"
            required
          />
        </div>

        {submitError && (
          <p className="text-sm text-red-500">{submitError}</p>
        )}

        <button
          type="submit"
          disabled={isSubmitting}
          className="w-full py-2 bg-primary text-primary-foreground rounded-md hover:opacity-90 disabled:opacity-50 text-sm font-medium"
        >
          {isSubmitting ? t('joining') : t('joinOrganization')}
        </button>
      </form>

      <p className="text-center text-sm text-muted-foreground">
        {t('haveAccount')}{' '}
        <Link href="/login" className="text-primary hover:underline">
          {t('signInLink')}
        </Link>
      </p>
    </div>
  );
}
