import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
  Factory,
  DollarSign,
  Award,
  Settings,
  Brain,
  BarChart3,
  TrendingUp,
  Target,
  Zap
} from 'lucide-react';
import { AnalyticsPageLayout } from '../../../components/analytics';
import { useSubscription } from '../../../api/hooks/subscription';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useProductionDashboard } from '../../../api/hooks/production';

// Import all analytics widgets
import {
  TodaysScheduleSummaryWidget,
  LiveBatchTrackerWidget,
  OnTimeCompletionWidget,
  CapacityUtilizationWidget,
  CostPerUnitWidget,
  WasteDefectTrackerWidget,
  YieldPerformanceWidget,
  QualityScoreTrendsWidget,
  TopDefectTypesWidget,
  EquipmentStatusWidget,
  MaintenanceScheduleWidget,
  EquipmentEfficiencyWidget,
  AIInsightsWidget,
  PredictiveMaintenanceWidget
} from '../../../components/domain/production/analytics/widgets';

const ProductionAnalyticsPage: React.FC = () => {
  const { t } = useTranslation('production');
  const { canAccessAnalytics, subscriptionInfo } = useSubscription();
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  const [activeTab, setActiveTab] = useState('overview');

  const { data: dashboard, isLoading: dashboardLoading } = useProductionDashboard(tenantId);

  // Check if user has access to advanced analytics (professional/enterprise)
  const hasAdvancedAccess = canAccessAnalytics('advanced');

  // Tab configuration
  const tabs = [
    {
      id: 'overview',
      label: t('tabs.overview'),
      icon: BarChart3
    },
    {
      id: 'operations',
      label: t('tabs.bakery_operations'),
      icon: Factory
    },
    {
      id: 'cost-efficiency',
      label: t('tabs.cost_efficiency'),
      icon: DollarSign
    },
    {
      id: 'quality',
      label: t('tabs.quality_assurance'),
      icon: Award
    },
    {
      id: 'equipment',
      label: t('tabs.equipment_maintenance'),
      icon: Settings
    },
    {
      id: 'ai-insights',
      label: t('tabs.ai_insights'),
      icon: Brain
    }
  ];

  return (
    <AnalyticsPageLayout
      title={t('analytics.production_analytics')}
      description={t('analytics.advanced_insights_professionals_enterprises')}
      subscriptionLoading={subscriptionInfo.loading}
      hasAccess={hasAdvancedAccess}
      dataLoading={dashboardLoading}
      actions={[
        {
          id: 'export-report',
          label: t('actions.export_report'),
          icon: TrendingUp,
          onClick: () => {},
          variant: 'outline',
          size: 'sm',
        },
        {
          id: 'optimize-production',
          label: t('actions.optimize_production'),
          icon: Zap,
          onClick: () => {},
          variant: 'primary',
          size: 'sm',
        },
      ]}
      stats={[
        {
          title: t('stats.overall_efficiency'),
          value: `${(dashboard?.efficiency_percentage ?? 0).toFixed(1)}%`,
          variant: 'success' as const,
          icon: Target,
          subtitle: t('stats.vs_target_95')
        },
        {
          title: t('stats.capacity_utilization'),
          value: `${(dashboard?.capacity_utilization ?? 0).toFixed(1)}%`,
          variant: 'info' as const,
          icon: DollarSign,
          subtitle: t('stats.current_capacity')
        },
        {
          title: t('stats.on_time_completion'),
          value: `${(dashboard?.on_time_completion_rate ?? 0).toFixed(1)}%`,
          variant: 'warning' as const,
          icon: Settings,
          subtitle: t('stats.completion_rate')
        },
        {
          title: t('stats.quality_score'),
          value: `${(dashboard?.average_quality_score ?? 0).toFixed(1)}/10`,
          variant: 'success' as const,
          icon: Award,
          subtitle: t('stats.excellent_standards')
        }
      ]}
      statsColumns={4}
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={setActiveTab}
      showMobileNotice={true}
      mobileNoticeText={t('mobile.swipe_scroll_interact')}
    >
      {/* Tab Content */}
      <div className="space-y-6">
        {/* Overview Tab - Mixed Dashboard */}
        {activeTab === 'overview' && (
          <div className="grid grid-cols-1 gap-6">
            <LiveBatchTrackerWidget />
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <OnTimeCompletionWidget />
              <CapacityUtilizationWidget />
            </div>
            <QualityScoreTrendsWidget />
            <WasteDefectTrackerWidget />
          </div>
        )}

        {/* Bakery Operations Tab */}
        {activeTab === 'operations' && (
          <div className="grid grid-cols-1 gap-6">
            <TodaysScheduleSummaryWidget />
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <OnTimeCompletionWidget />
              <CapacityUtilizationWidget />
            </div>
            <LiveBatchTrackerWidget />
          </div>
        )}

        {/* Cost & Efficiency Tab */}
        {activeTab === 'cost-efficiency' && (
          <div className="grid grid-cols-1 gap-6">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <CostPerUnitWidget />
              <YieldPerformanceWidget />
            </div>
            <WasteDefectTrackerWidget />
          </div>
        )}

        {/* Quality Assurance Tab */}
        {activeTab === 'quality' && (
          <div className="grid grid-cols-1 gap-6">
            <QualityScoreTrendsWidget />
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <WasteDefectTrackerWidget />
              <TopDefectTypesWidget />
            </div>
          </div>
        )}

        {/* Equipment & Maintenance Tab */}
        {activeTab === 'equipment' && (
          <div className="grid grid-cols-1 gap-6">
            <EquipmentStatusWidget />
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              <MaintenanceScheduleWidget />
              <EquipmentEfficiencyWidget />
            </div>
          </div>
        )}

        {/* AI Insights Tab */}
        {activeTab === 'ai-insights' && (
          <div className="grid grid-cols-1 gap-6">
            <AIInsightsWidget />
            <PredictiveMaintenanceWidget />
          </div>
        )}
      </div>
    </AnalyticsPageLayout>
  );
};

export default ProductionAnalyticsPage;