// PriceFetchConsentToggle — Settings Privacy section toggle for price_fetching_consent.
//
// Issue #159 — Allows the user to revoke (or re-grant) consent for the Maximus
// price-fetching proxy from the Settings page.
//
// Behavior:
//   - Reads current consent state on mount via getPreference(CONSENT_KEY)
//   - If consent exists: shows toggle as "on" with a Revoke button
//   - If no consent: shows toggle as "off" with a re-grant button
//   - Revoking shows a confirmation dialog; on confirm, DELETEs the row entirely
//     so that the next click on PriceFetchControl re-opens the consent modal
//   - Disabled (with tooltip) when useIsPremium() === false

import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useIsPremium } from "../../hooks/useIsPremium";
import {
  getPreference,
  setPreference,
  deletePreference,
} from "../../services/userPreferenceService";

// Same key as PriceFetchControl (per-profile SQLite DB — no profile_id needed).
const CONSENT_KEY = "price_fetching_consent";

/**
 * Read the current price_fetching_consent preference.
 * Returns the raw JSON string or null if not set.
 */
async function readConsent(): Promise<string | null> {
  try {
    return await getPreference(CONSENT_KEY);
  } catch {
    return null;
  }
}

/**
 * Write consent with the standard {consented_at, version: 1} shape.
 * Matches the shape written by PriceFetchControl on accept.
 */
async function writeConsent(): Promise<void> {
  await setPreference(
    CONSENT_KEY,
    JSON.stringify({ consented_at: new Date().toISOString(), version: 1 })
  );
}

/**
 * Delete the consent row entirely so that PriceFetchControl shows the modal again.
 */
async function revokeConsent(): Promise<void> {
  await deletePreference(CONSENT_KEY);
}

export function PriceFetchConsentToggle() {
  const { t } = useTranslation();
  const isPremium = useIsPremium();
  const [hasConsent, setHasConsent] = useState<boolean>(false);
  const [showConfirm, setShowConfirm] = useState<boolean>(false);
  const [loading, setLoading] = useState(true);

  // Load current consent state on mount.
  useEffect(() => {
    (async () => {
      const value = await readConsent();
      setHasConsent(value !== null);
      setLoading(false);
    })();
  }, []);

  const handleToggle = () => {
    if (!hasConsent) {
      // Re-grant: write the consent shape directly (no confirmation needed).
      writeConsent().then(() => setHasConsent(true));
    } else {
      // Revoke: ask for confirmation first.
      setShowConfirm(true);
    }
  };

  const handleConfirmRevoke = async () => {
    await revokeConsent();
    setHasConsent(false);
    setShowConfirm(false);
  };

  const handleCancelRevoke = () => {
    setShowConfirm(false);
  };

  // Return nothing while loading to avoid flash.
  if (loading) return null;

  return (
    <div className="bg-[var(--card)] border border-[var(--border)] rounded-xl p-6 space-y-4">
      <h2 className="text-lg font-semibold">
        {t("settings.privacy.title")}
      </h2>

      {/* Price fetch consent row */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex-1 min-w-0">
          <p className="text-sm font-medium text-[var(--foreground)]">
            {t("settings.privacy.priceFetchConsent.label")}
          </p>
          <p className="text-xs text-[var(--muted-foreground)] mt-0.5">
            {t("settings.privacy.priceFetchConsent.description")}
          </p>
        </div>
        <button
          type="button"
          role="switch"
          aria-checked={hasConsent}
          disabled={!isPremium}
          title={
            !isPremium
              ? t("settings.privacy.priceFetchConsent.notPremium")
              : undefined
          }
          onClick={handleToggle}
          className={[
            "shrink-0 relative inline-flex items-center h-6 w-11 rounded-full border-2 border-transparent",
            "transition-colors duration-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--primary)]",
            hasConsent
              ? "bg-[var(--primary)]"
              : "bg-[var(--muted)]",
            !isPremium
              ? "opacity-40 cursor-not-allowed"
              : "cursor-pointer",
          ].join(" ")}
        >
          <span
            className={[
              "pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow transform transition-transform duration-200",
              hasConsent ? "translate-x-5" : "translate-x-0",
            ].join(" ")}
          />
        </button>
      </div>

      {/* Confirmation dialog for revoke */}
      {showConfirm && (
        <div
          role="dialog"
          aria-modal="true"
          aria-label={t("settings.privacy.priceFetchConsent.revokeButton")}
          className="rounded-lg border border-[var(--border)] bg-[var(--background)] p-4 space-y-3"
        >
          <p className="text-sm text-[var(--foreground)]">
            {t("settings.privacy.priceFetchConsent.confirmRevoke")}
          </p>
          <div className="flex justify-end gap-2">
            <button
              type="button"
              onClick={handleCancelRevoke}
              className="px-3 py-1.5 rounded-lg border border-[var(--border)] text-sm hover:bg-[var(--muted)] transition-colors"
            >
              {t("common.cancel")}
            </button>
            <button
              type="button"
              onClick={handleConfirmRevoke}
              className="px-3 py-1.5 rounded-lg bg-[var(--negative)] text-white text-sm font-medium hover:opacity-90 transition-opacity"
            >
              {t("settings.privacy.priceFetchConsent.revokeButton")}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
