"use client";

import { useReducer } from "react";
import Link from "next/link";

type State = {
  password: string;
  confirm: string;
  error: string | null;
  loading: boolean;
  done: boolean;
};

type Action =
  | { type: "SET_PASSWORD"; value: string }
  | { type: "SET_CONFIRM"; value: string }
  | { type: "SET_ERROR"; value: string | null }
  | { type: "SET_LOADING"; value: boolean }
  | { type: "SET_DONE"; value: boolean };

const initialState: State = {
  password: "",
  confirm: "",
  error: null,
  loading: false,
  done: false,
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_PASSWORD":
      return { ...state, password: action.value };
    case "SET_CONFIRM":
      return { ...state, confirm: action.value };
    case "SET_ERROR":
      return { ...state, error: action.value };
    case "SET_LOADING":
      return { ...state, loading: action.value };
    case "SET_DONE":
      return { ...state, done: action.value };
  }
}

export default function ResetPasswordPage() {
  const [state, dispatch] = useReducer(reducer, initialState);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    dispatch({ type: "SET_ERROR", value: null });

    if (state.password.length < 8) {
      dispatch({ type: "SET_ERROR", value: "Password must be at least 8 characters." });
      return;
    }
    if (state.password !== state.confirm) {
      dispatch({ type: "SET_ERROR", value: "Passwords do not match." });
      return;
    }

    dispatch({ type: "SET_LOADING", value: true });

    try {
      const res = await fetch("/api/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password: state.password }),
      });

      const data = await res.json();

      if (!res.ok || data.error) {
        dispatch({ type: "SET_ERROR", value: data.message ?? "Failed to reset password. The link may have expired." });
        dispatch({ type: "SET_LOADING", value: false });
        return;
      }

      dispatch({ type: "SET_DONE", value: true });
    } catch {
      dispatch({ type: "SET_ERROR", value: "An unexpected error occurred. Please try again." });
    } finally {
      dispatch({ type: "SET_LOADING", value: false });
    }
  }

  if (state.done) {
    return (
      <main className="min-h-screen bg-slate-100 px-6 py-12">
        <div className="mx-auto max-w-md">
          <div className="rounded-2xl bg-white p-8 shadow-sm ring-1 ring-slate-200 text-center">
            <div className="mb-4 flex h-12 w-12 mx-auto items-center justify-center rounded-full bg-green-100">
              <svg className="h-6 w-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
              </svg>
            </div>
            <h2 className="text-2xl font-bold text-slate-900">Password Updated</h2>
            <p className="mt-2 text-sm text-slate-500">
              Your password has been updated. Please sign in with your new password.
            </p>
            <Link
              href="/login"
              className="mt-6 inline-block rounded-xl bg-slate-900 px-6 py-3 text-sm font-bold text-white hover:bg-slate-800"
            >
              Sign In
            </Link>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen bg-slate-100 px-6 py-12">
      <div className="mx-auto max-w-md">
        <div className="rounded-2xl bg-white p-8 shadow-sm ring-1 ring-slate-200">
          <div className="mb-6 flex h-12 w-12 items-center justify-center rounded-full bg-orange-100">
            <svg className="h-6 w-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
            </svg>
          </div>
          <h1 className="text-2xl font-bold text-slate-900">Set New Password</h1>
          <p className="mt-1 text-sm text-slate-500">
            Enter your new password below.
          </p>

          <form onSubmit={handleSubmit} className="mt-6 space-y-4">
            {state.error && (
              <div className="rounded-xl bg-red-50 p-4 text-sm text-red-700">
                {state.error}
              </div>
            )}

            <div>
              <label htmlFor="fld-1-new-password"  className="block text-sm font-medium text-slate-700">New Password</label>
              <input id="fld-1-new-password"  aria-label=". 8 Characters"
                type="password"
                value={state.password}
                onChange={(e) => dispatch({ type: "SET_PASSWORD", value: e.target.value })}
                required
                minLength={8}
                className="mt-1 w-full rounded-xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-900"
                placeholder="Min. 8 characters"
              />
            </div>

            <div>
              <label htmlFor="fld-2-confirm-password"  className="block text-sm font-medium text-slate-700">Confirm Password</label>
              <input id="fld-2-confirm-password"  aria-label="Repeat Password"
                type="password"
                value={state.confirm}
                onChange={(e) => dispatch({ type: "SET_CONFIRM", value: e.target.value })}
                required
                className="mt-1 w-full rounded-xl border border-slate-300 px-4 py-3 outline-none focus:border-slate-900"
                placeholder="Repeat password"
              />
            </div>

            <button
              type="submit"
              disabled={state.loading}
              className="w-full rounded-xl bg-slate-900 px-6 py-4 text-base font-bold text-white disabled:opacity-50"
            >
              {state.loading ? "Updating..." : "Update Password"}
            </button>
          </form>
        </div>

        <Link href="/login" className="mt-4 block text-sm text-slate-500 hover:text-slate-700">
          ← Back to sign in
        </Link>
      </div>
    </main>
  );
}
