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;
  onCategoryClick?: (e?: React.MouseEvent) => void;
}

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

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

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

  // Запрос для "От производителя" (Categories)
  const { data: categoriesData, loading: categoriesLoading, error: categoriesError } = useQuery(GET_LAXIMO_CATEGORIES, {
    variables: { catalogCode: catalogCode || '', vehicleId: vehicleId || '', ssd: ssd || '' },
    skip: !catalogCode || !vehicleId || activeTab !== 'manufacturer',
    errorPolicy: 'all'
  });

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

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

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

  const handleCategoryClick = (category: any) => {
    // Если передан onCategoryClick, используем его
    if (onCategoryClick) {
      onCategoryClick();
      return;
    }

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

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

  // Если нет данных о транспортном средстве, показываем заглушку
  if (!catalogCode || !vehicleId) {
    return (
      <div className="w-layout-vflex flex-block-14-copy-copy">
        <div className="text-center py-8 text-gray-500">
          <div className="text-lg font-medium mb-2">Каталог запчастей</div>
          <div className="text-sm">Выберите автомобиль для просмотра каталога</div>
        </div>
      </div>
    );
  }

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

  // Определяем, какие подкатегории показывать
  let subcategories: any[] = [];
  if (selectedCategory) {
    if (activeTab === 'uzly') {
      // Для вкладки "Общие" используем 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; 