"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  validateResetToken,
  resetPassword,
} from "@/lib/actions/password-reset";

export default function ResetPasswordForm({ token }: { token: string }) {
  const router = useRouter();
  const [status, setStatus] = useState<"loading" | "valid" | "invalid">(
    "loading",
  );
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [error, setError] = useState("");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    let cancelled = false;
    validateResetToken(token).then((res) => {
      if (cancelled) return;
      setStatus(res.ok ? "valid" : "invalid");
    });
    return () => {
      cancelled = true;
    };
  }, [token]);

  if (status === "loading") {
    return (
      <p className="px-2 text-sm text-muted-foreground">
        Checking your reset link…
      </p>
    );
  }

  if (status === "invalid") {
    return (
      <div className="space-y-4 px-2 md:px-6">
        <div className="rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">
          This reset link is invalid, expired, or has already been used.
        </div>
        <Button
          className="h-10 w-full rounded-full"
          render={<Link href="/forgot-password" />}
          nativeButton={false}
        >
          Request a new link
        </Button>
      </div>
    );
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setMessage("");

    if (password.length < 8) {
      setError("Password must be at least 8 characters.");
      return;
    }
    if (password !== confirm) {
      setError("Passwords do not match.");
      return;
    }

    setLoading(true);
    const res = await resetPassword(token, password);
    setLoading(false);

    if (!res.ok) {
      setError(res.error);
      return;
    }
    setMessage("Password updated successfully.");
    setTimeout(() => router.push("/login"), 1200);
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4 px-2 md:px-6">
      {error && (
        <div role="alert" className="rounded-md bg-destructive/10 px-3 py-2 text-xs text-destructive">
          {error}
        </div>
      )}
      {message && (
        <div className="rounded-md bg-primary/10 px-3 py-2 text-xs text-primary">
          {message}
        </div>
      )}

      <div className="space-y-1.5">
        <Label htmlFor="password" className="text-sm">
          New password
        </Label>
        <Input
          id="password"
          type="password"
          placeholder="At least 8 characters"
          className="h-10"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          disabled={loading}
          autoComplete="new-password"
          autoFocus
        />
      </div>

      <div className="space-y-1.5">
        <Label htmlFor="confirm" className="text-sm">
          Confirm new password
        </Label>
        <Input
          id="confirm"
          type="password"
          placeholder="Re-enter your new password"
          className="h-10"
          value={confirm}
          onChange={(e) => setConfirm(e.target.value)}
          disabled={loading}
          autoComplete="new-password"
        />
      </div>

      <Button type="submit" className="h-10 w-full rounded-full" disabled={loading}>
        {loading ? "Saving..." : "Save new password"}
      </Button>
    </form>
  );
}