import { createSignal, createMemo, Show } from "solid-js";
import { Title } from "@solidjs/meta";
import { useNavigate } from "@solidjs/router";
import { AuthLayout, PasswordInput, SocialAuthButtons } from "~/components/auth";
import { Input } from "~/components/ui";
import { Button } from "~/components/ui";
import { signup } from "~/lib/auth";

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

interface FormErrors {
  name?: string;
  email?: string;
  password?: string;
  confirmPassword?: string;
  terms?: string;
}

type StrengthLevel = "none" | "weak" | "medium" | "strong";

export default function SignupPage() {
  const navigate = useNavigate();
  const [name, setName] = createSignal("");
  const [email, setEmail] = createSignal("");
  const [password, setPassword] = createSignal("");
  const [confirmPassword, setConfirmPassword] = createSignal("");
  const [agreeTerms, setAgreeTerms] = createSignal(false);
  const [errors, setErrors] = createSignal<FormErrors>({});
  const [loading, setLoading] = createSignal(false);
  const [serverError, setServerError] = createSignal("");

  const strength = createMemo<{ level: StrengthLevel; label: string; percent: number }>(() => {
    const pwd = password();
    if (!pwd) return { level: "none", label: "", percent: 0 };
    let score = 0;
    if (pwd.length >= 8) score++;
    if (pwd.length >= 12) score++;
    if (/[a-z]/.test(pwd) && /[A-Z]/.test(pwd)) score++;
    if (/\d/.test(pwd)) score++;
    if (/[^a-zA-Z0-9]/.test(pwd)) score++;
    if (score <= 1) return { level: "weak", label: "Weak", percent: 25 };
    if (score <= 3) return { level: "medium", label: "Medium", percent: 60 };
    return { level: "strong", label: "Strong", percent: 100 };
  });

  const strengthColors: Record<string, string> = {
    weak: "bg-[var(--color-error)]",
    medium: "bg-[var(--color-warning)]",
    strong: "bg-[var(--color-success)]",
  };

  function validate(): boolean {
    const errs: FormErrors = {};
    if (!name().trim()) errs.name = "Name is required";
    if (!email().trim()) errs.email = "Email is required";
    else if (!EMAIL_REGEX.test(email())) errs.email = "Invalid email format";
    if (!password()) errs.password = "Password is required";
    else if (password().length < 8) errs.password = "Password must be at least 8 characters";
    if (password() !== confirmPassword()) errs.confirmPassword = "Passwords do not match";
    if (!agreeTerms()) errs.terms = "You must agree to the Terms of Service";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  }

  async function handleSubmit(e: Event) {
    e.preventDefault();
    setServerError("");
    if (!validate()) return;
    setLoading(true);
    try {
      await signup(name(), email(), password());
      navigate("/onboarding", { replace: true });
    } catch {
      setServerError("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthLayout>
      <Title>Create Account — ShieldAI</Title>
      <div class="flex flex-col gap-6">
        <div class="text-center">
          <h2 class="text-2xl font-bold text-[var(--color-text-primary)]">
            Create your account
          </h2>
          <p class="text-sm text-[var(--color-text-secondary)] mt-1">
            Start protecting your identity
          </p>
        </div>

        <Show when={serverError()}>
          <div
            class="px-4 py-3 rounded-lg text-sm bg-[var(--color-error-bg)] text-[var(--color-error)] border border-[var(--color-error)]/30"
            role="alert"
          >
            {serverError()}
          </div>
        </Show>

        <form onSubmit={handleSubmit} class="flex flex-col gap-4">
          <Input
            label="Full name"
            type="text"
            name="name"
            placeholder="John Doe"
            value={name()}
            onInput={(e) => setName(e.currentTarget.value)}
            error={errors().name}
            required
          />
          <Input
            label="Email"
            type="email"
            name="email"
            placeholder="you@example.com"
            value={email()}
            onInput={(e) => setEmail(e.currentTarget.value)}
            error={errors().email}
            required
          />
          <div>
            <PasswordInput
              label="Password"
              name="password"
              placeholder="Create a strong password"
              value={password()}
              onInput={(e) => setPassword(e.currentTarget.value)}
              error={errors().password}
              required
            />
            <Show when={strength().level !== "none"}>
              <div class="mt-2">
                <div class="h-1.5 w-full bg-[var(--color-bg-tertiary)] rounded-full overflow-hidden">
                  <div
                    class={`h-full rounded-full transition-all duration-300 ${strengthColors[strength().level]}`}
                    style={{ width: `${strength().percent}%` }}
                  />
                </div>
                <p class={`text-xs mt-1 text-[var(--color-text-tertiary)]`}>
                  Password strength:{" "}
                  <span
                    class={`font-medium ${
                      strength().level === "weak"
                        ? "text-[var(--color-error)]"
                        : strength().level === "medium"
                          ? "text-[var(--color-warning)]"
                          : "text-[var(--color-success)]"
                    }`}
                  >
                    {strength().label}
                  </span>
                </p>
              </div>
            </Show>
          </div>
          <PasswordInput
            label="Confirm password"
            name="confirmPassword"
            placeholder="Re-enter your password"
            value={confirmPassword()}
            onInput={(e) => setConfirmPassword(e.currentTarget.value)}
            error={errors().confirmPassword}
            required
          />
          <label class="flex items-start gap-2 text-sm text-[var(--color-text-secondary)] cursor-pointer">
            <input
              type="checkbox"
              checked={agreeTerms()}
              onChange={() => setAgreeTerms(!agreeTerms())}
              class="mt-0.5 rounded border-[var(--color-border)] text-[var(--color-brand-primary)] focus:ring-[var(--color-brand-primary)]"
            />
            <span>
              I agree to the{" "}
              <a href="/terms" class="text-[var(--color-brand-primary)] hover:underline">
                Terms of Service
              </a>{" "}
              and{" "}
              <a href="/privacy" class="text-[var(--color-brand-primary)] hover:underline">
                Privacy Policy
              </a>
            </span>
          </label>
          <Show when={errors().terms}>
            <p class="text-sm text-[var(--color-error)] -mt-2">{errors().terms}</p>
          </Show>
          <Button type="submit" loading={loading()} class="w-full">
            Create Account
          </Button>
        </form>

        <div class="relative">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-[var(--color-border)]" />
          </div>
          <div class="relative flex justify-center text-xs uppercase">
            <span class="bg-[var(--gradient-card-start)] px-2 text-[var(--color-text-tertiary)]">
              Or continue with
            </span>
          </div>
        </div>

        <SocialAuthButtons />

        <p class="text-center text-sm text-[var(--color-text-secondary)]">
          Already have an account?{" "}
          <a
            href="/login"
            class="text-[var(--color-brand-primary)] hover:text-[var(--color-brand-primary-light)] font-medium transition-colors"
          >
            Log in
          </a>
        </p>
      </div>
    </AuthLayout>
  );
}
