"use client";

import { useState, useTransition } from "react";
import { setLocale } from "./actions";

const OPTIONS = [
  { value: "en", label: "English" },
  { value: "de", label: "Deutsch" },
  { value: "fr", label: "Français" },
];

export default function LanguageForm({ initialLocale }: { initialLocale: string }) {
  const [value, setValue] = useState(initialLocale);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();

  const onSave = () => {
    setSaved(false);
    setError(null);
    startTransition(async () => {
      const res = await setLocale(value);
      if (res.ok) {
        setSaved(true);
        // Reload so next-intl re-resolves from the new cookie immediately.
        setTimeout(() => window.location.reload(), 250);
      } else {
        setError(res.error ?? "unknown_error");
      }
    });
  };

  return (
    <div className="card shadow-sm" style={{ maxWidth: 480 }}>
      <div className="card-body">
        <h5 className="card-title mb-3">
          <i className="ph ph-globe me-2" aria-hidden="true"></i>
          Language
        </h5>
        <p className="text-muted small mb-3">
          Sets the display language across all GoSec Cloud apps signed
          in to this browser. Stored on your account; new browsers pick
          it up automatically on sign-in.
        </p>

        <div className="mb-3">
          <label htmlFor="locale" className="form-label">
            Display language
          </label>
          <select
            id="locale"
            className="form-select"
            value={value}
            onChange={(e) => {
              setValue(e.target.value);
              setSaved(false);
            }}
          >
            {OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </div>

        <button
          type="button"
          className="btn btn-primary"
          disabled={pending || value === ""}
          onClick={onSave}
        >
          {pending ? "Saving…" : "Save"}
        </button>

        {saved && (
          <span className="text-success small ms-3">
            <i className="ph ph-check-circle me-1"></i>Saved. Reloading…
          </span>
        )}
        {error && (
          <span className="text-danger small ms-3">{error}</span>
        )}
      </div>
    </div>
  );
}
