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

interface FormErrors {
  password?: string;
  confirmPassword?: string;
}

export default function ResetPasswordPage() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const token = () => (Array.isArray(searchParams.token) ? searchParams.token[0] : searchParams.token) ?? "";
  const [password, setPassword] = createSignal("");
  const [confirmPassword, setConfirmPassword] = createSignal("");
  const [errors, setErrors] = createSignal<FormErrors>({});
  const [loading, setLoading] = createSignal(false);
  const [serverError, setServerError] = createSignal("");
  const [success, setSuccess] = createSignal(false);

  function validate(): boolean {
    const errs: FormErrors = {};
    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";
    setErrors(errs);
    return Object.keys(errs).length === 0;
  }

  async function handleSubmit(e: Event) {
    e.preventDefault();
    setServerError("");
    if (!validate()) return;
    if (!token()) {
      setServerError("Invalid or missing reset token.");
      return;
    }
    setLoading(true);
    try {
      await resetPassword(token(), password());
      setSuccess(true);
    } catch {
      setServerError("Something went wrong. Please try again.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <AuthLayout>
      <Title>Reset Password — ShieldAI</Title>
      <div class="flex flex-col gap-6">
        <Show
          when={!success()}
          fallback={
            <div class="flex flex-col items-center gap-4 py-4 text-center">
              <div class="h-12 w-12 rounded-full bg-[var(--color-success-bg)] flex items-center justify-center">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  class="h-6 w-6 text-[var(--color-success)]"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="2"
                >
                  <path d="M20 6L9 17L4 12" />
                </svg>
              </div>
              <h3 class="text-lg font-semibold text-[var(--color-text-primary)]">
                Password reset successful
              </h3>
              <p class="text-sm text-[var(--color-text-secondary)]">
                Your password has been updated.
              </p>
              <Button onClick={() => navigate("/login", { replace: true })}>
                Back to Sign In
              </Button>
            </div>
          }
        >
          <div class="text-center">
            <h2 class="text-2xl font-bold text-[var(--color-text-primary)]">
              Set new password
            </h2>
            <p class="text-sm text-[var(--color-text-secondary)] mt-1">
              Enter your new password below
            </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>

          <Show when={!token()}>
            <div
              class="px-4 py-3 rounded-lg text-sm bg-[var(--color-warning-bg)] text-[var(--color-warning)] border border-[var(--color-warning)]/30"
              role="alert"
            >
              Invalid or missing reset token. Please request a new password
              reset.
            </div>
          </Show>

          <form onSubmit={handleSubmit} class="flex flex-col gap-4">
            <PasswordInput
              label="New password"
              name="password"
              placeholder="Enter new password"
              value={password()}
              onInput={(e) => setPassword(e.currentTarget.value)}
              error={errors().password}
              required
            />
            <PasswordInput
              label="Confirm new password"
              name="confirmPassword"
              placeholder="Re-enter new password"
              value={confirmPassword()}
              onInput={(e) => setConfirmPassword(e.currentTarget.value)}
              error={errors().confirmPassword}
              required
            />
            <Button
              type="submit"
              loading={loading()}
              disabled={!token()}
              class="w-full"
            >
              Reset Password
            </Button>
          </form>
        </Show>
      </div>
    </AuthLayout>
  );
}
