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 ? `${dashboard.efficiency_percentage.toFixed(1)}%` : '94%',
          variant: 'success' as const,
          icon: Target,
          subtitle: t('stats.vs_target_95')
        },
        {
          title: t('stats.average_cost_per_unit'),
          value: '€2.45',
          variant: 'info' as const,
          icon: DollarSign,
          subtitle: t('stats.down_3_vs_last_week')
        },
        {
          title: t('stats.active_equipment'),
          value: '8/9',
          variant: 'warning' as const,
          icon: Settings,
          subtitle: t('stats.one_in_maintenance')
        },
        {
          title: t('stats.quality_score'),
          value: dashboard?.average_quality_score ? `${dashboard.average_quality_score.toFixed(1)}/10` : '9.2/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="min-h-screen">
        {/* Overview Tab - Mixed Dashboard */}
        {activeTab === 'overview' && (
          <div className="grid gap-6">
            <LiveBatchTrackerWidget />
            <OnTimeCompletionWidget />
            <QualityScoreTrendsWidget />
            <WasteDefectTrackerWidget />
            <CapacityUtilizationWidget />
          </div>
        )}

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

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

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

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

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

export default ProductionAnalyticsPage;