'use client';

import { Suspense, useState, FormEvent } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { useAuth } from '@/lib/auth-context';
import { useT } from '@/i18n';
import { API_BASE } from '@/lib/config';

function AuthForm() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const { login } = useAuth();
  const t = useT();
  const [tab, setTab] = useState<'login' | 'register'>(() =>
    searchParams.get('tab') === 'register' ? 'register' : 'login'
  );
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const [loginForm, setLoginForm] = useState({ account: '', password: '' });
  const [registerForm, setRegisterForm] = useState({ username: '', phone: '', email: '', password: '', confirmPassword: '', nickname: '' });

  function getFriendlyError(msg: string): string {
    const map: Record<string, string> = {
      '手机号格式不正确': '手机号格式不正确（11位手机号）',
      '邮箱格式不正确': '邮箱格式不正确',
      '用户名格式不正确（2-20位，支持中英文、数字、下划线）': '用户名格式不正确（2-20位，支持中英文、数字、下划线）',
      '用户名已被注册': t.auth.usernameConflict,
      '手机号已被注册': t.auth.phoneConflict,
      '邮箱已被注册': t.auth.emailConflict,
      '请填写用户名、手机号或邮箱': '请填写用户名、手机号或邮箱',
    };
    return map[msg] || msg || t.auth.loginFailed;
  }

  async function handleLogin(e: FormEvent) {
    e.preventDefault();
    setError('');
    if (!loginForm.account || !loginForm.password) { setError(t.auth.fillAccountAndPassword); return; }
    setLoading(true);
    try {
      const res = await fetch(`${API_BASE}/auth/login`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ account: loginForm.account, password: loginForm.password }),
      });
      if (!res.ok) {
        let msg = t.auth.loginFailed;
        try { const d = await res.json(); msg = d.message || msg; } catch {}
        throw new Error(msg);
      }
      const data = await res.json();
      login(data.accessToken, data.refreshToken);
      toast.success(t.auth.loginSuccess);
      router.push('/');
    } catch (err: any) { setError(getFriendlyError(err.message)); }
    finally { setLoading(false); }
  }

  async function handleRegister(e: FormEvent) {
    e.preventDefault();
    setError('');
    const { username, phone, email, password, confirmPassword, nickname } = registerForm;
    if (!username && !phone && !email) { setError(t.auth.fillPhoneOrEmail); return; }
    if (username && !/^[a-zA-Z0-9_\u4e00-\u9fa5]{2,20}$/.test(username)) { setError('用户名格式不正确（2-20位，支持中英文、数字、下划线）'); return; }
    if (phone && !/^1[3-9]\d{9}$/.test(phone)) { setError('手机号格式不正确（11位手机号）'); return; }
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { setError('邮箱格式不正确'); return; }
    if (!password) { setError(t.auth.fillPassword); return; }
    if (password.length < 6) { setError(t.auth.passwordMinLength); return; }
    if (password !== confirmPassword) { setError(t.auth.passwordsNotMatch); return; }
    setLoading(true);
    try {
      const body: Record<string, string> = { password };
      if (username) body.username = username;
      if (phone) body.phone = phone;
      if (email) body.email = email;
      if (nickname) body.nickname = nickname;
      const res = await fetch(`${API_BASE}/auth/register`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
      });
      if (!res.ok) {
        let msg = t.auth.registerFailed;
        try { const d = await res.json(); msg = d.message || msg; } catch {}
        throw new Error(msg);
      }
      const data = await res.json();
      login(data.accessToken, data.refreshToken);
      toast.success(t.auth.registerSuccess);
      router.push('/');
    } catch (err: any) { setError(getFriendlyError(err.message)); }
    finally { setLoading(false); }
  }

  return (
    <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center px-4 py-12">
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center pb-2">
          <div className="mx-auto mb-3 w-12 h-12 bg-gradient-to-br from-brand-500 to-brand-700 rounded-2xl flex items-center justify-center">
            <span className="text-white font-bold text-lg">Y</span>
          </div>
          <CardTitle className="text-xl">{tab === 'login' ? t.auth.welcomeBack : t.auth.joinTitle}</CardTitle>
          <CardDescription>
            {tab === 'login' ? t.auth.loginSubtitle : t.auth.registerSubtitle}
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs value={tab} onValueChange={(v) => { setTab(v as 'login' | 'register'); setError(''); }}>
            <TabsList className="w-full mb-6">
              <TabsTrigger value="login" className="flex-1">{t.auth.loginTitle}</TabsTrigger>
              <TabsTrigger value="register" className="flex-1">{t.auth.registerTitle}</TabsTrigger>
            </TabsList>

            {error && (
              <div className="mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg text-sm text-destructive">
                {error}
              </div>
            )}

            <TabsContent value="login">
              <form onSubmit={handleLogin} className="space-y-4">
                <Input type="text" placeholder="用户名 / 手机号 / 邮箱" value={loginForm.account}
                  onChange={(e) => setLoginForm({ ...loginForm, account: e.target.value })} />
                <Input type="password" placeholder={t.auth.password} value={loginForm.password}
                  onChange={(e) => setLoginForm({ ...loginForm, password: e.target.value })} />
                <Button type="submit" disabled={loading} className="w-full">
                  {loading ? t.auth.loggingIn : t.auth.loginTitle}
                </Button>
              </form>
            </TabsContent>

            <TabsContent value="register">
              <form onSubmit={handleRegister} className="space-y-4">
                <Input type="text" placeholder={t.auth.phone} value={registerForm.phone}
                  onChange={(e) => setRegisterForm({ ...registerForm, phone: e.target.value })} />
                <Input type="email" placeholder="Email" value={registerForm.email}
                  onChange={(e) => setRegisterForm({ ...registerForm, email: e.target.value })} />
                <Input type="text" placeholder={t.auth.usernameOptional} value={registerForm.username}
                  onChange={(e) => setRegisterForm({ ...registerForm, username: e.target.value })} />
                <Input type="text" placeholder={t.auth.nicknameOptional} value={registerForm.nickname}
                  onChange={(e) => setRegisterForm({ ...registerForm, nickname: e.target.value })} />
                <Input type="password" placeholder={t.auth.passwordHint} value={registerForm.password}
                  onChange={(e) => setRegisterForm({ ...registerForm, password: e.target.value })} />
                <Input type="password" placeholder={t.auth.confirmPassword} value={registerForm.confirmPassword}
                  onChange={(e) => setRegisterForm({ ...registerForm, confirmPassword: e.target.value })} />
                <Button type="submit" disabled={loading} className="w-full">
                  {loading ? t.auth.registering : t.auth.registerTitle}
                </Button>
                <p className="text-xs text-muted-foreground text-center leading-relaxed">
                  {t.auth.agreePrefix}{' '}
                  <Link href="/terms" className="text-brand-600 hover:underline dark:text-brand-400">{t.auth.termsOfService}</Link>
                  {' '}{' '}
                  <Link href="/privacy" className="text-brand-600 hover:underline dark:text-brand-400">{t.auth.privacyPolicy}</Link>
                  {' '}{' '}
                  <Link href="/ai-agreement" className="text-brand-600 hover:underline dark:text-brand-400">{t.auth.aiAgreement}</Link>
                </p>
              </form>
            </TabsContent>
          </Tabs>
        </CardContent>
      </Card>
    </div>
  );
}

export default function AuthPage() {
  return (
    <Suspense fallback={
      <div className="min-h-[calc(100vh-4rem)] flex items-center justify-center">
        <div className="space-y-4 w-full max-w-sm px-4">
          <Skeleton className="h-12 w-12 mx-auto rounded-2xl" />
          <Skeleton className="h-6 w-32 mx-auto" />
          <Skeleton className="h-4 w-48 mx-auto" />
          <Skeleton className="h-10 w-full" />
          <Skeleton className="h-10 w-full" />
        </div>
      </div>
    }>
      <AuthForm />
    </Suspense>
  );
}
