import { Checkbox, Col, Divider, Input, Row } from 'antd';
import { memo, useEffect, useState } from 'react';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import { useIntl } from 'umi';
import { useSelections } from 'ahooks';

type CustomCheckGroupProps = {
  value: CheckboxValueType[];
  onChange: (value: CheckboxValueType[]) => void;
  options: { label: string; value: string }[];
};
const CustomCheckGroup = ({ value, onChange, options }: CustomCheckGroupProps) => {
  const { formatMessage } = useIntl();
  const [filterValue, setFilterValue] = useState(options);
  const { selected, allSelected, isSelected, toggle, toggleAll, partiallySelected } = useSelections(
    filterValue.map((item) => item.value),
    value,
  );
  useEffect(() => {
    onChange?.(selected);
  }, [selected, onChange]);
  return (
    <>
      <Input
        placeholder={formatMessage({ id: 'base.common.input.placeholder.default' })}
        onChange={(event) =>
          setFilterValue(
            options.filter((item) =>
              item.label.toLocaleLowerCase().includes(event.target.value.toLocaleLowerCase()),
            ),
          )
        }
        style={{ margin: '10px 0' }}
      />
      <Checkbox indeterminate={partiallySelected} onChange={toggleAll} checked={allSelected}>
        {allSelected ? (
          <a>{formatMessage({ id: 'component.check.all' })}</a>
        ) : (
          formatMessage({ id: 'component.check.all' })
        )}
      </Checkbox>
      <Divider style={{ margin: '10px 0' }} />
      <div style={{ height: 400, width: '100%', overflow: 'auto' }}>
        <Row gutter={[16, 16]}>
          {filterValue?.map((option) => (
            <Col span={8} key={option.value}>
              <Checkbox checked={isSelected(option.value)} onClick={() => toggle(option.value)}>
                {selected?.indexOf(option.value) !== -1 ? <a>{option.label}</a> : option.label}
              </Checkbox>
            </Col>
          ))}
        </Row>
      </div>
    </>
  );
};

export default memo(CustomCheckGroup);
