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

interface VinCategoryProps {
  catalogCode: string;
  vehicleId: string;
  ssd?: string;
  onNodeSelect?: (node: any) => void;
}

const VinCategory: React.FC<VinCategoryProps> = ({ catalogCode, vehicleId, ssd, onNodeSelect }) => {
  const { data: categoriesData, loading: categoriesLoading, error: categoriesError } = useQuery(GET_LAXIMO_CATEGORIES, {
    variables: { catalogCode, vehicleId, ssd },
    skip: !catalogCode || vehicleId === undefined || vehicleId === null,
    errorPolicy: "all",
  });
  const categories = categoriesData?.laximoCategories || [];

  const [unitsByCategory, setUnitsByCategory] = useState<{ [key: string]: any[] }>({});
  const [getUnits] = useLazyQuery(GET_LAXIMO_UNITS, {
    onCompleted: (data) => {
      if (data && data.laximoUnits && lastCategoryIdRef.current) {
        setUnitsByCategory((prev) => ({
          ...prev,
          [lastCategoryIdRef.current!]: data.laximoUnits || [],
        }));
}
    },
  });
  const [selectedCategory, setSelectedCategory] = useState<any | null>(null);
  const lastCategoryIdRef = useRef<string | null>(null);

  // Если выбрана категория — показываем подкатегории (children или units)
  let subcategories: any[] = [];
  if (selectedCategory) {
    if (selectedCategory.children && selectedCategory.children.length > 0) {
      subcategories = selectedCategory.children;
    } else {
      subcategories = unitsByCategory[selectedCategory.quickgroupid] || [];
    }
  }

  const handleCategoryClick = (cat: any) => {
    if (cat.children && cat.children.length > 0) {
      setSelectedCategory(cat);
    } else {
      // Если нет children, грузим units (подкатегории)
      if (!unitsByCategory[cat.quickgroupid]) {
        lastCategoryIdRef.current = cat.quickgroupid;
        getUnits({ variables: { catalogCode, vehicleId, ssd, categoryId: cat.quickgroupid } });
      }
      setSelectedCategory(cat);
    }
  };

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

  const handleSubcategoryClick = (subcat: any) => {
    if (onNodeSelect) {
      onNodeSelect({
        ...subcat,
        unitid: subcat.unitid || subcat.quickgroupid || subcat.id,
      });
    }
  };

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

  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.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>
        ))
      ) : (
        // Список подкатегорий (children или units)
        <>
          <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.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; 