'use client';

import { useState, useEffect, useRef } 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; phone?: string; name: string; roles: string[]; tenantId: string };
}

type LoginMethod = 'email' | 'phone';

export default function RegisterPage() {
  const router = useRouter();
  const { t } = useTranslation('auth');
  const { t: tc } = useTranslation('common');

  const [loginMethod, setLoginMethod] = useState<LoginMethod>('email');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [smsCode, setSmsCode] = useState('');
  const [smsCooldown, setSmsCooldown] = useState(0);
  const [smsSending, setSmsSending] = useState(false);
  const cooldownRef = useRef<ReturnType<typeof setInterval> | null>(null);
  const [companyName, setCompanyName] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [appDownloadUrl, setAppDownloadUrl] = useState<{ android?: string; ios?: string }>({});

  useEffect(() => {
    // Try to fetch latest app version for download links
    fetch('/api/app/version/check?platform=android&current_version_code=0')
      .then((r) => r.json())
      .then((d) => {
        if (d?.downloadUrl) setAppDownloadUrl((prev) => ({ ...prev, android: d.downloadUrl }));
      })
      .catch(() => {});
  }, []);

  const handleSendSms = async () => {
    if (!phone.trim()) { setError('请先填写手机号'); return; }
    setError(null);
    setSmsSending(true);
    try {
      await apiClient('/api/v1/auth/sms/send', { method: 'POST', body: { phone: phone.trim(), purpose: 'register' } });
      setSmsCooldown(60);
      if (cooldownRef.current) clearInterval(cooldownRef.current);
      cooldownRef.current = setInterval(() => {
        setSmsCooldown((prev) => {
          if (prev <= 1) { clearInterval(cooldownRef.current!); return 0; }
          return prev - 1;
        });
      }, 1000);
    } catch (err) {
      setError(err instanceof Error ? err.message : '发送失败，请重试');
    } finally {
      setSmsSending(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password !== confirmPassword) {
      setError(tc('passwordsNoMatch'));
      return;
    }
    if (password.length < 6) {
      setError('密码至少 6 位');
      return;
    }
    if (!companyName.trim()) {
      setError('请填写企业名称');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const body: Record<string, string> = {
        password,
        name,
        companyName,
      };
      if (loginMethod === 'email') {
        body.email = email;
      } else {
        if (!smsCode.trim()) { setError('请输入短信验证码'); setIsLoading(false); return; }
        body.phone = phone;
        body.smsCode = smsCode;
      }

      const data = await apiClient<RegisterResponse>('/api/v1/auth/register', {
        method: 'POST',
        body,
      });

      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) {
      setError(err instanceof Error ? err.message : '注册失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="w-full max-w-lg space-y-6">
      {/* Header */}
      <div className="text-center">
        <img src="/icons/logo.svg" alt="iAgent" className="w-16 h-16 mx-auto mb-3" />
        <h1 className="text-2xl font-bold">{t('enterpriseRegTitle')}</h1>
        <p className="text-muted-foreground mt-2 text-sm leading-relaxed">{t('enterpriseRegSubtitle')}</p>
      </div>

      {/* Registration Card */}
      <div className="p-8 bg-card rounded-lg border space-y-5">
        {/* Login method toggle */}
        <div>
          <label className="block text-sm font-medium mb-2">{t('loginMethod')}</label>
          <div className="flex rounded-md border overflow-hidden">
            <button
              type="button"
              onClick={() => setLoginMethod('email')}
              className={`flex-1 py-2 text-sm font-medium transition-colors ${
                loginMethod === 'email'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-transparent text-muted-foreground hover:text-foreground'
              }`}
            >
              {t('loginByEmail')}
            </button>
            <button
              type="button"
              onClick={() => setLoginMethod('phone')}
              className={`flex-1 py-2 text-sm font-medium transition-colors ${
                loginMethod === 'phone'
                  ? 'bg-primary text-primary-foreground'
                  : 'bg-transparent text-muted-foreground hover:text-foreground'
              }`}
            >
              {t('loginByPhone')}
            </button>
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          {/* Identifier field */}
          {loginMethod === 'email' ? (
            <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('phone')}</label>
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="w-full px-3 py-2 bg-input border rounded-md text-sm"
                  placeholder={t('phonePlaceholder')}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">短信验证码</label>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={smsCode}
                    onChange={(e) => setSmsCode(e.target.value)}
                    className="flex-1 px-3 py-2 bg-input border rounded-md text-sm"
                    placeholder="请输入 6 位验证码"
                    maxLength={6}
                    required
                  />
                  <button
                    type="button"
                    onClick={handleSendSms}
                    disabled={smsSending || smsCooldown > 0}
                    className="px-4 py-2 text-sm font-medium bg-secondary text-secondary-foreground rounded-md hover:opacity-90 disabled:opacity-50 whitespace-nowrap"
                  >
                    {smsSending ? '发送中...' : smsCooldown > 0 ? `${smsCooldown}s` : '获取验证码'}
                  </button>
                </div>
              </div>
            </>
          )}

          {/* Full name */}
          <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>

          {/* Company name — required for enterprise */}
          <div>
            <label className="block text-sm font-medium mb-1">{t('organizationName')}</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')}
              required
            />
            <p className="text-xs text-muted-foreground mt-1">{t('organizationHint')}</p>
          </div>

          {/* Password */}
          <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.5 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>

      {/* App download section */}
      <div className="p-5 bg-muted/50 rounded-lg border border-dashed space-y-3">
        <div className="flex items-center gap-2">
          <span className="text-lg">📱</span>
          <h3 className="text-sm font-semibold">{t('downloadApp')}</h3>
        </div>
        <p className="text-xs text-muted-foreground leading-relaxed">{t('downloadAppDesc')}</p>
        <div className="flex gap-3">
          {appDownloadUrl.android ? (
            <a
              href={appDownloadUrl.android}
              className="flex-1 py-2 text-center text-xs font-medium bg-card border rounded-md hover:bg-accent transition-colors"
            >
              {t('downloadAndroid')}
            </a>
          ) : (
            <Link
              href="/app-versions"
              className="flex-1 py-2 text-center text-xs font-medium bg-card border rounded-md hover:bg-accent transition-colors"
            >
              {t('downloadAndroid')}
            </Link>
          )}
          <span className="flex-1 py-2 text-center text-xs font-medium bg-card border rounded-md text-muted-foreground cursor-not-allowed">
            {t('downloadIOS')} (即将上线)
          </span>
        </div>
      </div>
    </div>
  );
}
