"use client";

import Link from "next/link";
import { 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 };
};

export default function ForgotPasswordPage() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("");
  const [sent, setSent] = useState(false);
  const [isError, setIsError] = useState(false);

  const onSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    setStatus("Sending reset link...");
    setIsError(false);
    try {
      const res = await fetch("/api/auth/forgot-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const payload = (await res.json()) as ApiResponse<{ message: string }>;
      if (!res.ok && payload.error) {
        setStatus(payload.error.message ?? "Something went wrong.");
        setIsError(true);
        return;
      }
      setSent(true);
      setStatus(payload.data?.message ?? "If that email exists, a reset link has been sent.");
    } catch {
      setStatus("Something went wrong. Please try again.");
      setIsError(true);
    }
  };

  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">
            Reset your 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">
            {sent ? (
              <div className="text-center space-y-4">
                <div className="mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
                  <svg className="h-6 w-6 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                  </svg>
                </div>
                <p className="text-sm text-foreground font-medium">{status}</p>
                <p className="text-xs text-muted-foreground">Check your email inbox and spam folder.</p>
                <Link href="/login" className="btn-primary inline-flex justify-center py-2.5 px-4">
                  Back to sign in
                </Link>
              </div>
            ) : (
              <form className="space-y-6" onSubmit={onSubmit}>
                <div>
                  <label htmlFor="email" className="block text-sm font-medium text-foreground">
                    Email address
                  </label>
                  <p className="mt-1 text-xs text-muted-foreground">
                    We&#39;ll send a reset link to this address if it has an account.
                  </p>
                  <div className="mt-2">
                    <input
                      id="email" name="email" type="email" autoComplete="email" required
                      value={email} onChange={(e) => setEmail(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">
                  Send reset link
                </button>
                {isError && status && (
                  <div className="rounded-lg bg-red-500/10 border border-red-500/20 p-4">
                    <p className="text-sm text-center text-red-600 dark:text-red-400">{status}</p>
                  </div>
                )}
              </form>
            )}
          </div>
        </div>
      </div>
      <div className="relative z-10">
        <SiteFooter />
      </div>
    </div>
  );
}
