import React, { useState } from 'react';
import { useQuery } from '@apollo/client';
import { GET_LAXIMO_QUICK_DETAIL } from '@/lib/graphql/laximo';
import BrandSelectionModal from '../BrandSelectionModal';

interface VinQuickProps {
  quickGroup: any;
  catalogCode: string;
  vehicleId: string;
  ssd: string;
  onBack: () => void;
  onNodeSelect: (unit: any) => void;
}

const VinQuick: React.FC<VinQuickProps> = ({ quickGroup, catalogCode, vehicleId, ssd, onBack, onNodeSelect }) => {
  const { data, loading, error } = useQuery(GET_LAXIMO_QUICK_DETAIL, {
    variables: {
      catalogCode,
      vehicleId,
      quickGroupId: quickGroup.quickgroupid,
      ssd
    },
    skip: !quickGroup || !quickGroup.quickgroupid
  });
  const quickDetail = data?.laximoQuickDetail;



  const [isBrandModalOpen, setIsBrandModalOpen] = useState(false);
  const [selectedDetail, setSelectedDetail] = useState<any>(null);

  const handleUnitClick = (unit: any) => {
    onNodeSelect({
      ...unit,
      unitid: unit.unitid,
      name: unit.name,
      catalogCode,
      vehicleId,
      ssd: unit.ssd || ssd  // Используем SSD узла, а не родительский
    });
  };
  const handleDetailClick = (detail: any) => {
    setSelectedDetail(detail);
    setIsBrandModalOpen(true);
  };
  const handleCloseBrandModal = () => {
    setIsBrandModalOpen(false);
    setSelectedDetail(null);
  };

  return (
    <div className="w-full">
      {/* <button onClick={onBack} className="mb-4 px-4 py-2 bg-gray-200 rounded self-start">Назад</button> */}
      {loading ? (
        <div className="text-center py-4">Загружаем детали...</div>
      ) : error ? (
        <div className="text-red-600 py-4">Ошибка загрузки деталей: {error.message}</div>
      ) : quickDetail && quickDetail.units ? (
        quickDetail.units.map((unit: any) => (
          <div key={unit.unitid} className="w-layout-vflex flex-block-14-copy-copy">
            <div className="knotinfo">
              {unit.imageurl || unit.largeimageurl ? (
                <img
                  src={unit.largeimageurl ? unit.largeimageurl.replace('%size%', '250') : unit.imageurl.replace('%size%', '250')}
                  alt={unit.name}
                  className="image-26"
                  onError={e => { (e.currentTarget as HTMLImageElement).src = '/images/image-44.jpg'; }}
                />
              ) : (
                <img src="/images/image-44.jpg" alt="Нет изображения" className="image-26" />
              )}
            </div>
            <div className="knot-img">
              <h1 className="heading-19">{unit.name}</h1>
              
                {unit.details && unit.details.length > 0 && unit.details.map((detail: any) => (
                  <div className="w-layout-hflex flex-block-115" key={detail.detailid}>
                    <div className="oemnuber">{detail.oem}</div>
                    <div className="partsname">{detail.name}</div>
                    <a href="#" className="button-3 w-button" onClick={e => { e.preventDefault(); handleDetailClick(detail); }}>Показать цены</a>
                  </div>
                ))}
        
              <a href="#" className="showallparts w-button" onClick={e => { e.preventDefault(); handleUnitClick(unit); }}>Подробнее</a>
            </div>
          </div>
        ))
      ) : (
        <div className="text-center text-gray-500 py-4">Нет деталей для этой группы</div>
      )}
      {isBrandModalOpen && selectedDetail && (
        <BrandSelectionModal
          isOpen={isBrandModalOpen}
          onClose={handleCloseBrandModal}
          articleNumber={selectedDetail.oem}
          detailName={selectedDetail.name}
        />
      )}
    </div>
  );
};

export default VinQuick; 