import { ErrorCode } from "@batch-cooking/shared";
import { type FormEvent, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { ApiError } from "../../api/client";
import { useAuth } from "../../features/auth/AuthContext";
import { errorMessageService } from "../../services/error-message.service";
import "./settings-pages.scss";

/**
 * Account settings — routed at `/parametres/compte`. Read-only identity
 * (editing name/email isn't a requested feature yet) plus a "danger zone"
 * to permanently delete the account, gated behind re-entering the current
 * password (same idea as `login`'s check, see `auth.service.ts`'s
 * `deleteAccount`).
 */
export function AccountSettingsPage() {
  const { t } = useTranslation();
  const { user, deleteAccount } = useAuth();
  const navigate = useNavigate();

  const [isConfirming, setIsConfirming] = useState(false);
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleDelete(e: FormEvent) {
    e.preventDefault();
    setError(null);
    setIsSubmitting(true);
    try {
      await deleteAccount(password);
      void navigate("/login");
    } catch (err) {
      const code = err instanceof ApiError ? err.code : ErrorCode.INTERNAL_ERROR;
      setError(errorMessageService.getLabel(code));
    } finally {
      setIsSubmitting(false);
    }
  }

  function cancelDelete() {
    setIsConfirming(false);
    setPassword("");
    setError(null);
  }

  return (
    <div className="settings-page">
      <h1>{t("account.title")}</h1>

      <div className="settings-page__section">
        <p>
          {t("account.identity.firstNameLabel")}: {user?.firstName}
        </p>
        <p>
          {t("account.identity.lastNameLabel")}: {user?.lastName}
        </p>
        <p>
          {t("account.identity.emailLabel")}: {user?.email}
        </p>
      </div>

      <div className="settings-page__section settings-page__danger-zone">
        <h2 className="settings-page__section-title">{t("account.dangerZone.title")}</h2>
        <p className="settings-page__hint">{t("account.dangerZone.description")}</p>

        {!isConfirming ? (
          <div className="settings-page__actions">
            <button
              type="button"
              className="settings-page__danger-button"
              onClick={() => setIsConfirming(true)}
            >
              {t("account.dangerZone.deleteButton")}
            </button>
          </div>
        ) : (
          <form onSubmit={handleDelete} noValidate>
            <label htmlFor="deleteAccountPassword">{t("account.dangerZone.passwordLabel")}</label>
            <input
              id="deleteAccountPassword"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
            />
            {error && <p className="field-error">{error}</p>}
            <div className="settings-page__actions">
              <button
                type="submit"
                className="settings-page__danger-button"
                disabled={isSubmitting}
              >
                {t("account.dangerZone.confirmButton")}
              </button>
              <button type="button" onClick={cancelDelete} disabled={isSubmitting}>
                {t("account.dangerZone.cancelButton")}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
