import React, { useState, useEffect, useRef } from 'react';
import { useQuery, useLazyQuery } from '@apollo/client';
import { GET_LAXIMO_CATEGORIES, GET_LAXIMO_QUICK_GROUPS, GET_LAXIMO_UNITS } from '@/lib/graphql/laximo';

interface VinCategoryProps {
  catalogCode: string;
  vehicleId: string;
  ssd: string;
  onNodeSelect?: (node: any) => void;
  activeTab: 'uzly' | 'manufacturer';
  onQuickGroupSelect?: (group: any) => void;
}

const VinCategory: React.FC<VinCategoryProps> = ({ catalogCode, vehicleId, ssd, onNodeSelect, activeTab, onQuickGroupSelect }) => {
  const [selectedCategory, setSelectedCategory] = useState<any>(null);
  const [unitsByCategory, setUnitsByCategory] = useState<{ [key: string]: any[] }>({});
  const lastCategoryIdRef = useRef<string | null>(null);

  // Сброс выбранной категории при смене вкладки
  useEffect(() => {
    setSelectedCategory(null);
  }, [activeTab]);

  // Запрос для "Узлы"
  const { data: categoriesData, loading: categoriesLoading, error: categoriesError } = useQuery(GET_LAXIMO_CATEGORIES, {
    variables: { catalogCode, vehicleId, ssd },
    skip: !catalogCode || vehicleId === undefined || vehicleId === null || activeTab !== 'uzly',
    errorPolicy: 'all'
  });

  // Запрос для получения units (подкатегорий) в режиме "Узлы"
  const [getUnits] = useLazyQuery(GET_LAXIMO_UNITS, {
    onCompleted: (data) => {
      console.log('Units loaded:', data);
      if (data && data.laximoUnits && lastCategoryIdRef.current) {
        console.log('Setting units for category:', lastCategoryIdRef.current, data.laximoUnits);
        setUnitsByCategory(prev => ({
          ...prev,
          [lastCategoryIdRef.current!]: data.laximoUnits || []
        }));
      }
    },
    onError: (error) => {
      console.error('Error loading units:', error);
    }
  });

  // Запрос для "От производителя"
  const { data: quickGroupsData, loading: quickGroupsLoading, error: quickGroupsError } = useQuery(GET_LAXIMO_QUICK_GROUPS, {
    variables: { catalogCode, vehicleId, ssd },
    skip: !catalogCode || vehicleId === undefined || vehicleId === null || activeTab !== 'manufacturer',
    errorPolicy: 'all'
  });

  const categories = activeTab === 'uzly' ? (categoriesData?.laximoCategories || []) : (quickGroupsData?.laximoQuickGroups || []);
  const loading = activeTab === 'uzly' ? categoriesLoading : quickGroupsLoading;
  const error = activeTab === 'uzly' ? categoriesError : quickGroupsError;

  const handleBack = () => {
    setSelectedCategory(null);
  };

  const handleCategoryClick = (category: any) => {
    if (activeTab === 'manufacturer') {
      if (category.children && category.children.length > 0) {
        setSelectedCategory(category);
      } else if (category.link && onQuickGroupSelect) {
        onQuickGroupSelect(category);
      } else if (onNodeSelect) {
        onNodeSelect(category);
      }
    } else {
      // Логика для вкладки "Узлы"
      if (category.children && category.children.length > 0) {
        setSelectedCategory(category);
      } else {
        // Если нет children, грузим units (подкатегории)
        const categoryId = category.categoryid || category.quickgroupid || category.id;
        if (!unitsByCategory[categoryId]) {
          lastCategoryIdRef.current = categoryId;
          console.log('Loading units for category:', { categoryId, category });
          getUnits({ 
            variables: { 
              catalogCode, 
              vehicleId, 
              ssd, 
              categoryId 
            } 
          });
        }
        setSelectedCategory(category);
      }
    }
  };

  const handleSubcategoryClick = (subcat: any) => {
    if (activeTab === 'uzly' && onNodeSelect) {
      // Для режима "Узлы" при клике на подкатегорию открываем KnotIn
      onNodeSelect({
        ...subcat,
        unitid: subcat.unitid || subcat.categoryid || subcat.quickgroupid || subcat.id
      });
    } else {
      handleCategoryClick(subcat);
    }
  };

  if (loading) return <div>Загрузка категорий...</div>;
  if (error) return <div style={{ color: "red" }}>Ошибка: {error.message}</div>;

  // Определяем, какие подкатегории показывать
  let subcategories: any[] = [];
  if (selectedCategory) {
    if (activeTab === 'manufacturer') {
      // Для вкладки "От производителя" используем children
      subcategories = selectedCategory.children || [];
    } else {
      // Для вкладки "Узлы" используем либо children, либо units
      if (selectedCategory.children && selectedCategory.children.length > 0) {
        subcategories = selectedCategory.children;
      } else {
        const categoryId = selectedCategory.categoryid || selectedCategory.quickgroupid || selectedCategory.id;
        subcategories = unitsByCategory[categoryId] || [];
      }
    }
  }

  return (
    <div className="w-layout-vflex flex-block-14-copy-copy">
      {!selectedCategory ? (
        // Список категорий
        categories.map((cat: any, idx: number) => (
          <div
            className="div-block-131"
            key={cat.quickgroupid || cat.categoryid || cat.id || idx}
            onClick={() => handleCategoryClick(cat)}
            style={{ cursor: "pointer" }}
          >
            <div className="text-block-57">{cat.name}</div>
            <div className="w-embed">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="24" width="24" height="24" rx="12" transform="rotate(90 24 0)" fill="currentcolor"></rect>
                <path fillRule="evenodd" clipRule="evenodd" d="M10.9303 17L10 16.0825L14.1395 12L10 7.91747L10.9303 7L16 12L10.9303 17Z" fill="white"></path>
              </svg>
            </div>
          </div>
        ))
      ) : (
        // Список подкатегорий
        <>
          <div className="div-block-131" onClick={handleBack} style={{ cursor: "pointer", fontWeight: 500 }}>
            <div className="text-block-57">← Назад</div>
            <div className="w-embed">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect x="24" width="24" height="24" rx="12" transform="rotate(90 24 0)" fill="currentcolor"></rect>
                <path fillRule="evenodd" clipRule="evenodd" d="M10.9303 17L10 16.0825L14.1395 12L10 7.91747L10.9303 7L16 12L10.9303 17Z" fill="white"></path>
              </svg>
            </div>
          </div>
          {subcategories.length === 0 && <div style={{ color: "#888", padding: 8 }}>Нет подкатегорий</div>}
          {subcategories.map((subcat: any, idx: number) => (
            <div
              className="div-block-131"
              key={subcat.quickgroupid || subcat.categoryid || subcat.unitid || subcat.id || idx}
              onClick={() => handleSubcategoryClick(subcat)}
              style={{ cursor: "pointer" }}
            >
              <div className="text-block-57">{subcat.name}</div>
              <div className="w-embed">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <rect x="24" width="24" height="24" rx="12" transform="rotate(90 24 0)" fill="currentcolor"></rect>
                  <path fillRule="evenodd" clipRule="evenodd" d="M10.9303 17L10 16.0825L14.1395 12L10 7.91747L10.9303 7L16 12L10.9303 17Z" fill="white"></path>
                </svg>
              </div>
            </div>
          ))}
        </>
      )}
    </div>
  );
};

export default VinCategory; 