'use client';

import { createContext, useContext, useState, useEffect, useCallback } from 'react';
import { useAuth } from './AuthContext';

interface PlanFeaturesContextType {
  features: string[];
  planName: string | null;
  planStatus: string | null;
  hasFeature: (key: string) => boolean;
  loading: boolean;
  refresh: () => void;
}

const PlanFeaturesContext = createContext<PlanFeaturesContextType>({
  features: [],
  planName: null,
  planStatus: null,
  hasFeature: () => true,
  loading: true,
  refresh: () => {},
});

export function usePlanFeatures() {
  return useContext(PlanFeaturesContext);
}

export function PlanFeaturesProvider({ children }: { children: React.ReactNode }) {
  const { restaurantId, userRecord, loading: authLoading } = useAuth();
  const [features, setFeatures] = useState<string[]>([]);
  const [planName, setPlanName] = useState<string | null>(null);
  const [planStatus, setPlanStatus] = useState<string | null>(null);
  const [featuresLoading, setFeaturesLoading] = useState(true);

  const load = useCallback(() => {
    if (authLoading) return;
    if (!restaurantId) {
      setFeatures([]);
      setPlanName(null);
      setPlanStatus(null);
      setFeaturesLoading(false);
      return;
    }
    setFeaturesLoading(true);
    fetch('/api/billing', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        const sub = data?.subscription;

        // Parse features — JSONB comes as array, but handle string fallback
        const f = sub?.features;
        if (Array.isArray(f)) {
          setFeatures(f);
        } else if (typeof f === 'string') {
          try {
            const parsed = JSON.parse(f);
            setFeatures(Array.isArray(parsed) ? parsed : []);
          } catch {
            setFeatures([]);
          }
        } else {
          setFeatures([]);
        }

        // plan_name comes from the raw DB row (snake_case)
        setPlanName((sub?.plan_name ?? sub?.planName ?? null) as string | null);
        setPlanStatus((sub?.status ?? null) as string | null);
      })
      .catch(() => {
        setFeatures([]);
        setPlanName(null);
        setPlanStatus(null);
      })
      .finally(() => setFeaturesLoading(false));
  }, [restaurantId, authLoading]);

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

  const loading = authLoading || featuresLoading;

  const hasFeature = useCallback((key: string) => {
    if (authLoading || featuresLoading) return true;
    if (!restaurantId) {
      const role = userRecord?.role;
      return role === 'superadmin' || role === 'support';
    }
    return features.includes(key);
  }, [features, authLoading, featuresLoading, restaurantId, userRecord]);

  return (
    <PlanFeaturesContext.Provider value={{ features, planName, planStatus, hasFeature, loading, refresh: load }}>
      {children}
    </PlanFeaturesContext.Provider>
  );
}
