'use client';

import { useState } from 'react';
import Link from 'next/link';
import { authClient } from '@/lib/auth-client';
import { useRouter } from 'next/navigation';

export default function SignInPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);
    const { data, error: err } = await authClient.signIn.email(
      {
        email,
        password,
        callbackURL: '/profile',
      },
      {
        onSuccess: (ctx) => {
          const token = (ctx as { response?: { headers?: { get?: (n: string) => string } } })?.response?.headers?.get?.('set-auth-token');
          if (token && typeof window !== 'undefined') {
            localStorage.setItem('auth_token', token);
          }
        },
      }
    );
    setLoading(false);
    if (err) {
      setError(err.message ?? 'Неверный email или пароль');
      return;
    }
    if (data) {
      router.push('/profile');
      router.refresh();
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-light-primary dark:bg-dark-primary px-4">
      <div className="w-full max-w-sm space-y-6">
        <div className="text-center">
          <h1 className="text-2xl font-semibold text-black dark:text-white">
            Вход в GooSeek
          </h1>
          <p className="mt-1 text-sm text-black/60 dark:text-white/60">
            Войдите в аккаунт для доступа к профилю и памяти
          </p>
        </div>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label
              htmlFor="email"
              className="block text-sm font-medium text-black dark:text-white mb-1"
            >
              Email
            </label>
            <input
              id="email"
              type="email"
              autoComplete="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full rounded-lg border border-light-200 dark:border-dark-200 bg-light-primary dark:bg-dark-primary px-3 py-2 text-black dark:text-white placeholder:text-black/40 dark:placeholder:text-white/40 focus:outline-none focus:ring-2 focus:ring-[#EA580C]"
              placeholder="you@example.com"
            />
          </div>
          <div>
            <label
              htmlFor="password"
              className="block text-sm font-medium text-black dark:text-white mb-1"
            >
              Пароль
            </label>
            <input
              id="password"
              type="password"
              autoComplete="current-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full rounded-lg border border-light-200 dark:border-dark-200 bg-light-primary dark:bg-dark-primary px-3 py-2 text-black dark:text-white placeholder:text-black/40 dark:placeholder:text-white/40 focus:outline-none focus:ring-2 focus:ring-[#EA580C]"
            />
          </div>
          {error && (
            <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
          )}
          <button
            type="submit"
            disabled={loading}
            className="w-full rounded-lg bg-[#EA580C] px-4 py-2.5 text-white font-medium hover:bg-[#EA580C]/90 disabled:opacity-50 transition-colors"
          >
            {loading ? 'Вход...' : 'Войти'}
          </button>
        </form>
        <p className="text-center text-sm text-black/60 dark:text-white/60">
          Нет аккаунта?{' '}
          <Link
            href="/sign-up"
            className="text-[#EA580C] hover:underline font-medium"
          >
            Зарегистрироваться
          </Link>
        </p>
        <p className="text-center">
          <Link
            href="/"
            className="text-sm text-black/60 dark:text-white/60 hover:underline"
          >
            ← На главную
          </Link>
        </p>
      </div>
    </div>
  );
}
