import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { toast } from "sonner";
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 {
  Loader2,
  Mail,
  Lock,
  Eye,
  EyeOff,
  ArrowRight,
  User,
  ShieldCheck,
  Globe,
  BarChart3,
  Megaphone,
  PenSquare,
  ThumbsUp,
  Target,
  Palette,
  TrendingUp,
  MoreHorizontal,
  Play,
} from "lucide-react";

export const Route = createFileRoute("/auth")({
  head: () => ({
    meta: [
      { title: "Sign in | Studio 360 ERP" },
      {
        name: "description",
        content:
          "Log in to Studio 360 to manage invoices, accounting, bookings, payroll and profit distribution in one workspace.",
      },
      { property: "og:title", content: "Sign in | Studio 360 ERP" },
      { property: "og:description", content: "One brand. Every angle. Access your studio accounting workspace." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: AuthPage,
});

const capabilities = [
  { icon: Megaphone, label: "Digital\nMarketing" },
  { icon: PenSquare, label: "Content\nCreation" },
  { icon: ThumbsUp, label: "Social\nMedia" },
  { icon: Target, label: "Brand\nStrategy" },
  { icon: Palette, label: "Design &\nBranding" },
  { icon: TrendingUp, label: "Analytics &\nGrowth" },
  { icon: MoreHorizontal, label: "And Many\nMore" },
];

const trustPoints = [
  { icon: ShieldCheck, title: "Secure", body: "Your data is protected with top security." },
  { icon: Globe, title: "Reliable", body: "Built for performance and reliability." },
  { icon: BarChart3, title: "Result Driven", body: "We focus on what drives real results." },
];

function AuthPage() {
  const navigate = useNavigate();
  const [mode, setMode] = useState<"signin" | "signup">("signin");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [fullName, setFullName] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [busy, setBusy] = useState(false);

  /** Client portal logins land on the portal, staff land on the dashboard. */
  async function goToWorkspace() {
    const { data } = await supabase
      .from("customer_portal_users")
      .select("id")
      .eq("is_active", true)
      .limit(1);
    if (data && data.length > 0) {
      navigate({ to: "/portal" });
      return;
    }
    navigate({ to: "/dashboard" });
  }

  useEffect(() => {
    supabase.auth.getSession().then(({ data }) => {
      if (data.session) void goToWorkspace();
    });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [navigate]);

  async function signIn(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    const { error } = await supabase.auth.signInWithPassword({ email, password });
    setBusy(false);
    if (error) {
      toast.error(error.message);
      return;
    }
    await goToWorkspace();
  }

  async function signUp(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    const { error } = await supabase.auth.signUp({
      email,
      password,
      options: {
        data: { full_name: fullName },
        emailRedirectTo: `${window.location.origin}/dashboard`,
      },
    });
    setBusy(false);
    if (error) {
      toast.error(error.message);
      return;
    }
    toast.success("Account created. You can sign in now.");
    setMode("signin");
  }

  async function google() {
    const result = await lovable.auth.signInWithOAuth("google", {
      redirect_uri: window.location.origin,
    });
    if (result.error) {
      toast.error("Google sign-in failed");
      return;
    }
    if (result.redirected) return;
    navigate({ to: "/dashboard" });
  }

  const isSignUp = mode === "signup";

  return (
    <main className="min-h-screen bg-muted p-0 md:p-6 lg:p-10">
      <div className="mx-auto flex min-h-screen w-full max-w-6xl flex-col overflow-hidden bg-card shadow-panel md:min-h-0 md:rounded-3xl">
        <div className="grid flex-1 lg:grid-cols-[1.05fr_1fr]">
          {/* Brand panel */}
          <section className="brand-panel relative overflow-hidden px-8 py-12 md:px-12 lg:py-16">
            <div
              aria-hidden
              className="pointer-events-none absolute -right-40 top-[-18%] size-[38rem] rounded-full border-[3rem] border-primary-foreground/10"
            />
            <div
              aria-hidden
              className="pointer-events-none absolute -left-24 bottom-[-25%] size-[26rem] rounded-full bg-primary-foreground/5"
            />

            <div className="relative">
              <div className="flex items-start gap-1">
                <h1 className="text-5xl font-extrabold tracking-tight md:text-6xl">Studio</h1>
                <span className="mt-3 inline-flex size-9 items-center justify-center rounded-full bg-primary-foreground/15 md:mt-4">
                  <Play className="size-4 fill-current" />
                </span>
                <span className="mt-1 text-sm font-semibold">360°</span>
              </div>
              <p className="mt-1 text-sm text-primary-foreground/75">your one stop studio management solution.</p>

              <div className="mt-10 space-y-1 text-3xl font-bold leading-tight md:text-4xl">
                <p>One Brand.</p>
                <p>Every Angle.</p>
                <p className="brand-yellow">Endless Impact.</p>
              </div>
              <p className="mt-4 max-w-sm text-sm text-primary-foreground/80">
                From bookings to the balance sheet, we cover every angle of your studio business.
              </p>

              <ul className="mt-10 grid max-w-md grid-cols-4 gap-x-4 gap-y-7">
                {capabilities.map(({ icon: Icon, label }) => (
                  <li key={label} className="flex flex-col items-center gap-2 text-center">
                    <span className="flex size-12 items-center justify-center rounded-full border border-primary-foreground/25 bg-primary-foreground/10">
                      <Icon className="size-5" />
                    </span>
                    <span className="whitespace-pre-line text-[0.7rem] font-semibold leading-tight text-primary-foreground/90">
                      {label}
                    </span>
                  </li>
                ))}
              </ul>
            </div>
          </section>

          {/* Form panel */}
          <section className="flex items-center justify-center px-6 py-12 md:px-12">
            <div className="w-full max-w-sm">
              <h2 className="text-center text-2xl font-bold">
                {isSignUp ? (
                  <>
                    Create <span className="text-primary">Account</span>
                  </>
                ) : (
                  <>
                    Welcome <span className="text-primary">Back!</span>
                  </>
                )}
              </h2>
              <div className="mx-auto mt-2 h-0.5 w-10 rounded-full bg-primary" />
              <p className="mt-4 text-center text-sm text-muted-foreground">
                {isSignUp
                  ? "Set up your Studio 360 workspace and start managing every angle."
                  : "Log in to your Studio 360 account and continue your journey."}
              </p>

              <form onSubmit={isSignUp ? signUp : signIn} className="mt-7 space-y-4">
                {isSignUp && (
                  <div className="space-y-1.5">
                    <Label htmlFor="name" className="text-xs font-semibold">
                      Full Name
                    </Label>
                    <div className="relative">
                      <User className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                      <Input
                        id="name"
                        placeholder="Enter your name"
                        value={fullName}
                        onChange={(e) => setFullName(e.target.value)}
                        className="h-11 bg-muted/60 pl-10"
                      />
                    </div>
                  </div>
                )}

                <div className="space-y-1.5">
                  <Label htmlFor="email" className="text-xs font-semibold">
                    Email Address
                  </Label>
                  <div className="relative">
                    <Mail className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                    <Input
                      id="email"
                      type="email"
                      required
                      placeholder="Enter your email"
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="h-11 bg-muted/60 pl-10"
                    />
                  </div>
                </div>

                <div className="space-y-1.5">
                  <Label htmlFor="password" className="text-xs font-semibold">
                    Password
                  </Label>
                  <div className="relative">
                    <Lock className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      required
                      minLength={isSignUp ? 6 : undefined}
                      placeholder="Enter your password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="h-11 bg-muted/60 px-10"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword((v) => !v)}
                      aria-label={showPassword ? "Hide password" : "Show password"}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground transition-colors hover:text-foreground"
                    >
                      {showPassword ? <EyeOff className="size-4" /> : <Eye className="size-4" />}
                    </button>
                  </div>
                </div>

                {!isSignUp && (
                  <div className="text-right">
                    <button type="button" className="text-xs font-semibold text-primary hover:underline">
                      Forgot Password?
                    </button>
                  </div>
                )}

                <Button type="submit" disabled={busy} className="h-12 w-full justify-between rounded-lg text-base font-semibold">
                  <span className="flex items-center gap-2">
                    {busy && <Loader2 className="size-4 animate-spin" />}
                    {isSignUp ? "Create Account" : "Login"}
                  </span>
                  <ArrowRight className="size-4" />
                </Button>
              </form>

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

              <Button variant="outline" onClick={google} className="h-12 w-full justify-center gap-3 rounded-lg font-medium">
                <GoogleMark />
                Continue with Google
              </Button>

              <p className="mt-6 text-center text-sm text-muted-foreground">
                {isSignUp ? "Already have an account?" : "Don't have an account?"}{" "}
                <button
                  type="button"
                  onClick={() => setMode(isSignUp ? "signin" : "signup")}
                  className="font-semibold text-primary hover:underline"
                >
                  {isSignUp ? "Log in" : "Sign Up"}
                </button>
              </p>
            </div>
          </section>
        </div>

        {/* Trust bar */}
        <footer className="grid gap-6 border-t border-border bg-secondary/60 px-8 py-6 md:grid-cols-4 md:px-12">
          {trustPoints.map(({ icon: Icon, title, body }) => (
            <div key={title} className="flex items-start gap-3">
              <span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground">
                <Icon className="size-4" />
              </span>
              <div>
                <p className="text-sm font-semibold">{title}</p>
                <p className="text-xs text-muted-foreground">{body}</p>
              </div>
            </div>
          ))}
          <div className="self-center text-xs text-muted-foreground md:text-right">
            <p>
              Client?{" "}
              <Link to="/portal" className="font-semibold text-primary hover:underline">
                Open the client portal
              </Link>
            </p>
            <p className="mt-1">© {new Date().getFullYear()} Studio 360°. All rights reserved.</p>
            <p className="mt-1">Developed by FOYSAL AHASAN</p>
          </div>
        </footer>
      </div>
    </main>
  );
}

function GoogleMark() {
  return (
    <svg viewBox="0 0 24 24" className="size-4" aria-hidden>
      <path
        fill="#4285F4"
        d="M23.5 12.3c0-.8-.1-1.6-.2-2.3H12v4.5h6.4a5.5 5.5 0 0 1-2.4 3.6v3h3.9c2.3-2.1 3.6-5.2 3.6-8.8Z"
      />
      <path
        fill="#34A853"
        d="M12 24c3.2 0 5.9-1.1 7.9-2.9l-3.9-3c-1.1.7-2.4 1.1-4 1.1a7 7 0 0 1-6.6-4.8H1.4v3.1A12 12 0 0 0 12 24Z"
      />
      <path fill="#FBBC05" d="M5.4 14.4a7.2 7.2 0 0 1 0-4.6V6.7H1.4a12 12 0 0 0 0 10.8l4-3.1Z" />
      <path
        fill="#EA4335"
        d="M12 4.8c1.8 0 3.3.6 4.6 1.8l3.4-3.4A12 12 0 0 0 1.4 6.7l4 3.1A7 7 0 0 1 12 4.8Z"
      />
    </svg>
  );
}
