'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 LoginResponse {
  accessToken: string;
  refreshToken: string;
  user: { id: string; email?: string; phone?: string; name: string; roles: string[]; tenantId?: string };
}

type LoginMethod = 'email' | 'phone';

export default function LoginPage() {
  const router = useRouter();
  const { t } = useTranslation('auth');
  const [loginMethod, setLoginMethod] = useState<LoginMethod>('email');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [phone, setPhone] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const saveSession = (data: LoginResponse) => {
    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 */ }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);
    try {
      if (loginMethod === 'email') {
        const data = await apiClient<LoginResponse>('/api/v1/auth/login', {
          method: 'POST',
          body: { email, password },
        });
        saveSession(data);
      } else {
        const data = await apiClient<LoginResponse>('/api/v1/auth/login', {
          method: 'POST',
          body: { phone: phone.trim(), password },
        });
        saveSession(data);
      }
      router.push('/dashboard');
    } catch (err) {
      setError(err instanceof Error ? err.message : t('loginFailed'));
    } 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('adminConsole')}</p>
      </div>

      {/* Login method toggle */}
      <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'}`}>
          邮箱登录
        </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'}`}>
          手机验证码
        </button>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        {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" placeholder={t('emailPlaceholder')} 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" required />
            </div>
          </>
        ) : (
          <>
            <div>
              <label className="block text-sm font-medium mb-1">手机号</label>
              <input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)}
                className="w-full px-3 py-2 bg-input border rounded-md" placeholder="+86 138 0000 0000" 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" 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">
          {isLoading ? t('signingIn') : t('signIn')}
        </button>
      </form>

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