import { useCallback, useEffect, useState } from "react";
import { supabase } from "@/lib/supabase";

const PRICING_SUMMARY_SETTING_KEY = "pricing_summary_public";

type SettingRow = {
  key: string;
  value: {
    enabled?: boolean;
  } | null;
};

function parseVisibility(row: SettingRow | null | undefined) {
  return Boolean(row?.value?.enabled);
}

async function fetchPricingSummaryPublicVisibility() {
  const { data, error } = await supabase
    .from("tablero_cdc_app_settings")
    .select("key, value")
    .eq("key", PRICING_SUMMARY_SETTING_KEY)
    .maybeSingle();

  if (error) throw error;

  return parseVisibility(data as SettingRow | null);
}

async function savePricingSummaryPublicVisibility(enabled: boolean) {
  const { error } = await supabase.rpc("tablero_cdc_set_pricing_summary_public", {
    p_enabled: enabled,
  });

  if (error) throw error;
}

export function usePricingSummaryVisibility(enabled = true) {
  const [isPublic, setIsPublic] = useState(false);
  const [loading, setLoading] = useState(enabled);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    if (!enabled) return false;

    setLoading(true);
    setError(null);

    try {
      const nextIsPublic = await fetchPricingSummaryPublicVisibility();
      setIsPublic(nextIsPublic);
      return nextIsPublic;
    } catch (err) {
      console.error("No se pudo leer la visibilidad del total tarifado:", err);
      setError(
        err instanceof Error ? err.message : "No se pudo leer la visibilidad del total tarifado.",
      );
      return false;
    } finally {
      setLoading(false);
    }
  }, [enabled]);

  const setPublicVisibility = useCallback(async (nextIsPublic: boolean) => {
    setSaving(true);
    setError(null);

    try {
      await savePricingSummaryPublicVisibility(nextIsPublic);
      setIsPublic(nextIsPublic);
      return nextIsPublic;
    } catch (err) {
      console.error("No se pudo actualizar la visibilidad del total tarifado:", err);
      setError(
        err instanceof Error
          ? err.message
          : "No se pudo actualizar la visibilidad del total tarifado.",
      );
      throw err;
    } finally {
      setSaving(false);
    }
  }, []);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  useEffect(() => {
    if (!enabled) return;

    const channel = supabase
      .channel("tablero-cdc-pricing-summary-visibility")
      .on(
        "postgres_changes",
        {
          event: "*",
          schema: "public",
          table: "tablero_cdc_app_settings",
          filter: `key=eq.${PRICING_SUMMARY_SETTING_KEY}`,
        },
        (payload) => {
          const nextRow = (payload.new || payload.old) as SettingRow | null;
          setIsPublic(parseVisibility(nextRow));
        },
      )
      .subscribe();

    return () => {
      void supabase.removeChannel(channel);
    };
  }, [enabled]);

  return {
    isPublic,
    loading,
    saving,
    error,
    refresh,
    setPublicVisibility,
  };
}
