import React from 'react';
import { WebIntelligenceResult } from '@/types.ts';
import { useTranslation } from '@/hooks/useI18n.tsx';
import IntelligenceModule from '@/components/organization/IntelligenceModule.tsx';

interface WebIntelTabProps {
  webIntelResult: WebIntelligenceResult | null;
  isFetchingWebIntel: boolean;
  webIntelError: string | null;
  handleFetchWebIntelligence: () => void;
}

const WebIntelTab: React.FC<WebIntelTabProps> = ({
  webIntelResult,
  isFetchingWebIntel,
  webIntelError,
  handleFetchWebIntelligence,
}) => {
  const { t } = useTranslation();

  return (
    <IntelligenceModule
      description={t('mapSidebar.details.webIntelDescription')}
      buttonText={t('mapSidebar.details.fetchWebIntelButton')}
      onAction={handleFetchWebIntelligence}
      isPending={isFetchingWebIntel}
      error={webIntelError}
    >
      {webIntelResult && (
        <div className="mt-4 text-left text-base space-y-3 max-h-72 overflow-y-auto">
          {webIntelResult.text && <p>{webIntelResult.text}</p>}
          {Array.isArray(webIntelResult.sources) && webIntelResult.sources.length > 0 && (
            <div>
              <h5 className="font-semibold mb-2">{t('mapSidebar.details.webIntelSources')}</h5>
              <ul className="space-y-1 list-disc list-inside">
                {webIntelResult.sources
                  .filter((source) => source?.uri) // Filter out invalid sources
                  .map((source) => (
                    <li key={source.uri}>
                      <a
                        href={source.uri}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-primary hover:underline text-sm truncate"
                      >
                        {source.title || source.uri}
                      </a>
                    </li>
                  ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </IntelligenceModule>
  );
};

export default React.memo(WebIntelTab);
