import { fetchPremiumStatus } from '@api/app';
import { useState, useEffect } from 'react';
import { storage, StoreType } from 'src/storage';

const SUBSCRIPTION_KEY = 'user_subscription';

export const useSubscription = () => {
  const token = storage.get('token', StoreType.STRING) as string;
  const [isPremium, setIsPremium] = useState(true);
  const [loading, setLoading] = useState(true);

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

  const checkSubscription = async () => {
    try {
      setLoading(true);
      const status = await fetchPremiumStatus(token);
      if (status && 'premium-status' in status) {
        storage.set(SUBSCRIPTION_KEY, status['premium-status']);
      }

      const subscriptionData = (storage.get(SUBSCRIPTION_KEY, StoreType.NUMBER) as number) ?? null;

      if (subscriptionData) {
        // const isValid = subscription.active && new Date(subscription.expiryDate) > new Date();
        const isValid = subscriptionData == 1;

        setIsPremium(isValid);
      } else {
        setIsPremium(false);
      }
    } catch (error) {
      console.error('Error checking subscription:', error);
      setIsPremium(false);
    } finally {
      setLoading(false);
    }
  };

  const setPremium = (active: boolean, expiryDate = null) => {
    // try {
    //   const expiry = expiryDate || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
    //   const subscription = {
    //     active,
    //     expiryDate: expiry.toISOString()
    //   };
    //   storage.set(SUBSCRIPTION_KEY, JSON.stringify(subscription));
    //   setIsPremium(active);
    // } catch (error) {
    //   console.error('Error setting subscription:', error);
    // }
  };

  return {
    isPremium,
    loading,
    checkSubscription,
    setPremium
  };
};
