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

interface AIAnalysisTabProps {
  symbiosisResult: SymbiosisMatch[] | null;
  isAnalyzing: boolean;
  analysisError: string | null;
  handleAnalyzeSymbiosis: () => void;
  onSelectOrg: (org: Organization) => void;
}

const AIAnalysisTab: React.FC<AIAnalysisTabProps> = ({
  symbiosisResult,
  isAnalyzing,
  analysisError,
  handleAnalyzeSymbiosis,
  onSelectOrg,
}) => {
  const { t } = useTranslation();

  return (
    <IntelligenceModule
      description={t('mapSidebar.details.symbiosisDescription')}
      buttonText={t('mapSidebar.details.analyzeButton')}
      onAction={handleAnalyzeSymbiosis}
      isPending={isAnalyzing}
      error={analysisError}
    >
      {Array.isArray(symbiosisResult) && symbiosisResult.length > 0 && (
        <div className="mt-4 text-left">
          <h4 className="font-semibold text-base mb-2">
            {t('mapSidebar.details.analysisResultsTitle')}
          </h4>
          <ul className="space-y-2 max-h-72 overflow-y-auto">
            {symbiosisResult
              .filter((match) => match?.id && match?.org) // Filter out invalid matches
              .map((match) => (
                <li
                  key={match.id}
                  className="p-3 rounded-lg bg-muted text-sm cursor-pointer hover:bg-muted/80 transition-colors"
                  onClick={() => match.org && onSelectOrg(match.org)}
                >
                  <p className="font-bold">{match.org?.name || t('common.unknown')}</p>
                  {match.reason && <p className="text-muted-foreground mt-1">{match.reason}</p>}
                </li>
              ))}
          </ul>
        </div>
      )}
    </IntelligenceModule>
  );
};

export default React.memo(AIAnalysisTab);
