import type { ReactNode } from 'react';
import { Result, Button, Skeleton } from 'antd';
import { useNavigate } from 'react-router-dom';
import { SettingOutlined } from '@ant-design/icons';
import { useSettingsStore } from '@/stores/settings.store';
import { useAuthStore } from '@/stores/auth.store';
import { hasAnyRole } from '@/utils/roles';
import type { SiteSettings } from '@/types/api';

const FEATURE_LABELS: Record<string, string> = {
  enableInfluence: 'Influence (Advocacy Campaigns)',
  enableMap: 'Map & Canvassing',
  enableLandingPages: 'Landing Pages',
  enableNewsletter: 'Newsletter',
  enableMediaFeatures: 'Media Library',
  enablePayments: 'Payments',
  enableGalleryAds: 'Gallery Ads',
  enablePeople: 'People CRM',
  enableEvents: 'Events',
  enableSocial: 'Social Connections',
  enableMeet: 'Video Meetings',
  enableMeetingPlanner: 'Meeting Planner',
  enableTicketedEvents: 'Ticketed Events',
  enableSocialCalendar: 'Social Calendar',
  enablePetitions: 'Petitions',
  enablePolls: 'Straw Polls',
  enableAnalytics: 'Analytics Dashboard',
};

interface FeatureGateProps {
  feature: keyof Pick<SiteSettings, 'enableInfluence' | 'enableMap' | 'enableLandingPages' | 'enableNewsletter' | 'enableMediaFeatures' | 'enablePayments' | 'enableGalleryAds' | 'enablePeople' | 'enableEvents' | 'enableSocial' | 'enableMeet' | 'enableMeetingPlanner' | 'enableTicketedEvents' | 'enableSocialCalendar' | 'enablePetitions' | 'enablePolls' | 'enableAnalytics'>;
  children: ReactNode;
}

export default function FeatureGate({ feature, children }: FeatureGateProps) {
  const { settings, loading } = useSettingsStore();
  const { user } = useAuthStore();
  const navigate = useNavigate();
  const isSuperAdmin = hasAnyRole(user, ['SUPER_ADMIN']);
  const featureName = FEATURE_LABELS[feature] || feature;

  // Show skeleton while settings are loading to prevent briefly showing disabled features
  if (loading || !settings) return <Skeleton active style={{ padding: 24 }} />;

  if (settings[feature] === false) {
    return (
      <Result
        status="info"
        title="Feature Not Enabled"
        subTitle={isSuperAdmin
          ? `${featureName} is currently disabled. You can enable it in Settings.`
          : `${featureName} has not been enabled for this site.`
        }
        style={{ paddingTop: 80 }}
        extra={isSuperAdmin && (
          <Button
            type="primary"
            icon={<SettingOutlined />}
            onClick={() => navigate('/app/settings', { state: { activeTab: 'features' } })}
          >
            Go to Settings
          </Button>
        )}
      />
    );
  }

  return <>{children}</>;
}
