import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Zap, Loader2, Eye, EyeOff, Check } from "lucide-react";
import { useAuth } from "@/lib/auth";
import { useAppSettings } from "@/lib/app-settings";
import { toast } from "sonner";

export const Route = createFileRoute("/register")({
  head: () => ({ meta: [{ title: "Register · Delta Terminal" }] }),
  component: Register,
});

function pwScore(pw: string): { score: number; label: string; tone: string } {
  let s = 0;
  if (pw.length >= 8) s++;
  if (/[A-Z]/.test(pw)) s++;
  if (/[0-9]/.test(pw)) s++;
  if (/[^A-Za-z0-9]/.test(pw)) s++;
  if (pw.length >= 12) s++;
  const map = [
    { label: "Too short", tone: "bg-destructive" },
    { label: "Weak", tone: "bg-destructive" },
    { label: "Fair", tone: "bg-warning" },
    { label: "Good", tone: "bg-primary" },
    { label: "Strong", tone: "bg-bull" },
    { label: "Excellent", tone: "bg-bull" },
  ];
  return { score: s, ...map[s] };
}

function Register() {
  const nav = useNavigate();
  const { signUp } = useAuth();
  const settings = useAppSettings();
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [email, setEmail] = useState("");
  const [pw, setPw] = useState("");
  const [showPw, setShowPw] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const strength = pwScore(pw);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setError(null);
    try {
      await signUp(email, pw, firstName.trim(), lastName.trim());
      toast.success("Account created");
      nav({ to: "/settings" });
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Registration failed";
      setError(msg);
      toast.error(msg);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="relative grid min-h-dvh lg:grid-cols-2">
      <aside className="relative hidden overflow-hidden border-r border-border/60 lg:flex lg:flex-col lg:justify-between lg:p-10">
        <div
          aria-hidden="true"
          className="absolute inset-0 -z-10"
          style={{
            background:
              "radial-gradient(700px 400px at 20% 10%, color-mix(in oklab, var(--primary) 25%, transparent), transparent 60%), radial-gradient(600px 400px at 90% 90%, color-mix(in oklab, var(--accent) 22%, transparent), transparent 60%)",
          }}
        />
        <div className="flex items-center gap-3">
          <div className="grid h-11 w-11 place-items-center rounded-xl bg-primary text-primary-foreground shadow-lg shadow-primary/30">
            {settings.branding.logo_url ? (
              <img src={settings.branding.logo_url} alt="" className="h-8 w-8 object-contain" />
            ) : (
              <Zap className="h-6 w-6" />
            )}
          </div>
          <div className="font-display text-xl font-bold tracking-tight">{settings.branding.app_title}</div>
        </div>

        <div className="max-w-lg">
          <h1 className="font-display text-4xl font-bold leading-tight tracking-tight">
            Start trading in <span className="gradient-text">seconds</span>.
          </h1>
          <p className="mt-4 text-sm leading-relaxed text-muted-foreground">
            Paper trade, tune your algos and go live when you're ready — no credit card required.
          </p>
          <ul className="mt-8 grid gap-3 text-sm">
            {[
              "Paper-trading mode from day one",
              "Multi-algo consensus signals",
              "Encrypted API keys with region auto-detect",
              "Full audit trail of every action",
            ].map((label) => (
              <li key={label} className="flex items-start gap-3">
                <span className="mt-0.5 grid h-6 w-6 shrink-0 place-items-center rounded-full bg-primary/15 text-primary">
                  <Check className="h-3.5 w-3.5" />
                </span>
                <span className="text-foreground/90">{label}</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="text-xs text-muted-foreground">
          &copy; {new Date().getFullYear()} {settings.branding.app_title}. All rights reserved.
        </div>
      </aside>

      <main className="grid place-items-center px-4 py-10 sm:px-8">
        <Card className="glass-strong w-full max-w-md rounded-2xl p-6 sm:p-8">
          <div className="mb-6 flex items-center gap-3 lg:hidden">
            <div className="grid h-10 w-10 place-items-center rounded-xl bg-primary text-primary-foreground">
              <Zap className="h-5 w-5" />
            </div>
            <div className="font-display text-lg font-bold tracking-tight">{settings.branding.app_title}</div>
          </div>

          <div className="mb-6">
            <h2 className="font-display text-2xl font-bold tracking-tight">Create your account</h2>
            <p className="mt-1 text-sm text-muted-foreground">Free forever · start in paper mode.</p>
          </div>

          <form onSubmit={onSubmit} className="grid gap-4" noValidate>
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="grid gap-2">
                <Label htmlFor="firstName">First name</Label>
                <Input id="firstName" required autoComplete="given-name" value={firstName} onChange={(e) => setFirstName(e.target.value)} />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="lastName">Last name</Label>
                <Input id="lastName" required autoComplete="family-name" value={lastName} onChange={(e) => setLastName(e.target.value)} />
              </div>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="email">Email</Label>
              <Input id="email" type="email" required autoComplete="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@trader.io" />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="pw">Password</Label>
              <div className="relative">
                <Input
                  id="pw"
                  type={showPw ? "text" : "password"}
                  required
                  minLength={8}
                  autoComplete="new-password"
                  value={pw}
                  onChange={(e) => setPw(e.target.value)}
                  className="pr-10"
                  aria-describedby="pw-hint"
                />
                <button
                  type="button"
                  onClick={() => setShowPw((v) => !v)}
                  className="absolute inset-y-0 right-0 grid w-10 place-items-center text-muted-foreground hover:text-foreground focus-visible:text-foreground"
                  aria-label={showPw ? "Hide password" : "Show password"}
                  aria-pressed={showPw}
                >
                  {showPw ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
              {pw.length > 0 ? (
                <div className="flex items-center gap-2" aria-live="polite">
                  <div className="flex flex-1 gap-1" aria-hidden="true">
                    {[0, 1, 2, 3, 4].map((i) => (
                      <div
                        key={i}
                        className={`h-1 flex-1 rounded-full ${i < strength.score ? strength.tone : "bg-border/60"}`}
                      />
                    ))}
                  </div>
                  <span className="text-[11px] font-medium text-muted-foreground">{strength.label}</span>
                </div>
              ) : (
                <p id="pw-hint" className="text-[11px] text-muted-foreground">
                  Minimum 8 characters. Add numbers &amp; symbols for extra strength.
                </p>
              )}
            </div>

            {error && (
              <div role="alert" aria-live="polite" className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive-foreground">
                {error}
              </div>
            )}

            <Button type="submit" size="lg" className="mt-1 w-full font-bold" disabled={busy}>
              {busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}Create account
            </Button>
          </form>

          <p className="mt-6 text-center text-xs text-muted-foreground">
            Have an account?{" "}
            <Link to="/login" className="font-semibold text-primary hover:underline">
              Sign in
            </Link>
          </p>
        </Card>
      </main>
    </div>
  );
}
