"use client";

import Link from "next/link";
import { FormEvent, useState } from "react";

import { useLocale } from "@/components/providers/locale-provider";

export function ResetPasswordClient({ token }: { token: string }) {
  const { dict } = useLocale();
  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setSubmitting(true);
    setError(null);
    setMessage(null);

    try {
      const response = await fetch("/api/v1/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          token,
          password,
          password_confirmation: passwordConfirmation
        })
      });
      const payload = (await response.json()) as {
        message?: string;
        errors?: Record<string, string[]>;
      };
      if (!response.ok) {
        const firstError = payload.errors ? Object.values(payload.errors)[0]?.[0] : undefined;
        throw new Error(firstError ?? payload.message ?? dict.resetPassword.failure);
      }
      setMessage(payload.message ?? dict.resetPassword.success);
      setPassword("");
      setPasswordConfirmation("");
    } catch (err) {
      setError(err instanceof Error ? err.message : dict.resetPassword.failure);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-canvas px-6 py-10">
      <div className="w-full max-w-xl rounded-lg border border-line/70 bg-white p-8 shadow-panel sm:p-12">
        <h1 className="text-[36px] font-semibold tracking-tight text-ink">{dict.resetPassword.title}</h1>
        <p className="mt-3 text-[17px] leading-7 text-slate-600">
          {dict.resetPassword.description}
        </p>

        {!token ? (
          <div className="mt-6 rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">
            {dict.resetPassword.tokenMissing}
          </div>
        ) : (
          <form className="mt-8 space-y-5" onSubmit={handleSubmit}>
            <label className="block">
              <span className="ops-label">{dict.resetPassword.newPassword}</span>
              <input
                type="password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                className="ops-input"
              />
            </label>
            <label className="block">
              <span className="ops-label">{dict.resetPassword.confirmPassword}</span>
              <input
                type="password"
                value={passwordConfirmation}
                onChange={(event) => setPasswordConfirmation(event.target.value)}
                className="ops-input"
              />
            </label>

            {error ? <div className="rounded border border-ember/30 bg-ember/10 px-4 py-3 text-sm text-ember">{error}</div> : null}
            {message ? <div className="rounded border border-moss/30 bg-moss/10 px-4 py-3 text-sm text-moss">{message}</div> : null}

            <button type="submit" disabled={submitting || !token} className="ops-btn-primary">
              {submitting ? dict.common.processing : dict.resetPassword.saveNewPassword}
            </button>
          </form>
        )}

        <div className="mt-8">
          <Link href="/login" className="text-sm font-semibold text-moss">
            {dict.common.backToLogin}
          </Link>
        </div>
      </div>
    </main>
  );
}
