import { Input, ScrollView, Switch, Text, View } from '@tarojs/components'
import type { BaseEventOrig, SwitchProps } from '@tarojs/components'
import Taro, { useDidShow, useRouter } from '@tarojs/taro'
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import Popup from '@/components/popup'
import TextareaEnhance from '@/components/textareaEnhance'
import { CreateFavoriteApi, DelFavoriteApi, UpdateFavoriteApi } from '@/api/favorite'
import { alert } from '@/common/common'
import NormalButton from '@/components/normalButton'
import LayoutBlock from '@/components/layoutBlock'
import Divider from '@/components/divider'

const CollectionDetail = () => {
  const router = useRouter()
  const [isEdit, setEditStatus] = useState(false)
  const [submitData, setSubmitData] = useState({
    name: '',
    remark: '',
  })
  const currentData = useRef<Record<string, any> | undefined>(undefined)

  const getOtherReason = (val) => {
    setSubmitData(e => ({ ...e, remark: val }))
  }

  const changeInput = (val) => {
    setSubmitData(e => ({ ...e, name: val.detail.value }))
  }

  const [toTop, setToTop] = useState(false)

  useLayoutEffect(() => {
    console.log('isEdit', router.params.isEdit)
    Taro.setNavigationBarTitle({
      title: router.params.title as string,
    })
    const isEdit = JSON.parse(router.params.isEdit as string)
    if (isEdit) {
      console.log(router.params.editData)
      currentData.current = JSON.parse(router.params.editData as string)
      console.log('currentData', currentData.current)
      setSubmitData({
        name: currentData.current?.name,
        remark: currentData.current?.remark,
      })
      setToTop(currentData.current?.is_top)
    }
    else {
      currentData.current = undefined
    }
    setEditStatus(isEdit)
  }, [router.params])

  // 编辑保存
  const { fetchData: updateFavoriteFetchData } = UpdateFavoriteApi()
  const handleEditSave = async() => {
    if (!submitData.name) { return alert.none('请输入收藏夹名称!') }
    const res = await updateFavoriteFetchData({ ...submitData, id: currentData.current?.id, is_top: toTop ? 2 : 1 })
    if (res.success) {
      alert.success('编辑成功')
      setTimeout(() => {
        Taro.navigateBack()
      }, 1000)
    }
    else {
      alert.error('编辑失败')
    }
  }

  // 新增
  const { fetchData } = CreateFavoriteApi()
  // 新增保存
  const handleAddSave = async() => {
    if (!submitData.name) { return alert.none('请输入收藏夹名称!') }
    const res = await fetchData({ ...submitData, is_top: toTop ? 1 : 0 })
    if (res.success) {
      alert.success('创建成功')
      setTimeout(() => {
        Taro.navigateBack()
      }, 1000)
    }
    else {
      alert.error('创建失败')
    }
  }
  // 取消
  const handleCancel = () => {
    Taro.navigateBack()
  }
  // 删除
  const { fetchData: delFetchData } = DelFavoriteApi()
  const handleDelete = () => {
    Taro.showModal({
      content: '确认删除当前收藏夹?',
      cancelText: '取消',
      confirmText: '确认删除',
      confirmColor: '#E42945',
      async success(res) {
        if (res.confirm) {
          const res = await delFetchData({ id: currentData.current?.id })
          if (res.success) {
            alert.success('删除成功')
            setTimeout(() => {
              Taro.navigateBack()
            }, 1000)
          }
          else {
            alert.error('删除失败')
          }
        }
        else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }
  const handleChange = (e: BaseEventOrig<SwitchProps.onChangeEventDetail>) => {
    setToTop(e.detail.value)
  }
  return (
    <View className={styles.collection_con}>
      <View className={styles.collectionContent}>

        <LayoutBlock circle>

          <View className={styles.title_item}>
            <View className={styles.title}>收藏夹名称<Text style={{ color: 'red' }}>*</Text></View>
            <View className={styles.select}>
              <Input
                placeholder="请输入收藏夹名称"
                className={styles.input}
                alwaysEmbed
                cursorSpacing={100}
                onInput={changeInput}
                value={submitData?.name}
              />
            </View>
          </View>
          <Divider direction="horizontal" customStyles={{ margin: '24rpx 0' }}></Divider>
          <View className={styles.desc_item}>
            <View className={styles.title}>简介信息</View>
            <View className={styles.desc}>
              <TextareaEnhance customStyle={{ background: '#fff', border: 'none', padding: '0 20rpx', fontSize: '28rpx' }} defaultValue={submitData?.remark} onChange={getOtherReason} placeholder="请输入简介" />
            </View>
          </View>
        </LayoutBlock>
        <LayoutBlock circle>
          <View className={styles.toTopBar}>
            <View>
              <View className={styles.toTopTitle}>收藏夹置顶</View>
              <View className={styles.toTopTips}>提醒：会优先展示该收藏夹</View>
            </View>
            <Switch
              className={styles.switch}
              checked={toTop}
              color="#337fff"
              onChange={handleChange}
            />
          </View>
        </LayoutBlock>
      </View>
      {/* <View className={styles.btns_con}>
        <View className={styles.btns_two}>
          <View className={styles.verify_btn} onClick={() => onSubmit()}>
              确认
          </View>
        </View>
      </View> */}
      {
        isEdit
          ? <View className={styles.bottomBar}>
            <NormalButton plain type="danger" customStyles={{ width: '45%' }} round onClick={handleDelete}>
              删除
            </NormalButton>
            <NormalButton type="primary" round customStyles={{ width: '45%' }} onClick={handleEditSave}>
              保存
            </NormalButton>
          </View>
          : <View className={styles.bottomBar}>
            <NormalButton plain type="primary" customStyles={{ width: '45%' }} round onClick={handleCancel}>
              取消
            </NormalButton>
            <NormalButton type="primary" round customStyles={{ width: '45%' }} onClick={handleAddSave}>
              保存
            </NormalButton>
          </View>
      }
    </View>
  )
}
export default CollectionDetail
