import React, { useMemo } from 'react';
import { useSupplyDemandAnalysis } from '@/hooks/api/useAnalyticsAPI.ts';
import { useTranslation } from '@/hooks/useI18n.tsx';
import type { ItemCount } from '@/services/analytics-api.ts';

const SupplyChainAnalysis = () => {
  const { t } = useTranslation();
  const { data: supplyDemand } = useSupplyDemandAnalysis();

  // Helper function to render resource list
  const ResourceList = React.memo(
    ({ title, data, barColor }: { title: string; data: ItemCount[]; barColor: string }) => {
      // Memoize maxValue calculation
      const maxValue = useMemo(() => (data.length > 0 ? data[0].count : 0), [data]);

      return (
        <div>
          <h3 className="text-base font-semibold mb-2">{title}</h3>
          {data.length > 0 ? (
            <ul className="space-y-3">
              {data.map(({ item, count }) => (
                <li key={item}>
                  <div className="flex justify-between items-center text-sm mb-1">
                    <span className="truncate pr-2">{item}</span>
                    <span className="font-medium text-muted-foreground">{count}</span>
                  </div>
                  <div className="w-full bg-muted rounded-full h-1.5">
                    <div
                      className={`${barColor} h-1.5 rounded-full`}
                      style={{ width: `${(count / maxValue) * 100}%` }}
                    />
                  </div>
                </li>
              ))}
            </ul>
          ) : (
            <p className="text-sm text-muted-foreground">{t('heritage.noData')}</p>
          )}
        </div>
      );
    }
  );
  ResourceList.displayName = 'ResourceList';

  // Memoize arrays to prevent recreation
  const topNeeds = useMemo(
    () => (Array.isArray(supplyDemand?.top_needs) ? supplyDemand.top_needs : []),
    [supplyDemand?.top_needs]
  );
  const topOffers = useMemo(
    () => (Array.isArray(supplyDemand?.top_offers) ? supplyDemand.top_offers : []),
    [supplyDemand?.top_offers]
  );

  return (
    <div className="space-y-6">
      <ResourceList title={t('adminPage.topNeeds')} data={topNeeds} barColor="bg-destructive" />
      <ResourceList title={t('adminPage.topOffers')} data={topOffers} barColor="bg-success" />
    </div>
  );
};

export default React.memo(SupplyChainAnalysis);
