/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
 */
import { __ } from '@wordpress/i18n';

import { useSelect } from '@wordpress/data';

/**
 * Use Effect Hook
 */
import { useEffect, useState } from '@wordpress/element';

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps } from '@wordpress/block-editor';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import './editor.scss';
import SidePanel from './side-panel';

const useFaqPosts = (postIds) => {
  const posts = useSelect(select => select('core').getEntityRecords('postType', 'faq') ?? [], []);
  const [faqPostsSelected, setFaqPostsSelected] = useState([]);

  useEffect(() => {
    if (posts.length > 0) {
      if(postIds.length > 0){
        setFaqPostsSelected(postIds.map(id => posts.find(faq => faq.id === id)));
      }else{
        setFaqPostsSelected(posts);
      }
    }
  }, [posts, postIds]);

  return faqPostsSelected;
};

const useTaxonomies = (taxonomiesIds) => {
  const taxonomies = useSelect(select => select('core').getEntityRecords('taxonomy', 'faq_category') ?? [], []);
  const [taxonomiesSelected, setTaxonomiesSelected] = useState([]);

  useEffect(() => {
    if (taxonomies.length > 0) {
      setTaxonomiesSelected(taxonomiesIds.map(id => taxonomies.find(taxonomy => taxonomy.id === id)));
    }
  }, [taxonomies, taxonomiesIds]);

  return taxonomiesSelected;
};

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */
export default function Edit({ attributes, setAttributes }) {
  const faqPostsSelected = useFaqPosts(attributes.postIds);
  const taxonomiesSelected = useTaxonomies(attributes.taxonomiesIds);


  const colors = window.OrphicWPColorsTheme;
  console.log(colors);

  useEffect(() => {
    console.log("i updated");
    if (colors && colors.length > 0 && attributes.isFirstTimeChangeColor) {
      const primaryColor = colors.find(c => c.slug === 'primary')?.color || '#0065FF';
      const backgroundColor = colors.find(c => c.slug === 'background')?.color || 'transparent';
      const textColor = colors.find(c => c.slug === 'text')?.color || '#172B4D';
      const borderColor = colors.find(c => c.slug === 'border')?.color || '#EBECF0';

      setAttributes({
        backgroundColor,
        textColor,
        borderColor, 
        primaryColor
      });
      setAttributes({isFirstTimeChangeColor: false});
    }
  }, []);

  const isCustomColor = attributes.isCustomColor;

  let style = {};
  if(isCustomColor){
    style = {
      "--orphic-wp-block-faq-custom-background-color": attributes.backgroundColor,
      "--orphic-wp-block-faq-custom-text-color": attributes.textColor,
      "--orphic-wp-block-faq-custom-border-color": attributes.borderColor,
      "--orphic-wp-block-faq-custom-primary-color": attributes.primaryColor
    }
  }

  return (
		<p { ...useBlockProps() }>
			<SidePanel postIds={attributes.postIds} setPostIds={(value)=>{setAttributes({postIds: value})}} attributes={attributes} setAttributes={setAttributes}/>
			<div className={`orphic-wp-block-faq__container ${isCustomColor ? 'customColor' : ''}`} style={style}>
        {attributes.showFilterBar ? (
        <div className="orphic-wp-block-faq__filter">
          <div className="orphic-wp-block-faq__filter-items">  
                <span className="orphic-wp-block-faq__filter-item active">All</span>
                {taxonomiesSelected.map((taxonomy) => (
                  <span key={taxonomy.id} className="orphic-wp-block-faq__filter-item">{taxonomy.name}</span>
                ))}
          </div>
          <span className="orphic-wp-block-faq__filter-follower"></span>
          </div>
        ) : ""}
        <div className="orphic-wp-block-faq__questions-panel">
          {faqPostsSelected.map((faq) => (
            <div key={faq.id} className="orphic-wp-block-faq__questions-item">
              <div className="orphic-wp-block-faq__questions-item-title-wrapper">
                <span className="orphic-wp-block-faq__questions-item-title">{faq.title.raw}</span>
                <svg className="orphic-wp-block-faq__questions-item-icon" width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M13 5.84375L8 11.1562L3 5.84375" stroke="#172B4D" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
              </div>
              <div className="orphic-wp-block-faq__questions-item-line"></div>
            </div>
          ))}
        </div>
      </div>
		</p>
	);
}
