import {GetProps, message, Tabs} from 'antd';
import {act, FC, Ref, useImperativeHandle} from "react";
import styled from "styled-components";
import {useStateData} from '@jeoshi-design/rex-design.hooks.core';

export const TabRadio: FC<ITabRadioProps> = ({
  marginBottom = 10,
  actionRef,
  fieldKey,

  defaultActiveKey,
  items,
  onChange,
  ...otherProps
}) => {
  const {state, update} = useStateData(() => ({
    activeKey: defaultActiveKey || items?.find((item) => !item.disabled)?.key || '',
    fetchLoading: false,
  }));

  useImperativeHandle<{}, ITabRadioActionRef>(actionRef, () => {
      return {
        getValues: () => {
          return {
            [`${fieldKey}`]: state.activeKey,
          };
        },
        setValues: (data) => {
          state.activeKey = data;
          update();
        },
        setLoading: (val) => {
          state.fetchLoading = val;
          update();
        }
      };
    });

  return (
    <CustomTabsStyle marginBottom={marginBottom}>
      <Tabs
        {...otherProps}
        activeKey={state.activeKey}
        items={items}
        onChange={(key) => {
          if (state.fetchLoading) {
            // message.warning('请先完成当前操作');
            return;
          }
          state.activeKey = key;
          update();
          onChange?.(key);
        }}
      />
    </CustomTabsStyle>
  )
};

export interface ITabRadioProps extends GetProps<typeof Tabs> {
  /** 下边距 */
  marginBottom?: string | number;
  /** 属性key */
  fieldKey?: string;
  /** 操作对象 */
  actionRef?: Ref<ITabRadioActionRef>;
}

export interface ITabRadioActionRef {
  /** 获取过滤条件 */
  getValues: () => Record<string, string>;
  /** 设置表单数据 */
  setValues: (data: string) => void;
  setLoading: (loading: boolean) => void;
}



const CustomTabsStyle = styled.div<{marginBottom: string | number}>`
  > .ant-tabs > .ant-tabs-nav {
    margin-bottom: ${(props) => typeof props.marginBottom === 'number' ? `${props.marginBottom}px` : props.marginBottom};
  }
`;
