/*
 * Performance Chart Component for Enterprise Dashboard
 * Shows performance ranking of child outlets with clickable names
 */

import React from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/Card';
import { Badge } from '../ui/Badge';
import { BarChart3, TrendingUp, TrendingDown, ArrowUp, ArrowDown, ExternalLink, Package, ShoppingCart } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useTenantCurrency } from '../../hooks/useTenantCurrency';

interface PerformanceDataPoint {
  rank: number;
  tenant_id: string;
  outlet_name: string;
  metric_value: number;
}

interface PerformanceChartProps {
  data: PerformanceDataPoint[];
  metric: string;
  period: number;
  onOutletClick?: (tenantId: string, outletName: string) => void;
}

const PerformanceChart: React.FC<PerformanceChartProps> = ({
  data = [],
  metric,
  period,
  onOutletClick
}) => {
  const { t } = useTranslation('dashboard');
  const { currencySymbol } = useTenantCurrency();

  // Get metric info
  const getMetricInfo = () => {
    switch (metric) {
      case 'sales':
        return {
          icon: <TrendingUp className="w-4 h-4" />,
          label: t('enterprise.metrics.sales'),
          unit: currencySymbol,
          format: (val: number) => val.toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
        };
      case 'inventory_value':
        return {
          icon: <Package className="w-4 h-4" />,
          label: t('enterprise.metrics.inventory_value'),
          unit: currencySymbol,
          format: (val: number) => val.toLocaleString('es-ES', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
        };
      case 'order_frequency':
        return {
          icon: <ShoppingCart className="w-4 h-4" />,
          label: t('enterprise.metrics.order_frequency'),
          unit: '',
          format: (val: number) => Math.round(val).toString()
        };
      default:
        return {
          icon: <BarChart3 className="w-4 h-4" />,
          label: metric,
          unit: '',
          format: (val: number) => val.toString()
        };
    }
  };

  const metricInfo = getMetricInfo();

  // Calculate max value for bar scaling
  const maxValue = data.length > 0 ? Math.max(...data.map(item => item.metric_value), 1) : 1;

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <div className="flex items-center gap-2">
          <BarChart3 className="w-5 h-5 text-blue-600" />
          <CardTitle>{t('enterprise.outlet_performance')}</CardTitle>
        </div>
        <div className="text-sm text-gray-500">
          {t('enterprise.performance_based_on_period', {
            metric: t(`enterprise.metrics.${metric}`) || metric,
            period
          })}
        </div>
      </CardHeader>
      <CardContent>
        {data.length > 0 ? (
          <div className="space-y-4">
            {data.map((item, index) => {
              const percentage = (item.metric_value / maxValue) * 100;
              const isTopPerformer = index === 0;

              return (
                <div key={item.tenant_id} className="space-y-2">
                  <div className="flex justify-between items-center">
                    <div className="flex items-center gap-3">
                      <div
                        className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-medium"
                        style={isTopPerformer ? {
                          backgroundColor: 'var(--color-warning-light, #fef3c7)',
                          color: 'var(--color-warning-dark, #92400e)',
                          borderColor: 'var(--color-warning, #fbbf24)',
                          borderWidth: '1px',
                          borderStyle: 'solid'
                        } : {
                          backgroundColor: 'var(--bg-tertiary, #f1f5f9)',
                          color: 'var(--text-secondary, #475569)'
                        }}>
                        {item.rank}
                      </div>
                      {onOutletClick ? (
                        <button
                          onClick={() => onOutletClick(item.tenant_id, item.outlet_name)}
                          className="font-medium text-[var(--color-primary)] hover:text-[var(--color-primary-dark)] hover:underline flex items-center gap-1.5 transition-colors"
                        >
                          {item.outlet_name}
                          <ExternalLink className="w-3.5 h-3.5" />
                        </button>
                      ) : (
                        <span className="font-medium">{item.outlet_name}</span>
                      )}
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="font-semibold">
                        {metricInfo.unit}{metricInfo.format(item.metric_value)}
                      </span>
                      {isTopPerformer && (
                        <Badge variant="secondary" className="bg-yellow-50 text-yellow-800">
                          {t('enterprise.top_performer')}
                        </Badge>
                      )}
                    </div>
                  </div>
                  <div className="w-full rounded-full h-3" style={{ backgroundColor: 'var(--bg-quaternary)' }}>
                    <div
                      className="h-3 rounded-full transition-all duration-500 relative overflow-hidden"
                      style={{
                        width: `${percentage}%`,
                        background: isTopPerformer
                          ? 'linear-gradient(90deg, var(--chart-secondary) 0%, var(--chart-primary) 100%)'
                          : 'var(--chart-secondary)'
                      }}
                    >
                      {/* Shimmer effect for top performer */}
                      {isTopPerformer && (
                        <div
                          className="absolute inset-0 animate-shimmer"
                          style={{
                            background: 'linear-gradient(90deg, transparent 0%, rgba(255,255,255,0.4) 50%, transparent 100%)',
                            backgroundSize: '200% 100%',
                          }}
                        />
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="text-center py-8 text-gray-500">
            <BarChart3 className="w-12 h-12 mx-auto mb-4 text-gray-300" />
            <p>{t('enterprise.no_performance_data')}</p>
            <p className="text-sm text-gray-400 mt-1">
              {t('enterprise.performance_based_on_period', {
                metric: t(`enterprise.metrics.${metric}`) || metric,
                period
              })}
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
};

export default PerformanceChart;