'use client';

import { FC } from 'react';
import { motion } from 'framer-motion';

interface CityPosition {
  city: string;
  position: number | null;
  page?: number | null;
  positionOnPage?: number | null;
}

interface ComparisonData {
  city: string;
  myPosition: CityPosition;
  competitorPosition?: CityPosition;
}

interface CityPositionsTableProps {
  positions: CityPosition[];
  competitorPositions?: CityPosition[];
  isComparisonMode?: boolean;
  myArticleId?: string;
  competitorArticleId?: string;
}

const CityPositionsTable: FC<CityPositionsTableProps> = ({ 
  positions, 
  competitorPositions, 
  isComparisonMode = false,
  myArticleId,
  competitorArticleId 
}) => {
  // Подготавливаем данные для сравнения
  const comparisonData: ComparisonData[] = positions.map(myPos => {
    const competitorPos = competitorPositions?.find(cp => cp.city === myPos.city);
    return {
      city: myPos.city,
      myPosition: myPos,
      competitorPosition: competitorPos
    };
  });

  return (
    <div
      className="bg-white/40 backdrop-blur-md rounded-xl border border-white/30 shadow-lg shadow-purple-900/5 p-3 h-full flex flex-col"
      style={{ maxHeight: '100%' }}
    >
      {/* Заголовок таблицы */}
      <div className="mb-2 flex items-center justify-between">
        <h3 className="text-gray-800 font-medium">
          {isComparisonMode ? 'Сравнение позиций' : 'Позиции в городах'}
        </h3>
        {isComparisonMode && (
          <div className="text-xs text-gray-600">
            <span className="inline-block w-2 h-2 bg-blue-500 rounded-full mr-1"></span>
            {myArticleId}
            <span className="mx-2">vs</span>
            <span className="inline-block w-2 h-2 bg-red-500 rounded-full mr-1"></span>
            {competitorArticleId}
          </div>
        )}
      </div>

      {/* Заголовки столбцов */}
      <div className="grid grid-cols-3 mb-2 pb-2 border-b border-white/30 select-none pointer-events-none text-sm">
        <div className="text-gray-800 font-medium text-left">Город</div>
        <div className="text-gray-800 font-medium text-center">Страница</div>
        <div className="text-gray-800 font-medium text-center">Позиция</div>
      </div>

      {/* Контейнер со скроллом и фиксированной высотой */}
      <div
        className="overflow-auto flex-1"
        style={{
          height: 'calc(100% - 80px)',
          minHeight: '120px',
          maxHeight: 'calc(100% - 80px)',
        }}
      >
        {comparisonData.length > 0 ? (
          <div className="h-auto">
            {comparisonData.map((item, index) => (
              <motion.div
                key={`${item.city}-${index}`}
                initial={{ opacity: 0, y: 5 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.05 }}
                className={`grid grid-cols-3 py-1.5 text-sm ${
                  index !== comparisonData.length - 1
                    ? 'border-b border-white/20'
                    : ''
                } hover:bg-white/30 transition-colors duration-200 select-none`}
              >
                <div className="text-left font-medium pl-2 truncate">
                  {item.city}
                </div>
                
                {/* Колонка Страница */}
                <div className="text-center flex justify-center items-center gap-1">
                  {/* Моя страница */}
                  {item.myPosition.page ? (
                    <span className="inline-flex items-center justify-center w-8 h-5 bg-blue-100 text-blue-800 rounded-full text-xs font-medium">
                      {item.myPosition.page}
                    </span>
                  ) : (
                    <span className="inline-flex items-center justify-center w-8 h-5 bg-gray-100 text-gray-500 rounded-full text-xs">
                      —
                    </span>
                  )}
                  
                  {/* Страница конкурента (только в режиме сравнения) */}
                  {isComparisonMode && (
                    item.competitorPosition?.page ? (
                      <span className="inline-flex items-center justify-center w-8 h-5 bg-red-100 text-red-800 rounded-full text-xs font-medium">
                        {item.competitorPosition.page}
                      </span>
                    ) : (
                      <span className="inline-flex items-center justify-center w-8 h-5 bg-gray-100 text-gray-500 rounded-full text-xs">
                        —
                      </span>
                    )
                  )}
                </div>
                
                {/* Колонка Позиция */}
                <div className="text-center flex justify-center items-center gap-1">
                  {/* Моя позиция */}
                  {item.myPosition.positionOnPage ? (
                    <span className="inline-flex items-center justify-center w-8 h-5 bg-blue-100 text-blue-800 rounded-full text-xs font-medium">
                      {item.myPosition.positionOnPage}
                    </span>
                  ) : (
                    <span className="inline-flex items-center justify-center w-8 h-5 bg-gray-100 text-gray-500 rounded-full text-xs">
                      —
                    </span>
                  )}
                  
                  {/* Позиция конкурента (только в режиме сравнения) */}
                  {isComparisonMode && (
                    item.competitorPosition?.positionOnPage ? (
                      <span className="inline-flex items-center justify-center w-8 h-5 bg-red-100 text-red-800 rounded-full text-xs font-medium">
                        {item.competitorPosition.positionOnPage}
                      </span>
                    ) : (
                      <span className="inline-flex items-center justify-center w-8 h-5 bg-gray-100 text-gray-500 rounded-full text-xs">
                        —
                      </span>
                    )
                  )}
                </div>
              </motion.div>
            ))}
          </div>
        ) : (
          <div className="flex items-center justify-center h-full text-gray-500 text-sm">
            Нет данных о позициях
          </div>
        )}
      </div>

      {/* Статистика внизу */}
      <div className="mt-2 pt-2 border-t border-white/30 text-xs text-gray-600">
        <div className="flex justify-between">
          <span>Всего городов: {comparisonData.length}</span>
          <span>
            Найдено: {comparisonData.filter(item => item.myPosition.position !== null).length}
            {isComparisonMode && competitorPositions && (
              <>
                {' / '}
                {comparisonData.filter(item => item.competitorPosition?.position !== null).length}
              </>
            )}
          </span>
        </div>
        {isComparisonMode && (
          <div className="mt-1 text-center">
            <span className="inline-block w-2 h-2 bg-blue-500 rounded-full mr-1"></span>
            <span className="text-xs">Мой товар</span>
            <span className="mx-3"></span>
            <span className="inline-block w-2 h-2 bg-red-500 rounded-full mr-1"></span>
            <span className="text-xs">Конкурент</span>
          </div>
        )}
      </div>
    </div>
  );
};

export default CityPositionsTable;
