import { InputText } from 'primereact/inputtext';
import { SelectButton } from 'primereact/selectbutton';
import { Dispatch, SetStateAction } from 'react';

import Button from '../_V2/Button';
import { TSizeOptionValue } from '../../../types/DataTable.types';

interface HeaderProps {
  size: any;
  setSize: Dispatch<SetStateAction<TSizeOptionValue>>;
  sizeOptions: { label: string; value: TSizeOptionValue }[];
  globalFilterValue: string;
  onGlobalFilterChange: (e: { target: { value: any } }) => void;
  onRefresh: () => void;
  clearFilter: () => void;
  hasExpandButtons?: boolean;
  setExpandedRows?: Dispatch<SetStateAction<any>>;
  expandedData?: any[];
  extraButtonsTemplate?: () => JSX.Element;
}

export const TableGroupHeader: React.FC<HeaderProps> = ({
  size,
  setSize,
  sizeOptions,
  globalFilterValue,
  onGlobalFilterChange,
  onRefresh,
  clearFilter,
  hasExpandButtons,
  setExpandedRows,
  expandedData,
  extraButtonsTemplate,
}) => {
  if (hasExpandButtons && (!setExpandedRows || !expandedData)) {
    throw new Error(
      'When hasExpandButtons is true, setExpandedRows and expandedData are required.'
    );
  }

  return (
    <div className={`flex items-center justify-between ${hasExpandButtons ? 'gap-4' : ''}`}>
      <SelectButton
        value={size}
        onChange={(e) => setSize(e.value)}
        options={sizeOptions}
        style={{ textAlign: 'center' }}
      />
      {hasExpandButtons ? (
        <div className='flex flex-wrap gap-2 justify-content-end'>
          <Button
            icon='pi pi-plus'
            label='Expand All'
            onClick={() => {
              // Set the expandedRows state with the new object
              const elements = [];
              expandedData.forEach((element) => {
                elements.push(element);
              });
              setExpandedRows(elements);
            }}
          />
          <Button icon='pi pi-minus' label='Collapse All' onClick={() => setExpandedRows(null)} />
        </div>
      ) : null}
      <span className='w-full mx-auto p-input-icon-left md:w-auto'>
        <i className='pi pi-search' />
        <InputText
          value={globalFilterValue}
          onChange={onGlobalFilterChange}
          placeholder='Search everything'
          className='w-full'
        />
      </span>
      <div className='flex gap-4'>
        <div className='flex items-center gap-2 '>
          <Button type='button' label='Refresh' outlined onClick={onRefresh} />
          <Button type='button' label='Clear Filters' outlined onClick={clearFilter} />
          {extraButtonsTemplate ? extraButtonsTemplate() : null}
        </div>
      </div>
    </div>
  );
};
export default TableGroupHeader;
