"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
import { Background } from "../../components/background";
import { SiteFooter } from "../../components/site-footer";
import { SiteHeader } from "../../components/site-header";

type ApiResponse<T> = {
  data: T;
  meta: { timestamp: string; version: "v1" };
  error: null | { message: string; code?: string };
};

function ResetPasswordForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get("token") ?? "";

  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");
  const [status, setStatus] = useState("");
  const [isError, setIsError] = useState(false);

  const onSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (password !== confirm) {
      setStatus("Passwords do not match.");
      setIsError(true);
      return;
    }
    if (password.length < 8) {
      setStatus("Password must be at least 8 characters.");
      setIsError(true);
      return;
    }
    if (!token) {
      setStatus("Missing reset token. Please use the link from your email.");
      setIsError(true);
      return;
    }
    setStatus("Resetting password...");
    setIsError(false);
    try {
      const res = await fetch("/api/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password }),
      });
      const payload = (await res.json()) as ApiResponse<{ message: string }>;
      if (!res.ok || payload.error) {
        setStatus(payload.error?.message ?? "Reset failed. The link may have expired.");
        setIsError(true);
        return;
      }
      setStatus("Password reset successfully! Redirecting to sign in...");
      setTimeout(() => router.push("/login"), 2000);
    } catch {
      setStatus("Something went wrong. Please try again.");
      setIsError(true);
    }
  };

  if (!token) {
    return (
      <div className="text-center space-y-4">
        <p className="text-sm text-muted-foreground">Invalid reset link. Please request a new one.</p>
        <Link href="/forgot-password" className="text-primary hover:underline text-sm">Request password reset</Link>
      </div>
    );
  }

  return (
    <form className="space-y-6" onSubmit={onSubmit}>
      <div>
        <label htmlFor="password" className="block text-sm font-medium text-foreground">
          New Password
        </label>
        <div className="mt-1">
          <input
            id="password" name="password" type="password" autoComplete="new-password" required minLength={8}
            value={password} onChange={(e) => setPassword(e.target.value)}
            className="block w-full appearance-none rounded-lg border border-border bg-background/50 px-3 py-2 text-foreground placeholder-muted-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 sm:text-sm transition-all"
          />
        </div>
        <p className="mt-1 text-xs text-muted-foreground">Minimum 8 characters</p>
      </div>
      <div>
        <label htmlFor="confirm" className="block text-sm font-medium text-foreground">
          Confirm Password
        </label>
        <div className="mt-1">
          <input
            id="confirm" name="confirm" type="password" autoComplete="new-password" required
            value={confirm} onChange={(e) => setConfirm(e.target.value)}
            className="block w-full appearance-none rounded-lg border border-border bg-background/50 px-3 py-2 text-foreground placeholder-muted-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 sm:text-sm transition-all"
          />
        </div>
      </div>
      <button type="submit" className="btn-primary w-full py-3">
        Reset Password
      </button>
      {status && (
        <div className={`rounded-lg p-4 ${isError ? "bg-red-500/10 border border-red-500/20" : "bg-primary/10 border border-primary/20"}`}>
          <p className={`text-sm text-center ${isError ? "text-red-600 dark:text-red-400" : "text-foreground"}`}>{status}</p>
        </div>
      )}
    </form>
  );
}

export default function ResetPasswordPage() {
  return (
    <div className="page-soft-bg min-h-screen font-sans text-foreground flex flex-col relative overflow-hidden">
      <Background />
      <SiteHeader />
      <div className="relative z-10 flex flex-1 flex-col justify-center pt-24 pb-16 sm:px-6 lg:px-8">
        <div className="sm:mx-auto sm:w-full sm:max-w-md">
          <div className="flex justify-center">
            <div
              className="h-12 w-12 rounded-full flex items-center justify-center text-white font-bold text-xl shadow-[0_12px_30px_var(--gradient-glow)]"
              style={{ background: "linear-gradient(to right, var(--gradient-start), var(--gradient-mid), var(--gradient-end))" }}
            >
              L1
            </div>
          </div>
          <h2 className="mt-6 text-center text-3xl font-bold tracking-tight text-foreground">
            Set new password
          </h2>
          <p className="mt-2 text-center text-sm text-muted-foreground">
            <Link href="/login" className="font-medium text-primary hover:text-primary/80 transition-colors">
              Back to sign in
            </Link>
          </p>
        </div>
        <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
          <div className="rounded-3xl border border-border/60 bg-gradient-to-b from-background/90 via-background to-background/60 py-8 px-4 shadow-glass backdrop-blur-sm sm:px-10">
            <Suspense fallback={<div className="text-center text-sm text-muted-foreground">Loading...</div>}>
              <ResetPasswordForm />
            </Suspense>
          </div>
        </div>
      </div>
      <div className="relative z-10">
        <SiteFooter />
      </div>
    </div>
  );
}
