import { useControllableValue } from 'ahooks';
import { message, Space, Timeline } from 'antd';
import { useCallback, useContext, useRef, type CSSProperties } from 'react';
import { useIntl } from 'umi';
import { AuditContainerContext } from '.';
import { requestReasonDel } from './api';
import type { ReasonDataType } from './ReasonItem';
import ReasonItem from './ReasonItem';

const styles: Record<'h3' | 'timeline', CSSProperties> = {
  h3: {
    marginBottom: 0,
  },
  timeline: {
    marginTop: 6.5,
    marginLeft: 6.5,
  },
};

export interface ReasonProps {
  auditDetail?: { reason?: ReasonDataType[]; initiator?: any };
  style?: CSSProperties;
  foldLength?: number;
  fold?: boolean;
  readOnly?: boolean;
  onRefresh?: () => Promise<any>;
  onFold?: (fold: boolean) => void;
}

const Reason = (props: ReasonProps) => {
  const { auditDetail, style, foldLength = 3, readOnly, onRefresh } = props;
  const { formatMessage } = useIntl();
  const { reason, initiator } = auditDetail ?? {};
  const { wrapperRef } = useContext(AuditContainerContext);
  const timeoutRef = useRef<NodeJS.Timeout>();

  const delHandler = useCallback(
    async (id: number) => {
      try {
        await requestReasonDel(id);
        onRefresh?.();
        message.success(formatMessage({ id: 'component.AuditList.reason.del.success' }));
      } catch (e) {}
    },
    [formatMessage, onRefresh],
  );

  const [fold, setFold] = useControllableValue<boolean>(props, {
    valuePropName: 'fold',
    trigger: 'onFold',
  });

  const yxReason = reason?.filter((__, index: number) => (fold ? index < foldLength : true)) ?? [];
  const totalLength = reason?.length ?? 0;

  const scrollBottom = useCallback(() => {
    clearTimeout(timeoutRef.current);
    timeoutRef.current = setTimeout(() => {
      const ele = wrapperRef?.current;
      if (ele) {
        ele.scrollTo({ behavior: 'smooth', top: ele.scrollHeight });
      }
    }, 300);
  }, [wrapperRef]);

  return (
    <Space size={'large'} direction={'vertical'} style={style}>
      <h3 style={styles.h3}>
        {formatMessage({ id: 'base.apply.reason' })}({reason?.length ?? 0})
      </h3>

      <Timeline style={styles.timeline}>
        {yxReason.map((item: ReasonDataType, index: number) => {
          return (
            <ReasonItem
              key={item.id}
              {...item}
              canFold={totalLength > foldLength}
              fold={fold}
              restLength={totalLength - foldLength}
              onFold={() => setFold(true)}
              onExpand={() => {
                setFold(false);
                scrollBottom();
              }}
              initiator={initiator}
              index={index}
              length={yxReason.length}
              readOnly={readOnly}
              onDelete={delHandler}
            />
          );
        })}
      </Timeline>
    </Space>
  );
};

export default Reason;
