/*
 * Network Performance Tab Component for Enterprise Dashboard
 * Shows cross-location benchmarking and performance comparison
 */

import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card';
import { Button } from '../ui/Button';
import { BarChart3, TrendingUp, TrendingDown, Activity, CheckCircle2, AlertTriangle, Clock, Award, Target, LineChart, PieChart, Building2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useChildrenPerformance } from '../../api/hooks/useEnterpriseDashboard';
import PerformanceChart from '../charts/PerformanceChart';
import StatusCard from '../ui/StatusCard/StatusCard';
import { useTenantCurrency } from '../../hooks/useTenantCurrency';

interface NetworkPerformanceTabProps {
  tenantId: string;
  onOutletClick?: (outletId: string, outletName: string) => void;
}

const NetworkPerformanceTab: React.FC<NetworkPerformanceTabProps> = ({ tenantId, onOutletClick }) => {
  const { t } = useTranslation('dashboard');
  const { currencySymbol } = useTenantCurrency();
  const [selectedMetric, setSelectedMetric] = useState('sales');
  const [selectedPeriod, setSelectedPeriod] = useState(30);
  const [viewMode, setViewMode] = useState<'chart' | 'cards'>('chart');

  // Get children performance data
  const {
    data: childrenPerformance,
    isLoading: isChildrenPerformanceLoading,
    error: childrenPerformanceError
  } = useChildrenPerformance(tenantId!, selectedMetric, selectedPeriod, {
    enabled: !!tenantId,
  });

  const isLoading = isChildrenPerformanceLoading;

  // Calculate network-wide metrics
  const calculateNetworkMetrics = () => {
    if (!childrenPerformance?.rankings || childrenPerformance.rankings.length === 0) {
      return null;
    }

    const rankings = childrenPerformance.rankings;
    
    // Calculate averages
    const totalSales = rankings.reduce((sum, r) => sum + (selectedMetric === 'sales' ? r.metric_value : 0), 0);
    const totalInventory = rankings.reduce((sum, r) => sum + (selectedMetric === 'inventory_value' ? r.metric_value : 0), 0);
    const totalOrders = rankings.reduce((sum, r) => sum + (selectedMetric === 'order_frequency' ? r.metric_value : 0), 0);
    
    const avgSales = totalSales / rankings.length;
    const avgInventory = totalInventory / rankings.length;
    const avgOrders = totalOrders / rankings.length;

    // Find top and bottom performers
    const sortedByMetric = [...rankings].sort((a, b) => b.metric_value - a.metric_value);
    const topPerformer = sortedByMetric[0];
    const bottomPerformer = sortedByMetric[sortedByMetric.length - 1];

    // Calculate performance variance
    const variance = sortedByMetric.length > 1 
      ? Math.round(((topPerformer.metric_value - bottomPerformer.metric_value) / topPerformer.metric_value) * 100)
      : 0;

    return {
      totalOutlets: rankings.length,
      avgSales,
      avgInventory,
      avgOrders,
      totalSales,
      totalInventory,
      totalOrders,
      topPerformer,
      bottomPerformer,
      variance,
      networkEfficiency: Math.min(95, 85 + (100 - variance) / 2) // Cap at 95%
    };
  };

  const networkMetrics = calculateNetworkMetrics();

  // Get performance trend indicators
  const getPerformanceIndicator = (outletId: string) => {
    if (!childrenPerformance?.rankings) return null;
    
    const outlet = childrenPerformance.rankings.find(r => r.outlet_id === outletId);
    if (!outlet) return null;

    // Simple trend calculation based on position
    const position = childrenPerformance.rankings.findIndex(r => r.outlet_id === outletId) + 1;
    const total = childrenPerformance.rankings.length;
    
    if (position <= Math.ceil(total * 0.3)) {
      return { icon: TrendingUp, color: '#10b981', trend: 'improving' };
    } else if (position >= Math.floor(total * 0.7)) {
      return { icon: TrendingDown, color: '#ef4444', trend: 'declining' };
    } else {
      return { icon: Activity, color: '#f59e0b', trend: 'stable' };
    }
  };

  return (
    <div className="space-y-8">
      {/* Performance Header */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-[var(--text-primary)] mb-4 flex items-center gap-2">
          <BarChart3 className="w-6 h-6 text-[var(--color-primary)]" />
          {t('enterprise.network_performance')}
        </h2>
        <p className="text-[var(--text-secondary)] mb-6">
          {t('enterprise.performance_description')}
        </p>

        {/* Metric and Period Selectors */}
        <div className="flex flex-wrap gap-4 mb-6">
          <div className="flex items-center gap-2">
            <select
              value={selectedMetric}
              onChange={(e) => setSelectedMetric(e.target.value)}
              className="border border-[var(--border-primary)] rounded-md px-3 py-2 text-sm bg-[var(--input-bg)] text-[var(--text-primary)]"
            >
              <option value="sales">{t('enterprise.metrics.sales')}</option>
              <option value="inventory_value">{t('enterprise.metrics.inventory_value')}</option>
              <option value="order_frequency">{t('enterprise.metrics.order_frequency')}</option>
              <option value="on_time_delivery">{t('enterprise.metrics.on_time_delivery')}</option>
              <option value="inventory_turnover">{t('enterprise.metrics.inventory_turnover')}</option>
            </select>
          </div>

          <div className="flex items-center gap-2">
            <select
              value={selectedPeriod}
              onChange={(e) => setSelectedPeriod(Number(e.target.value))}
              className="border border-[var(--border-primary)] rounded-md px-3 py-2 text-sm bg-[var(--input-bg)] text-[var(--text-primary)]"
            >
              <option value={7}>{t('enterprise.last_7_days')}</option>
              <option value={30}>{t('enterprise.last_30_days')}</option>
              <option value={90}>{t('enterprise.last_90_days')}</option>
              <option value={180}>{t('enterprise.last_6_months')}</option>
            </select>
          </div>

          <div className="flex items-center gap-2 ml-auto">
            <Button
              variant={viewMode === 'chart' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('chart')}
            >
              <LineChart className="w-4 h-4 mr-2" />
              {t('enterprise.chart_view')}
            </Button>
            <Button
              variant={viewMode === 'cards' ? 'default' : 'outline'}
              size="sm"
              onClick={() => setViewMode('cards')}
            >
              <PieChart className="w-4 h-4 mr-2" />
              {t('enterprise.card_view')}
            </Button>
          </div>
        </div>
      </div>

      {/* Network Performance Summary */}
      {networkMetrics && (
        <div className="mb-8">
          <h3 className="text-xl font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
            <Target className="w-5 h-5 text-[var(--color-info)]" />
            {t('enterprise.network_summary')}
          </h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
            {/* Network Efficiency */}
            <Card>
              <CardHeader className="flex flex-row items-center justify-between pb-2">
                <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                  {t('enterprise.network_efficiency')}
                </CardTitle>
                <Activity className="w-5 h-5 text-[var(--color-primary)]" />
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-[var(--color-primary)]">
                  {networkMetrics.networkEfficiency}%
                </div>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('enterprise.operational_efficiency')}
                </p>
              </CardContent>
            </Card>

            {/* Performance Variance */}
            <Card>
              <CardHeader className="flex flex-row items-center justify-between pb-2">
                <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                  {t('enterprise.performance_variance')}
                </CardTitle>
                <BarChart3 className="w-5 h-5 text-[var(--color-warning)]" />
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-[var(--color-warning)]">
                  {networkMetrics.variance}%
                </div>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('enterprise.top_to_bottom_spread')}
                </p>
              </CardContent>
            </Card>

            {/* Average Performance */}
            <Card>
              <CardHeader className="flex flex-row items-center justify-between pb-2">
                <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                  {selectedMetric === 'sales' ? t('enterprise.avg_sales') : 
                   selectedMetric === 'inventory_value' ? t('enterprise.avg_inventory') : 
                   t('enterprise.avg_orders')}
                </CardTitle>
                <CheckCircle2 className="w-5 h-5 text-[var(--color-success)]" />
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-[var(--color-success)]">
                  {selectedMetric === 'sales' ? `${currencySymbol}${networkMetrics.avgSales.toLocaleString()}` :
                   selectedMetric === 'inventory_value' ? `${currencySymbol}${networkMetrics.avgInventory.toLocaleString()}` :
                   networkMetrics.avgOrders.toLocaleString()}
                </div>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('enterprise.per_outlet')}
                </p>
              </CardContent>
            </Card>

            {/* Total Outlets */}
            <Card>
              <CardHeader className="flex flex-row items-center justify-between pb-2">
                <CardTitle className="text-sm font-medium text-[var(--text-secondary)]">
                  {t('enterprise.total_outlets')}
                </CardTitle>
                <Building2 className="w-5 h-5 text-[var(--color-info)]" />
              </CardHeader>
              <CardContent>
                <div className="text-3xl font-bold text-[var(--color-info)]">
                  {networkMetrics.totalOutlets}
                </div>
                <p className="text-xs text-[var(--text-secondary)] mt-1">
                  {t('enterprise.locations_in_network')}
                </p>
              </CardContent>
            </Card>
          </div>
        </div>
      )}

      {/* Performance Insights */}
      {networkMetrics && (
        <div className="mb-8">
          <h3 className="text-xl font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
            <Award className="w-5 h-5 text-[var(--color-success)]" />
            {t('enterprise.performance_insights')}
          </h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {/* Top Performer */}
            <StatusCard
              id={`top-performer`}
              statusIndicator={{
                color: '#10b981',
                text: t('enterprise.top_performer'),
                icon: Award,
                isHighlight: true
              }}
              title={networkMetrics.topPerformer.outlet_name}
              subtitle={t('enterprise.best_in_network')}
              primaryValue={selectedMetric === 'sales' ? `${currencySymbol}${networkMetrics.topPerformer.metric_value.toLocaleString()}` :
                           selectedMetric === 'inventory_value' ? `${currencySymbol}${networkMetrics.topPerformer.metric_value.toLocaleString()}` :
                           networkMetrics.topPerformer.metric_value.toLocaleString()}
              primaryValueLabel={selectedMetric === 'sales' ? t('enterprise.sales') :
                                selectedMetric === 'inventory_value' ? t('enterprise.inventory_value') :
                                t('enterprise.orders')}
              secondaryInfo={{
                label: t('enterprise.performance_index'),
                value: `${Math.round((networkMetrics.topPerformer.metric_value / networkMetrics.avgSales) * 100)}%`
              }}
              progress={{
                label: t('enterprise.above_average'),
                percentage: Math.min(100, Math.round(((networkMetrics.topPerformer.metric_value - networkMetrics.avgSales) / networkMetrics.avgSales) * 100)),
                color: '#10b981'
              }}
              metadata={[
                `${t('enterprise.location')}: ${networkMetrics.topPerformer.outlet_name}`,
                `${t('enterprise.rank')}: #1`
              ]}
              actions={onOutletClick ? [{
                label: t('enterprise.view_details'),
                icon: BarChart3,
                variant: 'outline',
                onClick: () => onOutletClick(networkMetrics.topPerformer.outlet_id, networkMetrics.topPerformer.outlet_name),
                priority: 'primary'
              }] : []}
            />

            {/* Bottom Performer */}
            <StatusCard
              id={`bottom-performer`}
              statusIndicator={{
                color: '#ef4444',
                text: t('enterprise.needs_attention'),
                icon: AlertTriangle,
                isCritical: true
              }}
              title={networkMetrics.bottomPerformer.outlet_name}
              subtitle={t('enterprise.improvement_opportunity')}
              primaryValue={selectedMetric === 'sales' ? `${currencySymbol}${networkMetrics.bottomPerformer.metric_value.toLocaleString()}` :
                           selectedMetric === 'inventory_value' ? `${currencySymbol}${networkMetrics.bottomPerformer.metric_value.toLocaleString()}` :
                           networkMetrics.bottomPerformer.metric_value.toLocaleString()}
              primaryValueLabel={selectedMetric === 'sales' ? t('enterprise.sales') :
                                selectedMetric === 'inventory_value' ? t('enterprise.inventory_value') :
                                t('enterprise.orders')}
              secondaryInfo={{
                label: t('enterprise.performance_index'),
                value: `${Math.round((networkMetrics.bottomPerformer.metric_value / networkMetrics.avgSales) * 100)}%`
              }}
              progress={{
                label: t('enterprise.below_average'),
                percentage: Math.round(((networkMetrics.avgSales - networkMetrics.bottomPerformer.metric_value) / networkMetrics.avgSales) * 100),
                color: '#ef4444'
              }}
              metadata={[
                `${t('enterprise.location')}: ${networkMetrics.bottomPerformer.outlet_name}`,
                `${t('enterprise.rank')}: #${networkMetrics.totalOutlets}`
              ]}
              actions={onOutletClick ? [{
                label: t('enterprise.view_details'),
                icon: BarChart3,
                variant: 'outline',
                onClick: () => onOutletClick(networkMetrics.bottomPerformer.outlet_id, networkMetrics.bottomPerformer.outlet_name),
                priority: 'primary'
              }] : []}
            />

            {/* Network Insight */}
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center gap-3 mb-4">
                  <Award className="w-6 h-6 text-[var(--color-primary)]" />
                  <h3 className="text-lg font-semibold text-[var(--text-primary)]">{t('enterprise.network_insight')}</h3>
                </div>
                <div className="space-y-3">
                  {networkMetrics.variance < 20 ? (
                    <div className="flex items-center gap-2 text-[var(--color-success)]">
                      <CheckCircle2 className="w-5 h-5" />
                      <span className="text-sm">{t('enterprise.highly_balanced_network')}</span>
                    </div>
                  ) : networkMetrics.variance < 40 ? (
                    <div className="flex items-center gap-2 text-[var(--color-warning)]">
                      <AlertTriangle className="w-5 h-5" />
                      <span className="text-sm">{t('enterprise.moderate_variation')}</span>
                    </div>
                  ) : (
                    <div className="flex items-center gap-2 text-[var(--color-danger)]">
                      <AlertTriangle className="w-5 h-5" />
                      <span className="text-sm">{t('enterprise.high_variation')}</span>
                    </div>
                  )}

                  <p className="text-sm text-[var(--text-secondary)] mt-3">
                    {networkMetrics.variance < 20 
                      ? t('enterprise.balanced_network_description')
                      : networkMetrics.variance < 40 
                        ? t('enterprise.moderate_variation_description')
                        : t('enterprise.high_variation_description')}
                  </p>

                  {networkMetrics.variance >= 40 && (
                    <Button 
                      onClick={() => setSelectedMetric('sales')}
                      variant="outline"
                      size="sm"
                      className="mt-3"
                    >
                      {t('enterprise.analyze_performance')}
                    </Button>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      )}

      {/* Main Performance Visualization */}
      <div className="mb-8">
        <h3 className="text-xl font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
          <BarChart3 className="w-5 h-5 text-[var(--color-primary)]" />
          {t('enterprise.outlet_comparison')}
        </h3>

        {viewMode === 'chart' ? (
          <Card className="h-full">
            <CardContent className="p-6">
              {childrenPerformance && childrenPerformance.rankings ? (
                <PerformanceChart
                  data={childrenPerformance.rankings}
                  metric={selectedMetric}
                  period={selectedPeriod}
                  onOutletClick={onOutletClick}
                  showTrendIndicators={true}
                />
              ) : (
                <div className="h-96 flex items-center justify-center text-[var(--text-secondary)]">
                  {isLoading ? t('enterprise.loading_performance') : t('enterprise.no_performance_data')}
                </div>
              )}
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {childrenPerformance?.rankings?.map((outlet, index) => {
              const performanceIndicator = getPerformanceIndicator(outlet.outlet_id);
              
              return (
                <StatusCard
                  key={outlet.outlet_id}
                  id={outlet.outlet_id}
                  statusIndicator={performanceIndicator ? {
                    color: performanceIndicator.color,
                    text: performanceIndicator.trend === 'improving' ? t('enterprise.improving') :
                          performanceIndicator.trend === 'declining' ? t('enterprise.declining') : t('enterprise.stable'),
                    icon: performanceIndicator.icon
                  } : {
                    color: '#6b7280',
                    text: t('enterprise.no_data'),
                    icon: Clock
                  }}
                  title={outlet.outlet_name}
                  subtitle={`#${index + 1} ${t('enterprise.of')} ${childrenPerformance.rankings.length}`}
                  primaryValue={selectedMetric === 'sales' ? `${currencySymbol}${outlet.metric_value.toLocaleString()}` :
                               selectedMetric === 'inventory_value' ? `${currencySymbol}${outlet.metric_value.toLocaleString()}` :
                               outlet.metric_value.toLocaleString()}
                  primaryValueLabel={selectedMetric === 'sales' ? t('enterprise.sales') :
                                    selectedMetric === 'inventory_value' ? t('enterprise.inventory_value') :
                                    t('enterprise.orders')}
                  secondaryInfo={{
                    label: t('enterprise.performance_index'),
                    value: `${Math.round((outlet.metric_value / networkMetrics.avgSales) * 100)}%`
                  }}
                  progress={{
                    label: t('enterprise.of_network_avg'),
                    percentage: Math.round((outlet.metric_value / networkMetrics.avgSales) * 100),
                    color: performanceIndicator?.color || '#6b7280'
                  }}
                  metadata={[
                    `${t('enterprise.location_id')}: ${outlet.outlet_id}`,
                    `${t('enterprise.period')}: ${selectedPeriod} ${t('enterprise.days')}`
                  ]}
                  actions={onOutletClick ? [{
                    label: t('enterprise.view_details'),
                    icon: BarChart3,
                    variant: 'outline',
                    onClick: () => onOutletClick(outlet.outlet_id, outlet.outlet_name),
                    priority: 'primary'
                  }] : []}
                />
              );
            })}
          </div>
        )}
      </div>

      {/* Performance Recommendations */}
      {networkMetrics && networkMetrics.variance >= 30 && (
        <div className="mb-8">
          <h3 className="text-xl font-semibold text-[var(--text-primary)] mb-4 flex items-center gap-2">
            <TrendingUp className="w-5 h-5 text-[var(--color-success)]" />
            {t('enterprise.performance_recommendations')}
          </h3>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            <Card>
              <CardContent className="p-6">
                <div className="flex items-center gap-3 mb-4">
                  <Award className="w-6 h-6 text-[var(--color-primary)]" />
                  <h3 className="text-lg font-semibold text-[var(--text-primary)]">{t('enterprise.best_practices')}</h3>
                </div>
                <p className="text-[var(--text-secondary)] mb-4">
                  {t('enterprise.learn_from_top_performer', { 
                    name: networkMetrics.topPerformer.outlet_name 
                  })}
                </p>
                <Button variant="outline" size="sm">
                  {t('enterprise.schedule_knowledge_sharing')}
                </Button>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center gap-3 mb-4">
                  <AlertTriangle className="w-6 h-6 text-[var(--color-warning)]" />
                  <h3 className="text-lg font-semibold text-[var(--text-primary)]">{t('enterprise.targeted_improvement')}</h3>
                </div>
                <p className="text-[var(--text-secondary)] mb-4">
                  {t('enterprise.focus_on_bottom_performer', { 
                    name: networkMetrics.bottomPerformer.outlet_name 
                  })}
                </p>
                <Button variant="outline" size="sm">
                  {t('enterprise.create_improvement_plan')}
                </Button>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-6">
                <div className="flex items-center gap-3 mb-4">
                  <Target className="w-6 h-6 text-[var(--color-success)]" />
                  <h3 className="text-lg font-semibold text-[var(--text-primary)]">{t('enterprise.network_goal')}</h3>
                </div>
                <p className="text-[var(--text-secondary)] mb-4">
                  {t('enterprise.reduce_variance_goal', { 
                    current: networkMetrics.variance,
                    target: Math.max(10, networkMetrics.variance - 15)
                  })}
                </p>
                <Button variant="outline" size="sm">
                  {t('enterprise.set_network_targets')}
                </Button>
              </CardContent>
            </Card>
          </div>
        </div>
      )}
    </div>
  );
};

export default NetworkPerformanceTab;