import { useMemo, useState } from "react";
import { Link, useNavigate, useRouterState } from "@tanstack/react-router";
import { CheckCircle2, Eye, EyeOff, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { AmanahMark } from "@/components/brand/AmanahMark";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { login, type AuthPlatform } from "@/lib/auth";

interface LoginPageProps {
  platform: AuthPlatform;
  redirectTo?: string;
}

export function LoginPage({ platform, redirectTo = "/" }: LoginPageProps) {
  const navigate = useNavigate();
  const searchStr = useRouterState({ select: (s) => s.location.searchStr });
  const passwordUpdated = useMemo(
    () => new URLSearchParams(searchStr).get("reset") === "success",
    [searchStr],
  );

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showLoginForm, setShowLoginForm] = useState(!passwordUpdated);

  const isFirm = platform === "firm";

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    await new Promise((r) => setTimeout(r, 400));

    if (await login(platform, email, password)) {
      toast.success("Signed in successfully");
      navigate({ to: redirectTo });
      return;
    }

    toast.error("Invalid email or password");
    setLoading(false);
  };

  return (
    <div
      className={
        isFirm
          ? "flex min-h-screen items-center justify-center bg-background px-4 py-12"
          : "client-portal flex min-h-screen items-center justify-center px-4 py-12"
      }
    >
      <div className="w-full max-w-[420px]">
        <div className="mb-8 text-center">
          <AmanahMark size={56} className="mx-auto mb-5 shadow-[0_1px_3px_rgba(40,56,80,0.18)]" />
          <p className="font-display text-[26px] font-bold leading-none tracking-[0.1em] text-primary uppercase">
            Amanah
          </p>
          <p className="mt-2 text-[13px] font-medium text-brand">
            {isFirm ? "Boekhouding & Belastingadvies" : "Your documents, made simple"}
          </p>
          {isFirm ? (
            <p className="mt-3 inline-flex rounded-full bg-primary-soft px-2.5 py-0.5 text-[10px] font-bold tracking-[0.18em] text-primary uppercase">
              Firm
            </p>
          ) : null}
        </div>

        {passwordUpdated && !showLoginForm ? (
          <div className="rounded-xl border border-brand/30 bg-surface p-6 text-center shadow-[0_1px_2px_rgba(40,56,80,0.05)]">
            <span className="mx-auto mb-4 flex size-14 items-center justify-center rounded-full bg-brand-soft text-brand">
              <CheckCircle2 size={28} aria-hidden="true" />
            </span>
            <h1 className="font-display text-[22px] font-semibold text-foreground">
              Password updated
            </h1>
            <p className="mt-2 text-[14px] leading-relaxed text-muted-foreground">
              Your password has been changed successfully. Sign in with your new password to
              continue.
            </p>
            <Button
              type="button"
              className="mt-6 w-full"
              onClick={() => {
                setShowLoginForm(true);
                void navigate({ to: "/login", search: { reset: undefined }, replace: true });
              }}
            >
              Continue to sign in
            </Button>
          </div>
        ) : (
          <>
            <div className="mb-8 text-center">
              <h1 className="font-display text-[22px] font-semibold text-foreground">
                {isFirm ? "Sign in to your workspace" : "Welcome back"}
              </h1>
              <p className="mt-2 text-[14px] leading-relaxed text-muted-foreground">
                {isFirm
                  ? "Access clients, document processing, approvals and SnelStart syncing."
                  : "Sign in to upload documents, see their status, and reply to your accountant."}
              </p>
            </div>

            {passwordUpdated && (
              <div className="mb-4 flex items-start gap-2.5 rounded-lg border border-brand/30 bg-brand-soft px-3 py-2.5 text-left text-[13px] text-brand-foreground">
                <CheckCircle2 size={16} className="mt-0.5 shrink-0" aria-hidden="true" />
                <span>Password updated successfully. Please sign in with your new password.</span>
              </div>
            )}

            <form
              onSubmit={handleSubmit}
              className="rounded-xl border border-border bg-surface p-6 shadow-[0_1px_2px_rgba(40,56,80,0.05)]"
            >
              <div className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="email">Email</Label>
                  <Input
                    id="email"
                    type="email"
                    autoComplete="email"
                    placeholder="you@example.com"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <div className="flex items-center justify-between gap-2">
                    <Label htmlFor="password">Password</Label>
                    <Link
                      to="/forgot-password"
                      className="text-[12px] font-medium text-primary hover:underline"
                    >
                      Forgot password?
                    </Link>
                  </div>
                  <div className="relative">
                    <Input
                      id="password"
                      type={showPassword ? "text" : "password"}
                      autoComplete="current-password"
                      placeholder="Enter your password"
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      className="pr-10"
                      required
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword((v) => !v)}
                      className="absolute top-1/2 right-2.5 -translate-y-1/2 rounded-md p-1 text-muted-foreground transition-colors hover:text-foreground"
                      aria-label={showPassword ? "Hide password" : "Show password"}
                    >
                      {showPassword ? (
                        <EyeOff size={16} aria-hidden="true" />
                      ) : (
                        <Eye size={16} aria-hidden="true" />
                      )}
                    </button>
                  </div>
                </div>
              </div>

              <Button type="submit" className="mt-6 w-full" disabled={loading}>
                {loading ? (
                  <>
                    <Loader2 className="animate-spin" size={16} aria-hidden="true" />
                    Signing in…
                  </>
                ) : (
                  "Sign in"
                )}
              </Button>

              <p className="mt-4 text-center text-[13px] text-muted-foreground">
                New here?{" "}
                <Link to="/signup" className="font-semibold text-primary hover:underline">
                  Create an account
                </Link>
              </p>
            </form>
          </>
        )}
      </div>
    </div>
  );
}
