'use client'
import { useState } from 'react'
import useSWR from 'swr'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'
import DetailModal from './detail-modal'
import { useContext } from 'use-context-selector'
import { RiAddLine } from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import { delKnowledge, fetchKnowledges } from '@/service/common'
import I18n from '@/context/i18n'
import { useAppContext } from '@/context/app-context'
import LogoEmbeddedChatHeader from '@/app/components/base/logo/logo-embedded-chat-header'
import { useProviderContext } from '@/context/provider-context'
import { Plan } from '@/app/components/billing/type'
import Button from '@/app/components/base/button'
import UpgradeBtn from '@/app/components/billing/upgrade-btn'
import { NUM_INFINITE } from '@/app/components/billing/config'
import { LanguagesSupported } from '@/i18n/language'
import cn from '@/utils/classnames'
import Confirm from '@/app/components/base/confirm'
import useTimestamp from '@/hooks/use-timestamp'
dayjs.extend(relativeTime)

const KnowledgesPage = () => {
  const { t } = useTranslation()
  const { locale } = useContext(I18n)
  const { formatTime } = useTimestamp()

  const ServiceTypeMap: any = {
    QUESTION_ANSWER: '智能问答',
    SEARCH: '智能搜索',
    RECOMMEND: '智能推荐',
  }
  const StatusMap: any = {
    false: '未启用',
    true: '已启用',
  }
  const { userProfile, currentWorkspace, isCurrentWorkspaceOwner, isCurrentWorkspaceManager, systemFeatures } = useAppContext()
  const { data, mutate }: any = useSWR(
    {
      url: '/external_applications',
      params: {
        page: 1,
        limit: 99999,
      },
    },
    fetchKnowledges,
  )
  const [detailModalVisible, setDetailModalVisible] = useState(false)
  const [transfer, setTransfer] = useState<any>({
    mode: 'add',
    row: null,
  })
  const knowledgeList = data?.data || []
  const { plan, enableBilling } = useProviderContext()
  const isNotUnlimitedMemberPlan = enableBilling && plan.type !== Plan.team && plan.type !== Plan.enterprise
  const isMemberFull = enableBilling && isNotUnlimitedMemberPlan && knowledgeList.length >= plan.total.teamMembers

  const [showConfirmDelete, setShowConfirmDelete] = useState(false)
  const [row, setRow] = useState<any>({})
  const handleDel = async () => {
    try {
      await delKnowledge({
        url: `/external_applications/${row.id}`,
        body: {},
      })
      setShowConfirmDelete(false)
      mutate()
    }
    catch (e) { }
  }
  return (
    <>
      <div className='flex flex-col'>
        <div className='mb-4 flex items-center gap-3 rounded-xl border-l-[0.5px] border-t-[0.5px] border-divider-subtle bg-gradient-to-r from-background-gradient-bg-fill-chat-bg-2 to-background-gradient-bg-fill-chat-bg-1 p-3 pr-5'>
          <LogoEmbeddedChatHeader className='!h-12 !w-12' />
          <div className='grow'>
            <div className='system-md-semibold text-text-secondary'>{currentWorkspace?.name}</div>
            {enableBilling && (
              <div className='system-xs-medium mt-1 text-text-tertiary'>
                {isNotUnlimitedMemberPlan
                  ? (
                    <div className='flex space-x-1'>
                      <div>{t('billing.plansCommon.member')}{locale !== LanguagesSupported[1] && knowledgeList.length > 1 && 's'}</div>
                      <div className=''>{knowledgeList.length}</div>
                      <div>/</div>
                      <div>{plan.total.teamMembers === NUM_INFINITE ? t('billing.plansCommon.unlimited') : plan.total.teamMembers}</div>
                    </div>
                  )
                  : (
                    <div className='flex space-x-1'>
                      <div>{knowledgeList.length}</div>
                      <div>{t('billing.plansCommon.memberAfter')}{locale !== LanguagesSupported[1] && knowledgeList.length > 1 && 's'}</div>
                    </div>
                  )}
              </div>
            )}
          </div>
          {isMemberFull && (
            <UpgradeBtn className='mr-2' loc='member-invite' />
          )}
          <Button variant='primary' className={cn('shrink-0')} disabled={!isCurrentWorkspaceManager || isMemberFull}
            onClick={() => {
              setTransfer({ mode: 'add', row: null })
              setDetailModalVisible(true)
            }}>
            <RiAddLine className='mr-1 h-4 w-4' />
            新增
          </Button>
        </div>
        <div className='overflow-visible lg:overflow-visible'>
          <div className='flex min-w-[480px] items-center border-b border-divider-regular py-[7px]'>
            <div className='system-xs-medium-uppercase w-[100px] shrink-0 text-center text-text-tertiary'>服务类型</div>
            <div className='system-xs-medium-uppercase flex-1 shrink-0 text-center text-text-tertiary'>系统名称</div>
            <div className='system-xs-medium-uppercase flex-1 shrink-0 text-center text-text-tertiary'>URL</div>
            <div className='system-xs-medium-uppercase w-[80px] shrink-0 text-center text-text-tertiary'>连接应用状态</div>
            <div className='system-xs-medium-uppercase w-[160px] shrink-0 text-center text-text-tertiary'>更新时间</div>
            <div className='system-xs-medium-uppercase w-[120px] shrink-0 px-3 text-center text-text-tertiary'>操作</div>
          </div>
          <div className='relative min-w-[480px]'>
            {
              knowledgeList.map((know: any) => (
                <div key={know.id} className='flex justify-between border-b border-divider-subtle'>
                  <div className='system-sm-regular w-[100px] shrink-0 py-2 text-center text-text-secondary'>{ServiceTypeMap[know.type]}</div>
                  <div className='system-sm-regular flex-1 shrink-0 break-all py-2 text-center text-text-secondary'>{know.name}</div>
                  <div className='system-sm-regular flex-1 shrink-0 break-all py-2 text-center text-text-secondary'>{know.url}</div>
                  <div className='system-sm-regular w-[80px] shrink-0 py-2 text-center text-text-secondary'>{StatusMap[know.status]}</div>
                  <div className='system-sm-regular w-[160px] shrink-0 py-2 text-center text-text-secondary'>{formatTime(know.updated_at, t('appLog.dateTimeFormat') as string)}</div>
                  <div className='flex w-[120px] shrink-0 items-center justify-center'>
                    <Button variant='ghost-accent' size='small' className={cn('shrink-0')} disabled={!isCurrentWorkspaceManager || isMemberFull}
                      onClick={() => {
                        setTransfer({
                          mode: 'edit',
                          row: JSON.parse(JSON.stringify(know)),
                        })
                        setDetailModalVisible(true)
                      }}>
                      编辑
                    </Button>
                    <Button variant='ghost' size='small' className={cn('shrink-0 text-red-600')} disabled={!isCurrentWorkspaceManager || isMemberFull} onClick={() => {
                      setRow(know)
                      setShowConfirmDelete(true)
                    }}>
                      刪除
                    </Button>
                  </div>
                </div>
              ))
            }
          </div>
        </div>
      </div>
      {
        detailModalVisible && (
          <DetailModal
            transfer={transfer}
            onCancel={() => setDetailModalVisible(false)}
            onSend={() => {
              mutate()
            }}
          />
        )
      }
      {showConfirmDelete && (
        <Confirm
          title="删除确认"
          content={`请确认是否删除${row.name}？`}
          isShow={showConfirmDelete}
          onConfirm={handleDel}
          onCancel={() => setShowConfirmDelete(false)}
        />
      )}
    </>
  )
}

export default KnowledgesPage
