import {styled} from 'styled-components'
import {ProFormList, ProFormSelect, ProFormText,ProFormGroup,ProFormSegmented} from '@ant-design/pro-components'
import {memo, useState, forwardRef} from 'react'
import { LOGIC_TYPE} from "../pages/IndexDefine/constants";
import useI18NPrefix from "../hooks/useI18NPrefix";

const component = forwardRef(({
  type,
  options,
  value
},ref) => {
  const t = useI18NPrefix('global');
  const [count,setCount]=useState(0);

  const joinLogic=(index)=>{
    const display = ( index !== (count-1) )
    if (display){
      return <ProFormSegmented
        name="relation"
        fieldProps={{style:{marginLeft:"50%"}}}
        initialValue="AND"
        valueEnum={{
          AND: t('operation.and'),
          OR: t('operation.or'),
        }}
      />
    }
  }

  return (
    <Container ref={ref}>
      <CustomFromList
        name="filters"
        wrapperCol={{span:24}}
        initialValue={value}
        creatorButtonProps={{
          creatorButtonText: t("operation.attributes")
        }}
        onAfterAdd={(e,s,c)=>setCount(c)}
        onAfterRemove={(e,c)=>setCount(c)}
        itemContainerRender={(doms,{index})=> {
          return <>
            {doms}
            {joinLogic(index)}
          </>
        }}
      >
        <ProFormGroup key="group">
          <ProFormSelect
            width="sm"
            name="bizName"
            placeholder={t("placeholder.fields")}
            rules={[{ required: true }]}
            options={options}
          />
          <ProFormSelect
            width="sm"
            name="operator"
            placeholder={t("placeholder.logic")}
            rules={[{ required: true }]}
            valueEnum={LOGIC_TYPE}
          />
          <ProFormText
            width={250}
            name="value"
            placeholder={t("placeholder.value")}
            rules={[{ required: true }]}
          />
        </ProFormGroup>
      </CustomFromList>
    </Container>
  )
})

export const LogicPanel = memo(component)

const CustomFromList=styled(ProFormList)`
  .ant-form-item {
    margin-bottom: 5px;
  }
  .ant-pro-form-list-action{
    margin-block-end: 0;
    line-height: 0;
    height: 29px;
  }
`
const Container = styled.div`
  width: 95%;
  padding-block-end: 1px;
  padding-block-start: 15px;
  padding-inline-end: 20px;
  padding-inline-start: 20px;
  background-color: #f5f5f5;
  min-height: 68px;
`