import { InspectorControls, PanelColorSettings } from "@wordpress/block-editor";
import { __ } from "@wordpress/i18n";

import { PanelBody, FormTokenField, CheckboxControl, ToggleControl  } from "@wordpress/components";
import { useState, useEffect } from "@wordpress/element";
import { useSelect } from '@wordpress/data';

/**
 * SidePanel component for selecting FAQ posts.
 * @param {Object} props - Component properties.
 * @param {function} props.setFaqPostsSelected - Function to set the selected FAQ posts.
 * @param {Array} props.postIds - Array of post IDs already selected in attributes.
 * @returns {JSX.Element} The rendered component.
 */
const SidePanel = ({ postIds = [], setPostIds = (value) => {}, attributes = {}, setAttributes = (value) => {} }) => {

  //state for the label of the faq posts select input in side panel
  const [faqPostsLabel, setFaqPostsLabel] = useState([]);
  const [faqPostsForSelect, setFaqPostsForSelect] = useState([]);
  const [faqPostsObj, setFaqPostsObj] = useState([]);

  const [taxonomiesLabel, setTaxonomiesLabel] = useState([]);
  const [taxonomiesForSelect, setTaxonomiesForSelect] = useState([]);
  const [taxonomiesObj, setTaxonomiesObj] = useState([]);

  // Get theme colors and store them in state to avoid recalculating
  const [themeColors, setThemeColors] = useState({
    primary: '#0065FF',
    background: 'transparent',
    text: '#172B4D',
    border: '#EBECF0'
  });

  //fetch all faq posts
  // console.log(window.OrphicWPBlockOptions.orphic_wp_block_plugin_colors);
  const posts = useSelect( ( select ) => {
    return select( 'core' ).getEntityRecords( 'postType', 'faq' ) ?? [];
  }, [] );

  //fetch all taxonomies
  const taxonomies = useSelect( ( select ) => {
    return select( 'core' ).getEntityRecords( 'taxonomy', 'faq_category' ) ?? [];
  }, [] );

  //set the faq posts for the select input in side panel
  useEffect(() => {
    if (posts && posts.length > 0) {
      //set the faq posts object
      setFaqPostsObj(posts);

      //set the faq posts for the select input in side panel
      const faqPostsForSelect = posts.map((faq) => ({
        label: faq.title.raw,
      }));
      setFaqPostsForSelect(faqPostsForSelect);

      //set the faq posts already selected in the select input in side panel
      const faqPostsAlreadySelected = postIds.map((id) => posts.find((faq) => faq.id === id)?.title.raw);
      setFaqPostsLabel(faqPostsAlreadySelected);
    }
  }, [posts] );

  //map the taxonomies to the label and value for the select input
  useEffect(() => {
    if (taxonomies && taxonomies.length > 0) {

      const taxonomiesForSelect = taxonomies.map((taxonomy) => ({
        label: taxonomy.name,
      }));
      setTaxonomiesForSelect(taxonomiesForSelect);
      setTaxonomiesObj(taxonomies);
      const taxonomiesIds = attributes.taxonomiesIds;
      const taxonomiesLabel = taxonomiesIds.map((id) => taxonomies.find((taxonomy) => taxonomy.id === id)?.name);
      setTaxonomiesLabel(taxonomiesLabel);
    }
  }, [taxonomies]);

  useEffect(() => {
    const colors = window.OrphicWPBlockOptions.orphic_wp_block_plugin_colors || [];
    if (colors.length > 0) {
      setThemeColors({
        primary: colors.find(c => c.slug === 'primary')?.color || themeColors.primary,
        background: colors.find(c => c.slug === 'background')?.color || themeColors.background,
        text: colors.find(c => c.slug === 'text')?.color || themeColors.text,
        border: colors.find(c => c.slug === 'border')?.color || themeColors.border
      });
    }
  }, []);

  //map the faq posts to the label and value for the select input
  const handleFaqSelectChange = (value) => {
    setFaqPostsLabel(value);
    const filteredFaqPosts = value.map((title) => faqPostsObj.find((faq) => faq.title.raw === title)).map((faq) => faq.id);
    setPostIds(filteredFaqPosts);
  }

  const handleTaxonomiesSelectChange = (value) => {
    setTaxonomiesLabel(value);
    const filteredTaxonomies = value.map((title) => taxonomiesObj.find((taxonomy) => taxonomy.name === title)).map((taxonomy) => taxonomy.id);
    setAttributes({taxonomiesIds: filteredTaxonomies});
  }

	return (
		<>
        {/* test print something in the panel */}
			<InspectorControls>
				<PanelBody title={__("Settings", "orphic-wp-block-faq")}>
          {attributes.showFilterBar ? (
          <FormTokenField
            __experimentalExpandOnFocus={true}
            label={__("Select taxonomies", "orphic-wp-block-faq")}
            suggestions={taxonomiesForSelect.map((taxonomy) => taxonomy.label)}
            value={taxonomiesLabel}
            onChange={(value) => {handleTaxonomiesSelectChange(value)}}
          />
          ) : ""}
					<FormTokenField
            __experimentalExpandOnFocus={true}
						label={__("Select FAQs", "orphic-wp-block-faq")}
            suggestions={faqPostsForSelect.map((faq) => faq.label)}
						value={faqPostsLabel}
						onChange={(value) => {handleFaqSelectChange(value)}}
					/>
          <CheckboxControl
           label={__("Create JSON-LD", "orphic-wp-block-faq")} 
           checked={attributes.createJsonLd} 
           onChange={(value) => {setAttributes({createJsonLd: value})}}/>
          <CheckboxControl
           label={__("Show filter bar", "orphic-wp-block-faq")} 
           checked={attributes.showFilterBar} 
           onChange={(value) => {setAttributes({showFilterBar: value})}}/>
          

        
          

				</PanelBody>
        {/* style panel */}
        <PanelBody title={__("Style", "orphic-wp-block-faq")}>
            <ToggleControl
              label={__("Use custom color", "orphic-wp-block-faq")} 
              checked={attributes.isCustomColor} 
              onChange={(value) => {
                setAttributes({isCustomColor: value});
                // Ne plus reset les couleurs lors du toggle
              }}/>
            {attributes.isCustomColor && (
            <PanelColorSettings
              title={__("Color Settings", "orphic-wp-block-faq")}
              enableAlpha
              colorSettings={[
                {
                  value: attributes.backgroundColor,
                  onChange: (color) => setAttributes({backgroundColor: color || themeColors.background}),
                  label: __("Background Color", "orphic-wp-block-faq"),
                  resetFallbackColor: themeColors.background,
                },
                {
                  value: attributes.textColor,
                  onChange: (color) => setAttributes({textColor: color || themeColors.text}),
                  label: __("Text Color", "orphic-wp-block-faq"),
                  resetFallbackColor: themeColors.text,
                },
                {
                  value: attributes.borderColor,
                  onChange: (color) => setAttributes({borderColor: color || themeColors.border}),
                  label: __("Border Color", "orphic-wp-block-faq"),
                  resetFallbackColor: themeColors.border,
                },
                {
                  value: attributes.primaryColor,
                  onChange: (color) => setAttributes({primaryColor: color || themeColors.primary}),
                  label: __("Primary Color", "orphic-wp-block-faq"),
                  resetFallbackColor: themeColors.primary,
                },
              ]}
            />
            )}
        </PanelBody>
			</InspectorControls>
		</>
	);
};
export default SidePanel;
