import React from 'react';
import { Organization } from '@/types.ts';
import { useTranslation } from '@/hooks/useI18n.tsx';
import { useDirectSymbiosis } from '@/hooks/useDirectSymbiosis.ts';
import MatchCard from '@/components/organization/MatchCard.tsx';
import { Grid, Stack } from '@/components/ui/layout';

interface DirectMatchesDisplayProps {
  organization: Organization;
  onSelectOrg: (org: Organization) => void;
}

const DirectMatchesDisplay = ({ organization, onSelectOrg }: DirectMatchesDisplayProps) => {
  const { t } = useTranslation();
  const { providers, consumers } = useDirectSymbiosis(organization);
  // Ensure arrays and check lengths safely
  const safeProviders = Array.isArray(providers) ? providers : [];
  const safeConsumers = Array.isArray(consumers) ? consumers : [];
  const hasMatches = safeProviders.length > 0 || safeConsumers.length > 0;

  if (!hasMatches) {
    return (
      <p className="text-muted-foreground text-center py-8">
        {t('organizationPage.directSymbiosis.noMatches')}
      </p>
    );
  }

  return (
    <Grid cols={{ md: 2 }} gap="3xl" className="max-h-96 overflow-y-auto">
      <Stack spacing="sm">
        <h3 className="font-semibold text-lg text-success">
          {t('organizationPage.directSymbiosis.fulfillsNeeds')}
        </h3>
        {safeProviders.length > 0 ? (
          safeProviders.map((match, index) => (
            <MatchCard
              key={`prov-${index}`}
              match={match}
              onSelectOrg={onSelectOrg}
              type="provider"
            />
          ))
        ) : (
          <p className="text-sm text-muted-foreground pt-2">
            {t('organizationPage.directSymbiosis.noMatches')}
          </p>
        )}
      </Stack>
      <Stack spacing="sm">
        <h3 className="font-semibold text-lg text-destructive">
          {t('organizationPage.directSymbiosis.consumesOffers')}
        </h3>
        {safeConsumers.length > 0 ? (
          safeConsumers.map((match, index) => (
            <MatchCard
              key={`cons-${index}`}
              match={match}
              onSelectOrg={onSelectOrg}
              type="consumer"
            />
          ))
        ) : (
          <p className="text-sm text-muted-foreground pt-2">
            {t('organizationPage.directSymbiosis.noMatches')}
          </p>
        )}
      </Stack>
    </Grid>
  );
};

export default React.memo(DirectMatchesDisplay);
