import { useEffect, useState } from "react";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { toast } from "sonner";
import { supabase } from "@/integrations/supabase/client";
import { lovable } from "@/integrations/lovable/index";
import { useAuth } from "@/hooks/useAuth";
import { Wordmark } from "@/components/site-chrome";

export const Route = createFileRoute("/auth")({
  head: () => ({
    meta: [
      { title: "Sign in to Imisi" },
      { name: "description", content: "Create your Imisi account and start your personal style consultation." },
      { property: "og:title", content: "Sign in to Imisi" },
      { property: "og:description", content: "Create your Imisi account and start your personal style consultation." },
    ],
  }),
  component: AuthPage,
});

type Mode = "signin" | "signup" | "reset";

function AuthPage() {
  const navigate = useNavigate();
  const { session, loading } = useAuth();
  const [mode, setMode] = useState<Mode>("signup");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!loading && session) navigate({ to: "/onboarding" });
  }, [loading, session, navigate]);

  const submit = async (event: React.FormEvent) => {
    event.preventDefault();
    setBusy(true);
    try {
      if (mode === "reset") {
        const { error } = await supabase.auth.resetPasswordForEmail(email, {
          redirectTo: `${window.location.origin}/auth`,
        });
        if (error) throw error;
        toast.success("Check your inbox for a reset link.");
        setMode("signin");
        return;
      }
      if (mode === "signup") {
        const { error } = await supabase.auth.signUp({
          email,
          password,
          options: { emailRedirectTo: `${window.location.origin}/onboarding` },
        });
        if (error) throw error;
        toast.success("Welcome to Imisi. Let's get to know you.");
        navigate({ to: "/onboarding" });
        return;
      }
      const { error } = await supabase.auth.signInWithPassword({ email, password });
      if (error) throw error;
      navigate({ to: "/onboarding" });
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Something went wrong.");
    } finally {
      setBusy(false);
    }
  };

  const google = async () => {
    const result = await lovable.auth.signInWithOAuth("google", {
      redirect_uri: window.location.origin,
    });
    if (result.error) {
      toast.error("Google sign-in didn't complete. Please try again.");
      return;
    }
    if (result.redirected) return;
    navigate({ to: "/onboarding" });
  };

  return (
    <div className="flex min-h-screen flex-col items-center justify-center px-5 py-16">
      <Wordmark className="mb-10" />
      <div className="paper w-full max-w-md p-9 rise">
        <p className="eyebrow">{mode === "reset" ? "Reset password" : mode === "signup" ? "Create account" : "Welcome back"}</p>
        <h1 className="mt-3 text-3xl">
          {mode === "reset"
            ? "Let's get you back in"
            : mode === "signup"
              ? "Let's discover your style"
              : "Continue your style journey"}
        </h1>

        <form onSubmit={submit} className="mt-7 space-y-4">
          <div>
            <label htmlFor="email" className="text-xs text-muted-foreground">
              Email
            </label>
            <input
              id="email"
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="mt-1.5 w-full rounded-md border border-input bg-background px-4 py-3 text-sm outline-none focus:border-clay"
              placeholder="you@example.com"
            />
          </div>
          {mode !== "reset" && (
            <div>
              <label htmlFor="password" className="text-xs text-muted-foreground">
                Password
              </label>
              <input
                id="password"
                type="password"
                required
                minLength={6}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="mt-1.5 w-full rounded-md border border-input bg-background px-4 py-3 text-sm outline-none focus:border-clay"
                placeholder="••••••••"
              />
            </div>
          )}
          <button
            type="submit"
            disabled={busy}
            className="w-full rounded-md bg-clay px-6 py-3.5 text-sm font-medium text-clay-foreground transition-opacity hover:opacity-90 disabled:opacity-50"
          >
            {busy ? "One moment…" : mode === "reset" ? "Send reset link" : mode === "signup" ? "Create account" : "Sign in"}
          </button>
        </form>

        {mode !== "reset" && (
          <>
            <div className="my-6 flex items-center gap-3 text-xs text-muted-foreground">
              <span className="h-px flex-1 bg-border" /> or <span className="h-px flex-1 bg-border" />
            </div>
            <button
              onClick={google}
              className="w-full rounded-md border border-input bg-background px-6 py-3.5 text-sm font-medium transition-colors hover:bg-secondary"
            >
              Continue with Google
            </button>
          </>
        )}

        <div className="mt-7 space-y-2 text-center text-xs text-muted-foreground">
          {mode === "signin" && (
            <>
              <button onClick={() => setMode("signup")} className="underline underline-offset-4">
                New to Imisi? Create an account
              </button>
              <br />
              <button onClick={() => setMode("reset")} className="underline underline-offset-4">
                Forgot your password?
              </button>
            </>
          )}
          {mode === "signup" && (
            <button onClick={() => setMode("signin")} className="underline underline-offset-4">
              Already have an account? Sign in
            </button>
          )}
          {mode === "reset" && (
            <button onClick={() => setMode("signin")} className="underline underline-offset-4">
              Back to sign in
            </button>
          )}
        </div>
      </div>
    </div>
  );
}
