import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { z } from "zod";
import { toast } from "sonner";
import logoUrl from "@/assets/flexflares-logo.png";

import { supabase } from "@/integrations/supabase/client";
import { lovable } from "@/integrations/lovable";
import { signInWithIdentifier } from "@/lib/auth.functions";
import { Link } from "@tanstack/react-router";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";

type Mode = "login" | "register" | "forgot";

export const Route = createFileRoute("/auth")({
  validateSearch: (search: Record<string, unknown>) => ({
    mode: (search.mode as Mode) ?? "login",
    ref: typeof search.ref === "string" ? search.ref : undefined,
  }),
  head: () => ({
    meta: [
      { title: "Sign in — Flexflares Cyber Services" },
      { name: "description", content: "Log in or create an account to access your dashboard." },
    ],
  }),
  component: AuthPage,
});

const registerSchema = z.object({
  fullName: z.string().trim().min(2, "Enter your full name").max(100),
  username: z.string().trim().min(3, "Username must be 3+ chars").max(30).regex(/^[a-zA-Z0-9_.]+$/, "Only letters, numbers, . or _"),
  email: z.string().trim().email("Invalid email").max(255),
  phone: z.string().trim().min(7, "Enter your phone").max(20),
  password: z.string().min(6, "Password must be 6+ characters").max(72),
  confirm: z.string(),
  referral: z.string().trim().max(20).optional(),
}).refine((d) => d.password === d.confirm, { message: "Passwords do not match", path: ["confirm"] });

function AuthPage() {
  const search = Route.useSearch();
  const navigate = useNavigate();
  const [mode, setMode] = useState<Mode>(search.mode);
  const [pending, setPending] = useState(false);

  useEffect(() => setMode(search.mode), [search.mode]);

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      if (data.session) navigate({ to: "/dashboard" });
    });
  }, [navigate]);

  const google = async () => {
    setPending(true);
    const res = await lovable.auth.signInWithOAuth("google", { redirect_uri: window.location.origin });
    if (res.error) {
      toast.error(res.error.message ?? "Google sign-in failed");
      setPending(false);
      return;
    }
    if (res.redirected) return;
    navigate({ to: "/dashboard" });
  };

  const login = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const identifier = String(fd.get("identifier") ?? "").trim();
    const password = String(fd.get("password") ?? "");
    if (!identifier || !password) return toast.error("Enter your credentials");
    setPending(true);
    // Accepts a username OR an email; resolution happens server-side.
    const res = await signInWithIdentifier({ data: { identifier, password } });
    if (res.error || !res.session) {
      setPending(false);
      return toast.error(res.error ?? "Invalid login credentials");
    }
    const { error } = await supabase.auth.setSession(res.session);
    setPending(false);
    if (error) return toast.error(error.message);
    toast.success("Welcome back!");
    navigate({ to: "/dashboard" });
  };

  const register = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const parsed = registerSchema.safeParse({
      fullName: fd.get("fullName"),
      username: fd.get("username"),
      email: fd.get("email"),
      phone: fd.get("phone"),
      password: fd.get("password"),
      confirm: fd.get("confirm"),
      referral: fd.get("referral"),
    });
    if (!parsed.success) return toast.error(parsed.error.issues[0]?.message ?? "Please check the form");
    setPending(true);
    const { error } = await supabase.auth.signUp({
      email: parsed.data.email,
      password: parsed.data.password,
      options: {
        emailRedirectTo: `${window.location.origin}/dashboard`,
        data: {
          full_name: parsed.data.fullName,
          username: parsed.data.username,
          phone: parsed.data.phone,
          referral_code: parsed.data.referral?.toUpperCase() || null,
        },
      },
    });
    setPending(false);
    if (error) return toast.error(error.message);
    toast.success("Account created! You can log in now.");
    setMode("login");
  };

  const forgot = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    const email = String(fd.get("email") ?? "").trim();
    if (!email) return toast.error("Enter your email");
    setPending(true);
    const { error } = await supabase.auth.resetPasswordForEmail(email, {
      redirectTo: `${window.location.origin}/reset-password`,
    });
    setPending(false);
    if (error) return toast.error(error.message);
    toast.success("Password reset email sent");
    setMode("login");
  };

  return (
    <div className="relative flex min-h-screen items-center justify-center overflow-hidden px-4 py-10">
      <div aria-hidden className="pointer-events-none absolute inset-0 -z-10" style={{ backgroundImage: "var(--gradient-glow)" }} />

      <div className="w-full max-w-md">
        <a href="/" className="mb-6 flex items-center justify-center gap-2">
          <img src={logoUrl} alt="Flexflares Cyber Services logo" width={40} height={40} className="h-10 w-10 object-contain" />
          <span className="text-lg font-bold">Flexflares Cyber</span>
        </a>

        <Card className="glass border-0 shadow-elegant">
          <CardContent className="p-6 sm:p-8">
            <Tabs value={mode === "forgot" ? "login" : mode} onValueChange={(v) => setMode(v as Mode)}>
              <TabsList className="grid w-full grid-cols-2">
                <TabsTrigger value="login">Login</TabsTrigger>
                <TabsTrigger value="register">Register</TabsTrigger>
              </TabsList>

              <TabsContent value="login" className="mt-6">
                {mode !== "forgot" ? (
                  <form onSubmit={login} className="space-y-4">
                    <div>
                      <Label htmlFor="identifier">Username or email</Label>
                      <Input id="identifier" name="identifier" type="text" required autoComplete="username" placeholder="username or you@example.com" className="mt-1" />
                    </div>
                    <div>
                      <Label htmlFor="password">Password</Label>
                      <Input id="password" name="password" type="password" required autoComplete="current-password" className="mt-1" />
                    </div>
                    <div className="flex items-center justify-between text-sm">
                      <label className="flex items-center gap-2">
                        <Checkbox id="remember" defaultChecked /> <span>Remember me</span>
                      </label>
                      <button type="button" onClick={() => setMode("forgot")} className="text-primary hover:underline">
                        Forgot password?
                      </button>
                    </div>
                    <Button type="submit" disabled={pending} className="w-full shadow-glow" size="lg">
                      {pending ? "Signing in…" : "Login"}
                    </Button>
                  </form>
                ) : (
                  <form onSubmit={forgot} className="space-y-4">
                    <div>
                      <Label htmlFor="fEmail">Email</Label>
                      <Input id="fEmail" name="email" type="email" required className="mt-1" />
                    </div>
                    <Button type="submit" disabled={pending} className="w-full" size="lg">
                      {pending ? "Sending…" : "Send reset link"}
                    </Button>
                    <button type="button" onClick={() => setMode("login")} className="w-full text-center text-sm text-muted-foreground hover:text-primary">
                      Back to login
                    </button>
                  </form>
                )}

                <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>
                <Button type="button" variant="outline" className="w-full" onClick={google} disabled={pending}>
                  <svg className="mr-2 h-4 w-4" viewBox="0 0 48 48" aria-hidden><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.5l6.7-6.7C35.6 2.4 30.2 0 24 0 14.6 0 6.5 5.4 2.6 13.3l7.8 6C12.4 13.3 17.7 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4.1 7.1-10.1 7.1-17.5z"/><path fill="#FBBC05" d="M10.4 28.7A14.5 14.5 0 0 1 9.5 24c0-1.6.3-3.2.8-4.7l-7.8-6A24 24 0 0 0 0 24c0 3.9.9 7.5 2.6 10.7l7.8-6z"/><path fill="#34A853" d="M24 48c6.5 0 11.9-2.1 15.8-5.8l-7.5-5.8c-2.1 1.4-4.8 2.3-8.3 2.3-6.3 0-11.6-3.8-13.6-9.2l-7.8 6C6.5 42.6 14.6 48 24 48z"/></svg>
                  Continue with Google
                </Button>
              </TabsContent>

              <TabsContent value="register" className="mt-6">
                <form onSubmit={register} className="space-y-3">
                  <div>
                    <Label htmlFor="fullName">Full name</Label>
                    <Input id="fullName" name="fullName" required className="mt-1" />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <Label htmlFor="username">Username</Label>
                      <Input id="username" name="username" required className="mt-1" />
                    </div>
                    <div>
                      <Label htmlFor="phone">Phone</Label>
                      <Input id="phone" name="phone" type="tel" required className="mt-1" />
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="rEmail">Email</Label>
                    <Input id="rEmail" name="email" type="email" required className="mt-1" />
                  </div>
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <Label htmlFor="rPassword">Password</Label>
                      <Input id="rPassword" name="password" type="password" required className="mt-1" />
                    </div>
                    <div>
                      <Label htmlFor="confirm">Confirm</Label>
                      <Input id="confirm" name="confirm" type="password" required className="mt-1" />
                    </div>
                  </div>
                  <div>
                    <Label htmlFor="referral">Referral code (optional)</Label>
                    <Input id="referral" name="referral" defaultValue={search.ref ?? ""} placeholder="Have a code? Enter it to earn 100 points." className="mt-1 uppercase" />
                  </div>
                  <Button type="submit" disabled={pending} className="mt-2 w-full shadow-glow" size="lg">
                    {pending ? "Creating…" : "Create account"}
                  </Button>
                </form>
                <div className="my-5 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>
                <Button type="button" variant="outline" className="w-full" onClick={google} disabled={pending}>
                  <svg className="mr-2 h-4 w-4" viewBox="0 0 48 48" aria-hidden><path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.5l6.7-6.7C35.6 2.4 30.2 0 24 0 14.6 0 6.5 5.4 2.6 13.3l7.8 6C12.4 13.3 17.7 9.5 24 9.5z"/><path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.5 5.8c4.4-4.1 7.1-10.1 7.1-17.5z"/><path fill="#FBBC05" d="M10.4 28.7A14.5 14.5 0 0 1 9.5 24c0-1.6.3-3.2.8-4.7l-7.8-6A24 24 0 0 0 0 24c0 3.9.9 7.5 2.6 10.7l7.8-6z"/><path fill="#34A853" d="M24 48c6.5 0 11.9-2.1 15.8-5.8l-7.5-5.8c-2.1 1.4-4.8 2.3-8.3 2.3-6.3 0-11.6-3.8-13.6-9.2l-7.8 6C6.5 42.6 14.6 48 24 48z"/></svg>
                  Continue with Google
                </Button>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>

        <p className="mt-6 text-center text-xs text-muted-foreground">
          By continuing you agree to our Terms and Privacy Policy.
        </p>

        <div className="mt-4 flex justify-center">
          <Link
            to="/admin-login"
            aria-label="Administrator sign in"
            title="Administrator"
            className="grid h-8 w-8 place-items-center rounded-md border border-border/60 text-xs font-bold text-muted-foreground transition-colors hover:border-primary hover:text-primary"
          >
            A
          </Link>
        </div>
      </div>
    </div>
  );
}