const { useEffect, useState  } = wp.element;
const { InspectorControls, store: blockEditorStore  } = wp.blockEditor;
const { useSelect } = wp.data;
const { __ } = wp.i18n;
const { TabPanel, PanelBody, BaseControl, Button, SelectControl } = wp.components;

import { DeviceProvider, useDevice } from '../components/DeviceContext';
import ToggleOptionControl from '../components/ToggleOptionControl';
import FontFamilySelector from '../components/FontFamilySelector';
import FontWeightSelector from '../components/FontWeightSelector';
import ColorPickerSelection from '../components/ColorPickerSelection';
import FontSizeControl from '../components/FontSizeControl';
import ImageSizeControls from '../components/ImageSizeControls';
import SpacingControls from '../components/SpacingControls';
import WidthControl from '../components/WidthControl';
import TextShadowControl from '../components/TextShadowControl';
import LineHeightControl from '../components/LineHeightControl';
import TagSelector from '../components/TagSelector';

import LayoutOne from './layouts/LayoutOne';
import LayoutTwo from './layouts/LayoutTwo';

import layout1Image from '../assets/preview/layout-1.jpg';
import layout2Image from '../assets/preview/layout-2.jpg';

export default function Edit({ attributes, setAttributes, clientId  }) {
  return (
    <DeviceProvider>
      <EditInner attributes={attributes} setAttributes={setAttributes} clientId={clientId} />
    </DeviceProvider>
  );
}
const isEntryEmpty = ( entry ) => {
  return (
    ! entry.year?.trim() &&
    ! entry.title?.trim() &&
    ! entry.description?.trim() &&
    ! entry.imageUrl?.trim()
  );
};
function EditInner({ attributes, setAttributes, clientId  }) {
 const {
    entries,
    showHeading,
    showYear,
    showTitle,
    showDescription,
    showImage,
    layout,
    headingFontSize, headingFontSizeUnit, headingLineHeight, headingLineHeightUnit,
    yearFontSize, yearFontSizeUnit, yearLineHeight, yearLineHeightUnit,
    titleFontSize, titleFontSizeUnit, titleLineHeight, titleLineHeightUnit,
    descriptionFontSize, descriptionFontSizeUnit, descriptionLineHeight, descriptionLineHeightUnit,
    sectionWidthType,
    sectionWidth,
    sectionWidthUnit,
    isPreview
  } = attributes;

  const { activeDevice } = useDevice();
  const [ showPreviewImage, setShowPreviewImage ] = useState( isPreview );

  // Detect if the block is selected (user clicked to insert).
  const isSelected = useSelect(
    ( select ) => select( blockEditorStore ).isBlockSelected( clientId ),
    [ clientId ]
  );

  useEffect( () => {

    // Only clear preview *after actual block selection (click)*.
    if ( isPreview && isSelected ) {
      setAttributes({ isPreview: false });
      setShowPreviewImage( false );
    }
  }, [ isPreview, isSelected ]);

  useEffect( () => {
      const cleaned = entries.filter( ( entry ) => ! isEntryEmpty( entry ) );

      if ( cleaned.length !== entries.length ) {
        setAttributes({ entries: cleaned });
      }
  }, []);

  if ( showPreviewImage ) {
    const previewImage = 'layout-two' === layout ? layout2Image : layout1Image;
    return (
      <div className="journey-timeline-block-preview">
        <img src={previewImage} alt="Layout Preview" style={{ width: '100%' }} />
      </div>
    );
  }

  const renderLayout = ( entry, index ) => {
    switch ( layout ) {
      case 'layout-two':
        return (
          <LayoutTwo
            key={index}
            entries={entries}
            index={index}
            showHeading={showHeading}
            showYear={showYear}
            showTitle={showTitle}
            showDescription={showDescription}
            showImage={showImage}
            updateEntry={updateEntry}
            removeEntry={removeEntry}
            activeDevice={activeDevice}
            attributes={attributes}
            setAttributes={setAttributes}
          />
        );
      case 'layout-one':
      default:
        return (
          <LayoutOne
            key={index}
            entries={entries}
            index={index}
            showHeading={showHeading}
            showYear={showYear}
            showTitle={showTitle}
            showDescription={showDescription}
            showImage={showImage}
            updateEntry={updateEntry}
            removeEntry={removeEntry}
            activeDevice={activeDevice}
            attributes={attributes}
            setAttributes={setAttributes}
          />
        );
    }
  };

  const addEntry = () => {
      const newEntries = [ ...entries, { year: '', title: '', description: '', imageUrl: '' } ];
      setAttributes({ entries: newEntries });
  };
  useEffect( () => {
    if ( ! entries || 0 === entries.length ) {
      setAttributes({
        entries: [
          { year: '', title: '', description: '', imageUrl: '' }
        ]
      });
    }
  }, []);

  const updateEntry = ( index, field, value ) => {
      const newEntries = entries.map( ( entry, i ) => {
          if ( i === index ) {
              return { ...entry, [field]: value };
          }
          return entry;
      });
      setAttributes({ entries: newEntries });
  };

  const removeEntry = ( index ) => {
      const newEntries = entries.filter( ( _, i ) => i !== index );
      setAttributes({ entries: newEntries });
  };

  const onSectionWidthType = ( newWidthType ) => {
    setAttributes({ sectionWidthType: newWidthType });
  };
  const onSectionWidthChange = ( newWidth ) => {
    setAttributes({ sectionWidth: newWidth });
  };
  const onSectionWidthUnitChange = ( newUnit ) => {
    setAttributes({ sectionWidthUnit: newUnit });
  };

  const onHeadingFontSizeChange = ( newSize ) => {
    setAttributes({ headingFontSize: newSize });
  };
  const onHeadingUnitChange = ( newUnit ) => {
    setAttributes({ headingFontSizeUnit: newUnit });
  };
  const onHeadingLineHeightChange = ( newSize ) => {
    setAttributes({ headingLineHeight: newSize });
  };
  const onHeadingLineHeightUnitChange = ( newUnit ) => {
    setAttributes({ headingLineHeightUnit: newUnit });
  };

  const onYearFontSizeChange = ( newSize ) => {
    setAttributes({ yearFontSize: newSize });
  };
  const onYearUnitChange = ( newUnit ) => {
    setAttributes({ yearFontSizeUnit: newUnit });
  };
  const onYearLineHeightChange = ( newSize ) => {
    setAttributes({ yearLineHeight: newSize });
  };
  const onYearLineHeightUnitChange = ( newUnit ) => {
    setAttributes({ yearLineHeightUnit: newUnit });
  };

  const onTitleFontSizeChange = ( newSize ) => {
    setAttributes({ titleFontSize: newSize });
  };
  const onTitleUnitChange = ( newUnit ) => {
    setAttributes({ titleFontSizeUnit: newUnit });
  };
  const onTitleLineHeightChange = ( newSize ) => {
    setAttributes({ titleLineHeight: newSize });
  };
  const onTitleLineHeightUnitChange = ( newUnit ) => {
    setAttributes({ titleLineHeightUnit: newUnit });
  };

  const onDescriptionFontSizeChange = ( newSize ) => {
    setAttributes({ descriptionFontSize: newSize });
  };
  const onDescriptionUnitChange = ( newUnit ) => {
    setAttributes({ descriptionFontSizeUnit: newUnit });
  };
  const onDescriptionLineHeightChange = ( newSize ) => {
    setAttributes({ descriptionLineHeight: newSize });
  };
  const onDescriptionLineHeightUnitChange = ( newUnit ) => {
    setAttributes({ descriptionLineHeightUnit: newUnit });
  };

  const layouts = [
    { label: 'Layout One', value: 'layout-one' },
    { label: 'Layout Two', value: 'layout-two'}
  ];

  return (
    <>
      {/* Inspector Sidebar Controls with Horizontal Tabs. */}
      <InspectorControls>
        <TabPanel
          className="ojb-block-main-tabs"
          activeClass="active-tab"
          tabs={[
            {
              name: 'general',
              title: (
                <>
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M19 8h-1V6h-5v2h-2V6H6v2H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm.5 10c0 .3-.2.5-.5.5H5c-.3 0-.5-.2-.5-.5v-8c0-.3.2-.5.5-.5h14c.3 0 .5.2.5.5v8z"></path></svg>
                  {__( 'General', 'journey-timeline-block' )}
                </>
              ),
              className: 'tab-general'
            },
            {
              name: 'style',
              title: (
                <>
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M4 20h8v-1.5H4V20zM18.9 3.5c-.6-.6-1.5-.6-2.1 0l-7.2 7.2c-.4-.1-.7 0-1.1.1-.5.2-1.5.7-1.9 2.2-.4 1.7-.8 2.2-1.1 2.7-.1.1-.2.3-.3.4l-.6 1.1H6c2 0 3.4-.4 4.7-1.4.8-.6 1.2-1.4 1.3-2.3 0-.3 0-.5-.1-.7L19 5.7c.5-.6.5-1.6-.1-2.2zM9.7 14.7c-.7.5-1.5.8-2.4 1 .2-.5.5-1.2.8-2.3.2-.6.4-1 .8-1.1.5-.1 1 .1 1.3.3.2.2.3.5.2.8 0 .3-.1.9-.7 1.3z"></path></svg>
                  {__( 'Style', 'journey-timeline-block' )}
                </>
              ),
              className: 'tab-style'
            },
            {
              name: 'advance',
              title: (
                <>
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true" focusable="false"><path d="M14.5 13.8c-1.1 0-2.1.7-2.4 1.8H4V17h8.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20v-1.5h-3.1c-.3-1-1.3-1.7-2.4-1.7zM11.9 7c-.3-1-1.3-1.8-2.4-1.8S7.4 6 7.1 7H4v1.5h3.1c.3 1 1.3 1.8 2.4 1.8s2.1-.7 2.4-1.8H20V7h-8.1z"></path></svg>
                  {__( 'Advance', 'journey-timeline-block' )}
                </>
              ),
              className: 'tab-advance'
            }
          ]}
        >
          {( tab ) => {
            if ( 'general' === tab.name ) {
              return (
                <BaseControl className="ojb-general-tab-control ojb-control">
                  <PanelBody>
                    <SelectControl
                      label={__( 'Choose Layout' )}
                      value={layout}
                      options={layouts}
                      onChange={( val ) => setAttributes({ layout: val })}
                    />
                    <hr/>

                    <WidthControl
                      label="Width"
                      widthType={sectionWidthType}
                      setWidthType={onSectionWidthType}
                      sectionWidth={sectionWidth}
                      setSectionWidth={onSectionWidthChange}
                      sectionWidthUnit={sectionWidthUnit}
                      setSectionWidthUnit={onSectionWidthUnitChange}
                    />
                    <hr/>

                    <ToggleOptionControl
                      label="Show Heading"
                      checked={attributes.showHeading}
                      onChange={( val ) => setAttributes({ showHeading: val })}
                    />

                    <ToggleOptionControl
                      label="Show Year"
                      checked={attributes.showYear}
                      onChange={( val ) => setAttributes({ showYear: val })}
                    />

                    <ToggleOptionControl
                      label="Show Title"
                      checked={attributes.showTitle}
                      onChange={( val ) => setAttributes({ showTitle: val })}
                    />

                    <ToggleOptionControl
                      label="Show Description"
                      checked={attributes.showDescription}
                      onChange={( val ) => setAttributes({ showDescription: val })}
                    />

                    <ToggleOptionControl
                      label="Show Image"
                      checked={attributes.showImage}
                      onChange={( val ) => setAttributes({ showImage: val })}
                    />
                  </PanelBody>
                </BaseControl>
              );
            }
            if ( 'style' === tab.name ) {
              return (
                <BaseControl className="ojb-style-tab-control ojb-control">
                  {/* Section Setting PanelBody. */}
                  <PanelBody title="Section Settings" initialOpen={true}>
                      <ColorPickerSelection
                        value={attributes.sectionBgColor}
                        onChange={( color ) => setAttributes({ sectionBgColor: color })}
                        label={__( 'Background Color', 'journey-timeline-block' )}
                      />
                  </PanelBody>

                  {/* Item Box Setting PanelBody. */}
                  <PanelBody title="Item Box Settings" initialOpen={false}>
                      <ColorPickerSelection
                        value={attributes.sectionItemContentBgColor}
                        onChange={( color ) => setAttributes({ sectionItemContentBgColor: color })}
                        label={__( 'Content Box Background Color', 'journey-timeline-block' )}
                      />
                      {/* Only show this section if layout is 'layout2'. */}
                      {'layout-two' === attributes.layout && (
                        <>
                          <hr/>
                          <ColorPickerSelection
                            value={attributes.sectionItemYearBgColor}
                            onChange={( color ) => setAttributes({ sectionItemYearBgColor: color })}
                            label={__( 'Year Box Background Color', 'journey-timeline-block' )}
                          />
                       </>
                      )}
                  </PanelBody>

                  {/* Section Heading Setting PanelBody. */}
                  <PanelBody title="Heading Settings" initialOpen={false}>
                    <FontFamilySelector
                      label={__( 'Font Family', 'journey-timeline-block' )}
                      value={attributes.headingFontFamily}
                      onChange={( val ) => setAttributes({ headingFontFamily: val })}
                    />
                    <hr/>
                    <FontSizeControl
                      label="Font Size"
                      fontSize={headingFontSize}
                      setFontSize={onHeadingFontSizeChange}
                      fontSizeUnit={headingFontSizeUnit}
                      setFontSizeUnit={onHeadingUnitChange}
                    />
                    <hr/>
                    <LineHeightControl
                      label="Line Height"
                      lineHeight={headingLineHeight}
                      setLineHeight={onHeadingLineHeightChange}
                      lineHeightUnit={headingLineHeightUnit}
                      setLineHeightUnit={onHeadingLineHeightUnitChange}
                    />
                    <hr/>
                    <FontWeightSelector
                      value={attributes.headingFontWeight}
                      onChange={( value ) => setAttributes({ headingFontWeight: value })}
                      label={__( 'Font Weight', 'journey-timeline-block' )}
                    />
                    <hr/>
                    <ColorPickerSelection
                      value={attributes.headingFontColor}
                      onChange={( color ) => setAttributes({ headingFontColor: color })}
                      label={__( 'Font Color', 'journey-timeline-block' )}
                    />
                    {/* Only show this section if layout is 'layout2'. */}
                    {'layout-two' === attributes.layout && (
                      <>
                        <hr/>
                        <ColorPickerSelection
                          value={attributes.headingBgColor}
                          onChange={( color ) => setAttributes({ headingBgColor: color })}
                          label={__( 'Circle Background Color', 'journey-timeline-block' )}
                        />
                      </>
                    )}
                  </PanelBody>

                  {/* Year Setting PanelBody. */}
                  <PanelBody title="Year Settings" initialOpen={false}>
                    <TagSelector
                      label="Year Tag"
                      value={attributes.yearTag}
                      onChange={( val ) => setAttributes({ yearTag: val })}
                    />
                    <hr/>

                    <FontFamilySelector
                      label={__( 'Font Family', 'journey-timeline-block' )}
                      value={attributes.yearFontFamily}
                      onChange={( val ) => setAttributes({ yearFontFamily: val })}
                    />
                    <hr/>
                    <FontSizeControl
                      label="Font Size"
                      fontSize={yearFontSize}
                      setFontSize={onYearFontSizeChange}
                      fontSizeUnit={yearFontSizeUnit}
                      setFontSizeUnit={onYearUnitChange}
                    />
                    <hr/>
                    <LineHeightControl
                      label="Line Height"
                      lineHeight={yearLineHeight}
                      setLineHeight={onYearLineHeightChange}
                      lineHeightUnit={yearLineHeightUnit}
                      setLineHeightUnit={onYearLineHeightUnitChange}
                    />
                    <hr/>
                    <FontWeightSelector
                      value={attributes.yearFontWeight}
                      onChange={( value ) => setAttributes({ yearFontWeight: value })}
                      label={__( 'Font Weight', 'journey-timeline-block' )}
                    />
                    <hr/>
                    <ColorPickerSelection
                      value={attributes.yearFontColor}
                      onChange={( color ) => setAttributes({ yearFontColor: color })}
                      label={__( 'Font Color', 'journey-timeline-block' )}
                    />
                    <hr/>
                    <TextShadowControl
                      label="Text Shadow"
                      value={attributes.yearTextShadow}
                      onChange={( val ) => setAttributes({ yearTextShadow: val })}
                    />
                  </PanelBody>

                  {/* Title Setting PanelBody. */}
                  <PanelBody title="Title Settings" initialOpen={false}>
                    <TagSelector
                      label="Title Tag"
                      value={attributes.titleTag}
                      onChange={( val ) => setAttributes({ titleTag: val })}
                    />
                    <hr/>

                    <FontFamilySelector
                      label={__( 'Font Family', 'journey-timeline-block' )}
                      value={attributes.titleFontFamily}
                      onChange={( val ) => setAttributes({ titleFontFamily: val })}
                    />
                    <hr/>
                    <FontSizeControl
                      label="Font Size"
                      fontSize={titleFontSize}
                      setFontSize={onTitleFontSizeChange}
                      fontSizeUnit={titleFontSizeUnit}
                      setFontSizeUnit={onTitleUnitChange}
                    />
                    <hr/>
                    <LineHeightControl
                      label="Line Height"
                      lineHeight={titleLineHeight}
                      setLineHeight={onTitleLineHeightChange}
                      lineHeightUnit={titleLineHeightUnit}
                      setLineHeightUnit={onTitleLineHeightUnitChange}
                    />
                    <hr/>
                    <FontWeightSelector
                      value={attributes.titleFontWeight}
                      onChange={( value ) => setAttributes({ titleFontWeight: value })}
                      label={__( 'Font Weight', 'journey-timeline-block' )}
                    />
                    <hr/>
                    <ColorPickerSelection
                      value={attributes.titleFontColor}
                      onChange={( color ) => setAttributes({ titleFontColor: color })}
                      label={__( 'Font Color', 'journey-timeline-block' )}
                    />
                    <hr/>
                    <TextShadowControl
                      label="Text Shadow"
                      value={attributes.titleTextShadow}
                      onChange={( val ) => setAttributes({ titleTextShadow: val })}
                    />
                  </PanelBody>

                  {/* Description Setting PanelBody. */}
                  <PanelBody title="Description Settings" initialOpen={false}>
                    <FontFamilySelector
                      label={__( 'Font Family', 'journey-timeline-block' )}
                      value={attributes.descriptionFontFamily}
                      onChange={( val ) => setAttributes({ descriptionFontFamily: val })}
                    />
                    <hr/>
                    <FontSizeControl
                      label="Font Size"
                      fontSize={descriptionFontSize}
                      setFontSize={onDescriptionFontSizeChange}
                      fontSizeUnit={descriptionFontSizeUnit}
                      setFontSizeUnit={onDescriptionUnitChange}
                    />
                    <hr/>
                    <LineHeightControl
                      label="Line Height"
                      lineHeight={descriptionLineHeight}
                      setLineHeight={onDescriptionLineHeightChange}
                      lineHeightUnit={descriptionLineHeightUnit}
                      setLineHeightUnit={onDescriptionLineHeightUnitChange}
                    />
                    <hr/>
                    <FontWeightSelector
                      value={attributes.descriptionFontWeight}
                      onChange={( value ) => setAttributes({ descriptionFontWeight: value })}
                      label={__( 'Font Weight', 'journey-timeline-block' )}
                    />
                    <hr/>
                    <ColorPickerSelection
                      value={attributes.descriptionFontColor}
                      onChange={( color ) => setAttributes({ descriptionFontColor: color })}
                      label={__( 'Font Color', 'journey-timeline-block' )}
                    />
                  </PanelBody>

                  {/* Image Setting PanelBody. */}
                  <PanelBody title="Image Settings" className = "ojb-image-setting" initialOpen={false}>
                    <ImageSizeControls
                      imageSize={attributes.imageSize}
                      setImageSize={( val ) => setAttributes({ imageSize: val })}
                    />
                  </PanelBody>
                </BaseControl>
              );
            }
            if ( 'advance' === tab.name ) {
              return (
                <BaseControl className="ojb-advance-tab-control ojb-control">
                  <PanelBody title="Section Settings">
                    <SpacingControls
                      label="Padding"
                      spacingValues={attributes.sectionPadding}
                      onChange={( value ) => setAttributes({ sectionPadding: value })}
                      isLinked={attributes.sectionPaddingIsLinked}
                      setIsLinked={( val ) => setAttributes({ sectionPaddingIsLinked: val })}
                    />
                    <hr/>
                    <SpacingControls
                      label="Margin"
                      spacingValues={attributes.sectionMargin}
                      onChange={( value ) => setAttributes({ sectionMargin: value })}
                      isLinked={attributes.sectionMarginIsLinked}
                      setIsLinked={( val ) => setAttributes({ sectionMarginIsLinked: val })}
                    />
                  </PanelBody>
                </BaseControl>
              );
            }
          }}
        </TabPanel>
      </InspectorControls>
      {/* Main block content (editor canvas). */}

      <div
        key={activeDevice}
        className = {'journey-timeline-block-section'}
      >

        {renderLayout( entries[0], 0 )}

        <Button onClick={addEntry} variant="primary" style={{ marginTop: '20px' }}>
          {__( 'Add Journey Entry', 'journey-timeline-block' )}
        </Button>

      </div>
    </>
  );
}

// Export wrapper props for outermost editor div.
export function getEditWrapperProps( attributes ) {
  const { sectionBgColor, sectionPadding, sectionMargin, sectionWidthType, sectionWidth, sectionWidthUnit } = attributes;

  const getBoxSpacingValue = ( spacingObj ) => {
    if ( ! spacingObj?.desktop ) {
return undefined;
}
    const { top = '0', right = '0', bottom = '0', left = '0', unit = 'px' } = spacingObj.desktop;
    return `${top}${unit} ${right}${unit} ${bottom}${unit} ${left}${unit}`;
  };

  const getSectionWidth = () => {
    if ( ! sectionWidth?.desktop ) {
return undefined;
}

    if ( 'custom' === sectionWidthType ) {
      const value = parseFloat( sectionWidth.desktop );
      if ( isNaN( value ) ) {
return undefined;
}
      return `${value}${sectionWidthUnit || 'px'}`;
    }

    if ( 'full' === sectionWidthType ) {
return '100%';
}
    if ( 'inline' === sectionWidthType ) {
return 'auto';
}

    return undefined;
  };

  return {
    style: {
      backgroundColor: sectionBgColor || undefined,
      padding: getBoxSpacingValue( sectionPadding ),
      margin: getBoxSpacingValue( sectionMargin ),
      maxWidth: getSectionWidth()
    },
    className: `our-journey-wrapper ${attributes.className || ''}`
  };
}
