"use client";

import { useActionState } from "react";
import { saveGarminCredentialsAction, type SaveGarminCredentialsState } from "./actions";

export function GarminCredentialsForm({ savedEmail }: { savedEmail: string | null }) {
  const [state, action, pending] = useActionState<SaveGarminCredentialsState, FormData>(
    saveGarminCredentialsAction,
    null
  );

  return (
    <form action={action} className="flex flex-col gap-3">
      <div className="flex flex-col gap-1.5">
        <label htmlFor="garmin-email" className="text-sm text-fg/70">
          E-mail Garmin Connect
        </label>
        <input
          id="garmin-email"
          name="email"
          type="email"
          defaultValue={savedEmail ?? ""}
          placeholder="twoj@email.com"
          required
          className="rounded-md border border-white/10 bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg/30 focus:border-accent/60 focus:outline-none"
        />
      </div>
      <div className="flex flex-col gap-1.5">
        <label htmlFor="garmin-password" className="text-sm text-fg/70">
          Hasło Garmin Connect
        </label>
        <input
          id="garmin-password"
          name="password"
          type="password"
          placeholder="••••••••"
          required
          className="rounded-md border border-white/10 bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg/30 focus:border-accent/60 focus:outline-none"
        />
      </div>

      {state && "error" in state && (
        <p className="text-sm text-red-400">{state.error}</p>
      )}
      {state && "success" in state && (
        <p className="text-sm text-accent">Zapisano dane logowania.</p>
      )}

      <button
        type="submit"
        disabled={pending}
        className="btn btn-primary self-start"
      >
        {pending ? "Zapisywanie…" : "Zapisz"}
      </button>
    </form>
  );
}
