import { useEffect, useRef } from 'react'
import { useTranslation } from '@/i18n.ts'
import { useStyle } from './style.ts'
import {
  Alert,
  Button,
  Divider,
  Form,
  Input,
  InputNumber,
  InputRef,
  notification,
  Flex
} from 'antd'
import { useAtom, useAtomValue } from 'jotai'
import TwoColPageLayout from '@/layout/TwoColPageLayout.tsx'
import { ProCard } from '@ant-design/pro-components'
import { PlusOutlined } from '@ant-design/icons'
import Glass from '@/components/glass'
import { categoryAtom, saveOrUpdateCategoryAtom } from '@/store/videos/category.ts'
import Switch from '@/components/switch'
import CategoryTree from './components/CategoryTree.tsx'


const Category = () => {
  const { t } = useTranslation()
  const { styles, cx } = useStyle()
  const [ form ] = Form.useForm()
  const inputRef = useRef<InputRef>()
  const { mutate, isPending, isError, error } = useAtomValue(saveOrUpdateCategoryAtom)
  const [ current, setCurrent ] = useAtom(categoryAtom)

  useEffect(() => {

    if (isError) {
      notification.error({
        message: t('message.error', '错误'),
        description: (error as any).message ?? t('message.saveFail', '保存失败'),
      })
    }
  }, [ isError ])

  useEffect(() => {
    if (current?.id === 0 && inputRef.current) {
      inputRef.current.focus()
    }
  }, [ current ])
  return (
          <TwoColPageLayout
                  leftPanel={<>
                    <ProCard title={t('videos.category.title', '分类')}>

                      <CategoryTree form={form}/>
                    </ProCard>
                    <div className={styles.treeActions}>
                      <Divider style={{ flex: 1, margin: '8px 0' }}/>
                      <Button style={{ flex: 1 }} size={'small'}
                              block={true} type={'dashed'}
                              icon={<PlusOutlined/>}
                              onClick={() => {
                                const data = {
                                  name: '',
                                  extend: {
                                    class: '',
                                    area: '',
                                    lang: '',
                                    year: '',
                                    tag: '',
                                    state: '',
                                    version: '',
                                  },
                                  sort: 0,
                                  status: 1,
                                  parent_id: 0,
                                  id: 0,
                                }
                                setCurrent(data)
                                form.setFieldsValue(data)
                              }}
                      >{t('actions.news')}</Button>
                    </div>
                  </>}
          >
            <Glass
                    enabled={current?.id === undefined}
                    description={<>
                      <Alert
                              message={t('message.infoTitle', '提示')}
                              description={t('videos.category.form.empty', '请从左侧选择一行数据操作')}
                              type="info"
                      />
                    </>}
            >


              <ProCard title={t('videos.category.setting', '编辑')}>
                <Form form={form}
                      initialValues={current!}
                      labelAlign="right"
                      labelWrap
                      colon={false}
                      className={cx(styles.form, {
                        [styles.emptyForm]: current?.id === undefined
                      })}
                >
                  <Form.Item hidden={true} label={'id'} name={'id'}>
                    <Input disabled={true}/>
                  </Form.Item>
                  <Form.Item

                          rules={[
                            { required: true, message: t('rules.required') }
                          ]}
                          label={t('videos.category.form.name', '名称')} name={'name'}>
                    <Input ref={inputRef as any}
                           placeholder={t('videos.category.form.name', '名称')}/>
                  </Form.Item>


                  <Form.Item label={t('videos.category.form.tag', 'Tag')}
                             name={[ 'extend', 'class' ]}
                  >
                    <Input/>
                  </Form.Item>
                  <Form.Item label={t('videos.category.form.area', '地区')}
                             name={[ 'extend', 'area' ]}
                  >
                    <Input/>
                  </Form.Item>
                  <Form.Item label={t('videos.category.form.lang', '语言')}
                             name={[ 'extend', 'lang' ]}
                  >
                    <Input/>
                  </Form.Item>
                  <Form.Item label={t('videos.category.form.year', '年份')}
                             name={[ 'extend', 'year' ]}
                  >
                    <Input/>
                  </Form.Item>
                  <Form.Item label={t('videos.category.form.state', '资源')}
                             name={[ 'extend', 'state' ]}
                  >
                    <Input/>
                  </Form.Item>
                  <Form.Item label={t('videos.category.form.version', '版本')}
                             name={[ 'extend', 'version' ]}
                  >
                    <Input/>
                  </Form.Item>

                  <Flex flex={1}>
                    <Flex flex={1}>
                      <Form.Item label={t('videos.category.form.sort', '排序')} name={'sort'}>
                        <InputNumber/>
                      </Form.Item>
                    </Flex>
                    <Flex flex={1}>
                      <Form.Item label={t('videos.category.form.status', '状态')}
                                 name={'status'}>
                        <Switch/>
                      </Form.Item>
                    </Flex>
                  </Flex>

                  <Form.Item label={' '}>
                    <Button type="primary"
                            htmlType={'submit'}
                            loading={isPending}
                            onClick={() => {
                              form.validateFields().then((values) => {
                                mutate({
                                  ...values,
                                  status: values.status ? 1 : 0,
                                  extend: JSON.stringify(values.extend),
                                })
                              })
                            }}
                    >
                      {t('videos.category.form.save', '保存')}
                    </Button>
                  </Form.Item>

                </Form>
              </ProCard>

            </Glass>
          </TwoColPageLayout>
  )
}

export default Category