import { useState, useEffect, useCallback } from 'react';
import { supabase } from '../../lib/supabase';

export function useSettings() {
  const [prices, setPrices] = useState({ 200: 2000, 300: 3000 });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchPrices = useCallback(async () => {
    const { data, error } = await supabase
      .from('settings')
      .select('key, value')
      .in('key', ['price_200', 'price_300']);

    if (error) {
      setError(error.message);
    } else if (data) {
      const map = {};
      data.forEach(({ key, value }) => {
        const thickness = parseInt(key.replace('price_', ''), 10);
        map[thickness] = Number(value);
      });
      setPrices((prev) => ({ ...prev, ...map }));
    }
    setLoading(false);
  }, []);

  useEffect(() => {
    fetchPrices();
  }, [fetchPrices]);

  const updatePrice = async (key, value) => {
    const { error } = await supabase
      .from('settings')
      .update({ value: String(value), updated_at: new Date().toISOString() })
      .eq('key', key);

    if (!error) {
      const thickness = parseInt(key.replace('price_', ''), 10);
      setPrices((prev) => ({ ...prev, [thickness]: Number(value) }));
    }
    return { error };
  };

  return { prices, loading, error, updatePrice };
}
