"use client";

import React, { useRef, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Turnstile, type TurnstileRef } from "nextjs-turnstile";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { loginViaCookie } from "@/lib/auth-api";
import { AuthSocialButtons } from "@/components/auth-social-buttons";
import { cn } from "@/lib/utils";

const TURNSTILE_SITE_KEY =
  process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY ?? process.env.NEXT_PUBLIC_CLOUD_FLARE_SITE_KEY ?? "";

export default function LoginPage() {
  const router = useRouter();
  const turnstileRef = useRef<TurnstileRef>(null);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [turnstileToken, setTurnstileToken] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!email.trim()) {
      setError("E-posta gerekli.");
      return;
    }
    if (!password) {
      setError("Şifre gerekli.");
      return;
    }
    if (TURNSTILE_SITE_KEY && !turnstileToken) {
      setError("Lütfen doğrulamayı tamamlayın.");
      return;
    }
    setLoading(true);
    try {
      await loginViaCookie(email.trim(), password);
      if (typeof window !== "undefined") window.dispatchEvent(new Event("auth-change"));
      router.push("/");
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Giriş yapılamadı.");
      turnstileRef.current?.reset();
      setTurnstileToken(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex min-h-[calc(100vh-4rem)] items-center justify-center bg-zinc-50 px-4 py-12 dark:bg-neutral-950">
      <div className="w-full max-w-md animate-in fade-in duration-300">
        <div className="rounded-2xl border border-neutral-200 bg-white p-8 shadow-sm dark:border-neutral-800 dark:bg-neutral-900">
          <h1 className="text-2xl font-bold text-neutral-900 dark:text-white">
            Giriş yap
          </h1>
          <p className="mt-1 text-sm text-neutral-500 dark:text-neutral-400">
            Hesabınıza giriş yapın
          </p>

          <form onSubmit={handleSubmit} className="mt-6 space-y-4">
            {error && (
              <div
                className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950/50 dark:text-red-400"
                role="alert"
              >
                {error}
              </div>
            )}

            <div className="space-y-2">
              <Label htmlFor="login-email">E-posta</Label>
              <Input
                id="login-email"
                type="email"
                autoComplete="email"
                placeholder="ornek@email.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                disabled={loading}
                className={cn(
                  "w-full rounded-lg border-neutral-200 dark:border-neutral-700"
                )}
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="login-password">Şifre</Label>
              <Input
                id="login-password"
                type="password"
                autoComplete="current-password"
                placeholder="••••••••"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                disabled={loading}
                className="w-full rounded-lg border-neutral-200 dark:border-neutral-700"
              />
            </div>

            {TURNSTILE_SITE_KEY && (
              <div className="flex justify-center [&_iframe]:max-w-full">
                <Turnstile
                  ref={turnstileRef}
                  siteKey={TURNSTILE_SITE_KEY}
                  theme="auto"
                  onSuccess={setTurnstileToken}
                  onExpire={() => setTurnstileToken(null)}
                  onError={() => setTurnstileToken(null)}
                />
              </div>
            )}

            <Button
              type="submit"
              className="w-full rounded-lg"
              size="lg"
              disabled={loading}
            >
              {loading ? (
                <>
                  <Loader2 className="size-4 animate-spin" />
                  Giriş yapılıyor...
                </>
              ) : (
                "Giriş yap"
              )}
            </Button>

            <AuthSocialButtons callbackUrl="/" disabled={loading} />
          </form>

          <p className="mt-6 text-center text-sm text-neutral-600 dark:text-neutral-400">
            Hesabınız yok mu?{" "}
            <Link
              href="/auth/register"
              className="font-medium text-blue-600 hover:underline dark:text-blue-400"
            >
              Kayıt olun
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
