<script lang="tsx">
import { ref } from 'vue';
import { Sender } from 'ant-design-x-vue';
import { Tooltip } from 'ant-design-vue';

interface SenderInputProps {
  modelValue?: string;
  loading?: boolean;
  placeholder?: string;
}

export default {
  name: 'SenderInput',
  props: {
    modelValue: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '随时告诉我你想做什么，比如查数据、发任务、写内容，我会立刻帮你完成。',
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['update:modelValue', 'submit', 'cancel'],
  setup(props: SenderInputProps, { emit, expose }) {
    const senderRef = ref(null);
    const localSearchValue = ref(props.modelValue);

    const isEmptyValue = computed(() => !localSearchValue.value.trim());
    
    watch(
      () => props.modelValue,
      (newValue) => {
        console.log(newValue);
        localSearchValue.value = newValue || '';
      },
    );

    const handleSubmit = () => {
      if (isEmptyValue.value) {
        return;
      }
      emit('submit', localSearchValue.value);
    };
    const handleCancel = () => {
      emit('cancel');
    };

    const focus = () => {
      senderRef.value?.focus?.();
    };

    const renderActions = () => {
      if (props.loading) {
        return (
          <Tooltip title="停止生成" onClick={handleCancel}>
            <div class="w-32px h-32px p-6px flex justify-center items-center rounded-50% bg-#6D4CFE cursor-pointer">
              <div class="w-12px h-12px rounded-2px bg-#FFF"></div>
            </div>
          </Tooltip>
        );
      }

      return (
        <div
          onClick={handleSubmit}
          class={`submit-btn  w-32px h-32px p-6px flex justify-center items-center rounded-50% cursor-pointer ${
            isEmptyValue.value ? 'opacity-50' : ''
          }`}
        >
          <icon-arrow-right size={20} class="color-#FFFFFF" />
        </div>
      );
    };

    expose({
      focus,
    });

    return () => (
      <div class="sender-input-wrap full h-120px">
        <Sender
          v-model:value={localSearchValue.value}
          ref={senderRef}
          onChange={(value: string) => emit('update:modelValue', value.trim())}
          onSubmit={handleSubmit}
          class="h-full w-full mb-24px"
          placeholder={props.placeholder}
          actions={() => renderActions()}
        />
      </div>
    );
  },
};
</script>

<style lang="scss" scoped>
.sender-input-wrap {
  :deep(.ant-sender) {
    .submit-btn {
      background: linear-gradient(125deg, #6d4cfe 32.25%, #3ba1f0 72.31%),
        linear-gradient(113deg, #6d4cfe 0%, #b93bf0 100%);
    }
  }
}
</style>
