import React, { useMemo } from 'react';
import { getSectorDisplay } from '@/constants.tsx';
import { useMapActions, useMapInteraction } from '@/contexts/MapContexts.tsx';
import { useTranslation } from '@/hooks/useI18n.tsx';
import { mapBackendSectorToTranslationKey } from '@/lib/sector-mapper.ts';
import Button from '@/components/ui/Button.tsx';
import VerifiedBadge from '@/components/ui/VerifiedBadge.tsx';

const SidebarPreview: React.FC = () => {
  const { t } = useTranslation();
  const { selectedOrg } = useMapInteraction();
  const { handleViewOrganization } = useMapActions();

  if (!selectedOrg) return null;

  const sectorDisplay = getSectorDisplay(selectedOrg.Sector);

  return (
    <div className="p-4 space-y-4 h-full overflow-y-auto scrollbar-none flex flex-col">
      <div className="flex-1 space-y-4">
        <div className="flex items-start gap-4">
          <div className="h-16 w-16 rounded-lg flex items-center justify-center shrink-0 bg-muted overflow-hidden border">
            {selectedOrg.LogoURL ? (
              <img
                src={selectedOrg.LogoURL}
                alt={`${selectedOrg.Name} logo`}
                className="w-full h-full object-cover"
                loading="lazy"
                decoding="async"
                onError={(e) => {
                  // Hide broken images gracefully
                  (e.target as HTMLImageElement).style.display = 'none';
                }}
              />
            ) : (
              sector && (
                <div
                  className={`w-full h-full flex items-center justify-center bg-sector-${sectorDisplay.colorKey}`}
                >
                  {React.cloneElement(sectorDisplay.icon, {
                    className: 'h-8 w-8 text-primary-foreground',
                  })}
                </div>
              )
            )}
          </div>
          <div className="flex-1 min-w-0">
            <h3 className="font-semibold text-lg">{selectedOrg.Name}</h3>
            {sector && (
              <p className="text-sm text-muted-foreground">{t(sectorDisplay.nameKey)}</p>
            )}
            {selectedOrg.Address && (
              <p className="text-xs text-muted-foreground mt-1">{selectedOrg.Address}</p>
            )}
            {selectedOrg.Verified && (
              <div className="mt-1">
                <VerifiedBadge />
              </div>
            )}
          </div>
        </div>

        <p className="text-sm line-clamp-3 bg-muted/50 p-3 rounded-md">{selectedOrg.Description}</p>
      </div>

      <div className="shrink-0 space-y-2">
        <Button className="w-full" onClick={() => handleViewOrganization(selectedOrg)}>
          {t('mapSidebar.details.viewMore')}
        </Button>
      </div>
    </div>
  );
};

export default React.memo(SidebarPreview);
