import { createFileRoute, useNavigate, Link } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { lovable } from "@/integrations/lovable/index";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { MessageSquare, Loader2 } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/auth")({
  validateSearch: (s: Record<string, unknown>): { next?: string } => ({
    next: typeof s.next === "string" && s.next.startsWith("/") && !s.next.startsWith("//") ? s.next : undefined,
  }),
  head: () => ({
    meta: [
      { title: "Sign in or create your account — Gatavase Bulky SMS" },
      { name: "description", content: "Sign in or create your Gatavase Bulky SMS account to send bulk SMS across Uganda and Africa with delivery reports and mobile money billing." },
      { property: "og:title", content: "Sign in — Gatavase Bulky SMS" },
      { property: "og:description", content: "Access your Gatavase Bulky SMS dashboard to send campaigns, manage contacts and top up credits." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
      { property: "og:url", content: "https://sms.gatavaseug.com/auth" },
      { name: "robots", content: "noindex, follow" },
    ],
    links: [{ rel: "canonical", href: "https://sms.gatavaseug.com/auth" }],
  }),
  component: AuthPage,
});

function useDestination() {
  const { next } = Route.useSearch();
  const isSafe = typeof next === "string" && next.startsWith("/") && !next.startsWith("//");
  const relative = isSafe && next ? next : "/dashboard";
  const absolute = () => window.location.origin + relative;
  return { relative, absolute };
}

function AuthPage() {
  const navigate = useNavigate();
  const dest = useDestination();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    supabase.auth.getUser().then(({ data }) => {
      if (data.user) window.location.href = dest.relative;
    });
  }, [dest.relative]);

  const handleGoogle = async () => {
    setLoading(true);
    const result = await lovable.auth.signInWithOAuth("google", { redirect_uri: dest.absolute() });
    if (result.error) { toast.error("Google sign in failed"); setLoading(false); return; }
    if (result.redirected) return;
    window.location.href = dest.relative;
  };
  void navigate;

  return (
    <div className="grid min-h-screen lg:grid-cols-2">
      <div className="relative hidden flex-col justify-between overflow-hidden bg-gradient-hero p-10 text-primary-foreground lg:flex">
        <Link to="/" className="flex items-center gap-2">
          <div className="grid h-9 w-9 place-items-center rounded-xl bg-white/15 backdrop-blur">
            <MessageSquare className="h-5 w-5" />
          </div>
          <span className="font-display text-lg font-bold">Bulky<span className="opacity-80">SMS</span></span>
        </Link>
        <div className="space-y-4">
          <h2 className="font-display text-4xl font-bold leading-tight">Send SMS to thousands of customers across Africa — in seconds.</h2>
          <p className="text-primary-foreground/80">Branded sender IDs · Mobile money billing · Real delivery reports.</p>
        </div>
        <p className="text-xs text-primary-foreground/60">© {new Date().getFullYear()} Gatavase Bulky SMS</p>
      </div>

      <div className="flex items-center justify-center p-6 sm:p-10">
        <div className="w-full max-w-md">
          <div className="lg:hidden mb-8 flex items-center gap-2">
            <div className="grid h-9 w-9 place-items-center rounded-xl bg-gradient-brand">
              <MessageSquare className="h-5 w-5 text-primary-foreground" />
            </div>
            <span className="font-display text-lg font-bold">Bulky SMS</span>
          </div>
          <h1 className="font-display text-3xl font-bold">Welcome back</h1>
          <p className="mt-1 text-sm text-muted-foreground">Sign in or create an account to start sending.</p>

          <Button onClick={handleGoogle} disabled={loading} variant="outline" className="mt-6 w-full">
            {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : (
              <svg className="mr-2 h-4 w-4" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.1c-.22-.66-.35-1.36-.35-2.1s.13-1.44.35-2.1V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l3.66-2.83z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38z"/></svg>
            )}
            Continue with Google
          </Button>

          <div className="my-6 flex items-center gap-3 text-xs text-muted-foreground">
            <div className="h-px flex-1 bg-border" /> OR <div className="h-px flex-1 bg-border" />
          </div>

          <Tabs defaultValue="signin">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="signin">Sign in</TabsTrigger>
              <TabsTrigger value="signup">Sign up</TabsTrigger>
            </TabsList>
            <TabsContent value="signin"><SignInForm dest={dest} /></TabsContent>
            <TabsContent value="signup"><SignUpForm dest={dest} /></TabsContent>
          </Tabs>
        </div>
      </div>
    </div>
  );
}

type Dest = ReturnType<typeof useDestination>;

function SignInForm({ dest }: { dest: Dest }) {
  const [loading, setLoading] = useState(false);
  return (
    <form
      className="mt-4 space-y-4"
      onSubmit={async (e) => {
        e.preventDefault();
        setLoading(true);
        const fd = new FormData(e.currentTarget);
        const { error } = await supabase.auth.signInWithPassword({
          email: String(fd.get("email")), password: String(fd.get("password")),
        });
        setLoading(false);
        if (error) return toast.error(error.message);
        toast.success("Welcome back!");
        window.location.href = dest.relative;
      }}
    >
      <div><Label htmlFor="email">Email</Label><Input id="email" name="email" type="email" required autoComplete="email" /></div>
      <div><Label htmlFor="password">Password</Label><Input id="password" name="password" type="password" required autoComplete="current-password" /></div>
      <Button type="submit" disabled={loading} className="w-full bg-gradient-brand text-primary-foreground">
        {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} Sign in
      </Button>
    </form>
  );
}

function SignUpForm({ dest }: { dest: Dest }) {
  const [loading, setLoading] = useState(false);
  return (
    <form
      className="mt-4 space-y-4"
      onSubmit={async (e) => {
        e.preventDefault();
        setLoading(true);
        const fd = new FormData(e.currentTarget);
        const { error } = await supabase.auth.signUp({
          email: String(fd.get("email")),
          password: String(fd.get("password")),
          options: {
            emailRedirectTo: dest.absolute(),
            data: {
              full_name: String(fd.get("full_name")),
              business_name: String(fd.get("business_name")),
            },
          },
        });
        setLoading(false);
        if (error) return toast.error(error.message);
        toast.success("Account created!");
        window.location.href = dest.relative;
      }}
    >
      <div className="grid grid-cols-2 gap-3">
        <div><Label htmlFor="full_name">Your name</Label><Input id="full_name" name="full_name" required /></div>
        <div><Label htmlFor="business_name">Business</Label><Input id="business_name" name="business_name" required /></div>
      </div>
      <div><Label htmlFor="su-email">Email</Label><Input id="su-email" name="email" type="email" required autoComplete="email" /></div>
      <div><Label htmlFor="su-password">Password</Label><Input id="su-password" name="password" type="password" required minLength={6} autoComplete="new-password" /></div>
      <Button type="submit" disabled={loading} className="w-full bg-gradient-brand text-primary-foreground">
        {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} Create account
      </Button>
    </form>
  );
}
