import { NodesRef } from '@tarojs/taro';

import { useCallback, useState } from 'react';

import SafeBottomPadding from '@/components/safe-bottom-padding';
import SearchInput from '@/components/search';
import UserJobList from '@/components/user-job-list';
import { UserJobType } from '@/constants/job';
import useListHeight, { IUseListHeightProps } from '@/hooks/use-list-height';

import './index.less';

const PREFIX = 'my-declaration';
const SEARCH_CLASS = `${PREFIX}__search`;
const SAFE_PADDING_BOTTOM_CLASS = `${PREFIX}__safe-padding-bottom`;
const CALC_LIST_PROPS: IUseListHeightProps = {
  selectors: [`.${SEARCH_CLASS}`, `.${PREFIX}`, `.${SAFE_PADDING_BOTTOM_CLASS}`],
  calc: (
    rects: [
      NodesRef.BoundingClientRectCallbackResult,
      NodesRef.BoundingClientRectCallbackResult,
      NodesRef.BoundingClientRectCallbackResult,
    ]
  ) => {
    const [searchRect, pageRect, safePaddingRect] = rects;
    return pageRect.bottom - searchRect.height - safePaddingRect.height;
  },
};

export default function Declaration() {
  const listHeight = useListHeight(CALC_LIST_PROPS);
  const [focus, setFocus] = useState(false);
  const [value, setValue] = useState<string>('');
  const [keyWord, setKeyWord] = useState<string>('');

  const handleClickSearch = useCallback(() => {
    if (value === keyWord) {
      return;
    }
    setFocus(false);
    setKeyWord(value);
  }, [value, keyWord]);

  const handleSearchClear = useCallback(() => {
    setValue('');
    setKeyWord('');
  }, []);

  const handleSearchBlur = useCallback(() => setFocus(false), []);

  const handleSearchFocus = useCallback(() => setFocus(true), []);

  const handleSearchChange = useCallback(e => setValue(e.detail.value), []);

  return (
    <div className={PREFIX}>
      <SearchInput
        focus={focus}
        value={value}
        placeholder="搜索我应聘的"
        className={SEARCH_CLASS}
        onClear={handleSearchClear}
        onBlur={handleSearchBlur}
        onFocus={handleSearchFocus}
        onSearch={handleClickSearch}
        onChange={handleSearchChange}
      />
      <UserJobList type={UserJobType.MyDeclared} keyWord={keyWord} listHeight={listHeight} />
      <SafeBottomPadding className={SAFE_PADDING_BOTTOM_CLASS} />
    </div>
  );
}
