import { useState } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { 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 { signup, type AuthPlatform } from "@/lib/auth";

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

export function SignupPage({ platform, redirectTo = "/" }: SignupPageProps) {
  const navigate = useNavigate();
  const [name, setName] = useState("");
  const [company, setCompany] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);

  const isFirm = platform === "firm";

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

    if (password !== confirmPassword) {
      toast.error("Passwords do not match");
      return;
    }

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

    const result = await signup(platform, { name, email, password, company });
    if (result.ok) {
      toast.success("Account created — welcome!");
      navigate({ to: redirectTo });
      return;
    }

    toast.error(result.error);
    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}
          <h1 className="mt-6 font-display text-[22px] font-semibold text-foreground">
            {isFirm ? "Create your account" : "Get started"}
          </h1>
          <p className="mt-2 text-[14px] leading-relaxed text-muted-foreground">
            {isFirm
              ? "Join the firm workspace to manage clients, approvals and SnelStart sync."
              : "Create your account to send documents to your accountant and track everything in one place."}
          </p>
        </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="name">Full name</Label>
              <Input
                id="name"
                type="text"
                autoComplete="name"
                placeholder="Jane Doe"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="company">{isFirm ? "Firm name" : "Company name"}</Label>
              <Input
                id="company"
                type="text"
                autoComplete="organization"
                placeholder={isFirm ? "Amanah Accountants" : "Your company"}
                value={company}
                onChange={(e) => setCompany(e.target.value)}
              />
            </div>

            <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">
              <Label htmlFor="password">Password</Label>
              <div className="relative">
                <Input
                  id="password"
                  type={showPassword ? "text" : "password"}
                  autoComplete="new-password"
                  placeholder="At least 8 characters"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="pr-10"
                  minLength={8}
                  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 className="space-y-2">
              <Label htmlFor="confirmPassword">Confirm password</Label>
              <Input
                id="confirmPassword"
                type={showPassword ? "text" : "password"}
                autoComplete="new-password"
                placeholder="Repeat your password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                minLength={8}
                required
              />
            </div>
          </div>

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

          <p className="mt-4 text-center text-[13px] text-muted-foreground">
            Already have an account?{" "}
            <Link to="/login" className="font-semibold text-primary hover:underline">
              Sign in
            </Link>
          </p>
        </form>
      </div>
    </div>
  );
}
