"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { authClient } from "@/lib/auth/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";

export default function LoginPage() {
  const router = useRouter();
  const t = useTranslations("auth");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [unverified, setUnverified] = useState(false);
  const [resending, setResending] = useState(false);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setUnverified(false);
    setLoading(true);
    const { error } = await authClient.signIn.email({ email, password, callbackURL: "/recipes" });
    setLoading(false);
    if (error) {
      if (error.code === "EMAIL_NOT_VERIFIED") {
        setUnverified(true);
      } else {
        toast.error(error.message ?? "Sign in failed");
      }
    } else {
      router.push("/recipes");
    }
  }

  async function resendVerification() {
    setResending(true);
    const { error } = await authClient.sendVerificationEmail({
      email,
      callbackURL: "/recipes",
    });
    setResending(false);
    if (error) {
      toast.error(error.message ?? "Failed to resend");
    } else {
      toast.success("Verification email sent — check your inbox");
      setUnverified(false);
    }
  }

  async function handleGoogle() {
    await authClient.signIn.social({ provider: "google", callbackURL: "/recipes" });
  }

  return (
    <Card>
      <CardHeader className="space-y-1">
        <CardTitle className="text-2xl font-semibold tracking-tight">Epicure</CardTitle>
        <CardDescription>{t("signInTitle")}</CardDescription>
      </CardHeader>
      <form onSubmit={handleSubmit}>
        <CardContent className="space-y-4">
          <Button variant="outline" className="w-full" type="button" onClick={handleGoogle}>
            {t("continueWithGoogle")}
          </Button>
          <div className="flex items-center gap-2">
            <Separator className="flex-1" />
            <span className="text-xs text-muted-foreground">{t("or")}</span>
            <Separator className="flex-1" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">{t("email")}</Label>
            <Input id="email" type="email" placeholder={t("emailPlaceholder")} value={email} onChange={(e) => { setEmail(e.target.value); setUnverified(false); }} required />
          </div>
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <Label htmlFor="password">{t("password")}</Label>
              <Link href="/forgot-password" className="text-xs text-muted-foreground underline underline-offset-4 hover:text-foreground">
                {t("forgotPassword")}
              </Link>
            </div>
            <Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
          </div>

          {unverified && (
            <div className="rounded-lg border border-amber-200 bg-amber-50 dark:border-amber-900 dark:bg-amber-950/30 px-4 py-3 space-y-2">
              <p className="text-sm text-amber-800 dark:text-amber-300 font-medium">{t("emailNotVerified")}</p>
              <p className="text-xs text-amber-700 dark:text-amber-400">{t("checkInboxVerification")}</p>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={resendVerification}
                disabled={resending}
                className="border-amber-300 dark:border-amber-700"
              >
                {resending ? t("resendingSending") : t("resendVerification")}
              </Button>
            </div>
          )}

          <Button className="w-full" type="submit" disabled={loading}>
            {loading ? t("signInLoading") : t("signIn")}
          </Button>
        </CardContent>
      </form>
      <CardFooter className="flex justify-center">
        <p className="text-sm text-muted-foreground">
          {t("noAccount")}{" "}
          <Link href="/signup" className="underline underline-offset-4 hover:text-foreground">{t("signUp")}</Link>
        </p>
      </CardFooter>
    </Card>
  );
}
