'use client';

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

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

export default function RegisterPage() {
  const router = useRouter();
  const { t } = useTranslation('auth');
  const { t: tc } = useTranslation('common');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      setError(tc('passwordsNoMatch'));
      return;
    }
    if (password.length < 6) {
      setError(t('passwordMinLength', 'Password must be at least 6 characters'));
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const data = await apiClient<RegisterResponse>('/api/v1/auth/register', {
        method: 'POST',
        body: {
          email,
          password,
          name,
          ...(companyName ? { companyName } : {}),
        },
      });

      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 decode errors */ }

      router.push('/dashboard');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Registration failed');
    } finally {
      setIsLoading(false);
    }
  };

  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('createAccount')}</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('email')}</label>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            className="w-full px-3 py-2 bg-input border rounded-md text-sm"
            placeholder={t('emailPlaceholder')}
            required
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">
            {t('organizationName')}
            <span className="text-muted-foreground font-normal ml-1">({tc('optional')})</span>
          </label>
          <input
            type="text"
            value={companyName}
            onChange={(e) => setCompanyName(e.target.value)}
            className="w-full px-3 py-2 bg-input border rounded-md text-sm"
            placeholder={t('organizationNamePlaceholder')}
          />
          <p className="text-xs text-muted-foreground mt-1">
            {t('organizationHint')}
          </p>
        </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>

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

        <button
          type="submit"
          disabled={isLoading}
          className="w-full py-2 bg-primary text-primary-foreground rounded-md hover:opacity-90 disabled:opacity-50 text-sm font-medium"
        >
          {isLoading ? t('creatingAccount') : t('register')}
        </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>
  );
}
