/* eslint-disable react/prop-types */
import React, { useState } from 'react';
import { Autocomplete, Avatar, Box, TextField, Typography } from '@mui/material';
import { useQuery } from '@tanstack/react-query';
import { getproductsubcategories } from 'pages/nearle/api/api';

const SubcatAutocomplete = ({ onSelect, sx }) => {
  const { data: subCategories = [] } = useQuery({
    queryKey: ['getsubcategory'],
    queryFn: getproductsubcategories
  });

  const [selected, setSelected] = useState(null);

  return (
    subCategories?.length > 0 && (
      <Autocomplete
        sx={{ ...sx }}
        disablePortal
        id="combo-box-subcategory"
        options={subCategories}
        value={selected}
        getOptionLabel={(option) => option?.subcatname || ''}
        onChange={(event, value) => {
          setSelected(value);
          onSelect?.(value); // 👈 callback to parent
        }}
        renderOption={(props, option) => (
          <Box {...props} sx={{ display: 'flex', alignItems: 'center', gap: 1, width: '100%' }}>
            <Avatar src={option.image} alt={option.subcatname} variant="square" sx={{ width: 24, height: 24 }} />
            <Typography variant="body1">{option.subcatname}</Typography>
          </Box>
        )}
        renderInput={(params) => (
          <TextField
            {...params}
            placeholder="Select Sub Category"
            InputProps={{
              ...params.InputProps,
              startAdornment: selected ? (
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                  <Avatar src={selected.image} alt={selected.subcatname} variant="square" sx={{ width: 34, height: 34 }} />
                  {/* <Typography variant="body2">{selected.productcount}</Typography> */}
                </Box>
              ) : null
            }}
          />
        )}
      />
    )
  );
};

export default SubcatAutocomplete;
