import { Chart } from '../../js/chart-wrapper';
import { PanelBody, PanelRow, TextControl, Flex, FlexItem } from '@wordpress/components';
import SidebarAutocomplete from '../components/autocomplete/institution/sidebar-autocomplete'
import {
	useBlockProps,
	InspectorControls,
  RichText
} from '@wordpress/block-editor';

export default function Edit({ attributes, setAttributes }) {
    const { graph_title, graph_meta_data = [] } = attributes; // Garante que tableData nunca seja undefined

    if (graph_meta_data.length === 0) {
      setAttributes({
        graph_meta_data: [
              ["Categoria", "Valor"],
              ["Maçã", 30],
              ["Banana", 20],
              ["Laranja", 50]
          ]
      });
  }    

  const updateCell = (rowIndex, colIndex, value) => {
    const newData = [...graph_meta_data];
    newData[rowIndex][colIndex] = value;
    setAttributes({ graph_meta_data: newData });
  };

    const handleSelectChange = (newValue) => {
      setAttributes( { graph_meta_data: newValue } );
    };

    const blockProps = useBlockProps();

    const onChangeTitle = ( titleUpdated ) => {
      setAttributes( { graph_title: titleUpdated } );
    }

    const onChangeCustomWidth = ( widthUpdated ) => {
      setAttributes( { custom_size_width: widthUpdated } );
    };
  
    const onChangeCustomHeight = ( heightUpdated ) => {
      setAttributes( { custom_size_height: heightUpdated } );
    };

    const onChangeCustomMaxItem = ( maxItemUpdated ) => {
      setAttributes( { custom_max_item: maxItemUpdated } );
    };
    
    const chartEvents = [
        {
          eventName: "select",
          callback({ chartWrapper }) {
            console.log("Selected ", chartWrapper.getChart().getSelection());
          },
        },
        {
          eventName: "ready",
          callback({ chartWrapper }) {
            console.log(chartWrapper.getChart())
            setAttributes({graph_image_data: chartWrapper.getChart().getImageURI()})
          },
        },
        {
          eventName: "error",
          callback({ chartWrapper, eventArgs }) {
            console.error("chartWrapper:", chartWrapper);
            console.error("Error:", eventArgs);
          },
        },
      ];

      const data = [
        ["Name", "Salary", "Full time employee"],
        ["Mike", { v: 10000, f: "$10,000" }, true],
        ["Jim", { v: 8000, f: "$8,000" }, false],
        ["Alice", { v: 12500, f: "$12,500" }, true],
        ["Bob", { v: 7000, f: "$7,000" }, true],
      ];

      const options = {
        title: "Company Performance",
        curveType: "function",
        legend: { position: "bottom" },
        pageSize: 1,
      };

    return (
        <div {...blockProps}>
            <InspectorControls key="setting">
              <div>
                <fieldset>
                  <Flex>
                    <PanelBody title="Configurações gráfico" initialOpen={true}>
                        <PanelRow>
                        <TextControl
                              label="Título"
                              placeholder='Título'
                              value={ attributes.graph_title }
                              onChange={ ( value ) => onChangeTitle( value ) }
                            />
                        </PanelRow>
                        <PanelRow>
                          <FlexItem>
                            <TextControl
                              label="Limite de itens"
                              value={ attributes.custom_max_item }
                              onChange={ ( value ) => onChangeCustomMaxItem( value ) }
                            />
                          </FlexItem>
                        </PanelRow>                        
                        <PanelRow>
                          <FlexItem>
                            <TextControl
                              label="Altura"
                              placeholder='px'
                              value={ attributes.custom_size_height }
                              onChange={ ( value ) => onChangeCustomHeight( value ) }
                            />
                          </FlexItem>
                          <FlexItem>
                            <TextControl
                              label="Largura"
                              placeholder='px'
                              value={ attributes.custom_size_width }
                              onChange={ ( value ) => onChangeCustomWidth( value ) }
                            />
                          </FlexItem>
                        </PanelRow>
                      </PanelBody>                          
                  </Flex>
                  <Flex>
                    <FlexItem>
                        <SidebarAutocomplete
                          onChange={handleSelectChange}
                          limit={attributes.custom_max_item}
                        />
                    </FlexItem>
                  </Flex>
                </fieldset>
              </div>
            </InspectorControls>
            <div
              style={ {
                width: isNaN(attributes.custom_size_width) || attributes.custom_size_width === '__IMAGE__' 
                  ? '150px' 
                  : attributes.custom_size_width + 'px',
                height: isNaN(attributes.custom_size_height) || attributes.custom_size_height === '__IMAGE__' 
                  ? '150px' 
                  : attributes.custom_size_height + 'px',
                marginInline: 'auto',
              } }
            >              
            {/* Título editável */}
            <RichText
                tagName="h3"
                value={graph_title || "Título da Tabela"}
                onChange={(value) => setAttributes({ graph_title: value })}
                placeholder="Digite o título da tabela..."
                className="table-title"
            />

            <table className="wp-block-table">
                <tbody>
                    {graph_meta_data.map((row, rowIndex) => (
                        <tr key={rowIndex}>
                            {row.map((cell, colIndex) => (
                                <td key={colIndex}>
                                    <RichText
                                        value={String(cell)}
                                        onChange={(value) => updateCell(rowIndex, colIndex, value)}
                                    />
                                </td>
                            ))}
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
        </div>
    );
}