import { useState } from 'react'
import { Table, Form, Modal, Button, Radio, Input, InputNumber, Checkbox, DatePicker, Space } from 'antd'
import { useTranslation } from 'react-i18next'
import dayjs from 'dayjs'
import BatchImportPrice from './BatchImportPrice'
import { useDatePresets } from '@/hooks/useDatePresets'
import useProductsStore from '@/stores/Products/Index'

const { RangePicker } = DatePicker

const ProductInfoQuotation = ({ editable, ...props }) => {

  const { t } = useTranslation()

  const [isQuotationModalOpen, setQuotationModalOpen] = useState(false)
  const [quotationForm] = Form.useForm()

  const datePresets = useDatePresets()

  const [editingProduct] = useProductsStore((state) => [state.editingProduct])
  const [batchImportPriceVisible, setBatchImportPriceVisible] = useState(false)
  const [quotationTableVisible, setQuotationTableVisible] = useState(false)
  const [quotation, setQuotation] = useState([])
  const [batchImportData, setBatchImportData] = useState([])


  const handleBatchImportData = (data) => {
    setBatchImportData(data)
  }

  const handleBatchImportOK = () => {
    const tempBatchImportData = batchImportData.map((item) => {
      const { tag, validPeriod, ...rest } = item
      return rest
    })
    const newData = [...quotation, ...tempBatchImportData]
    const sortedData = [...newData].sort((a, b) => {
      if (a.group_size_min !== b.group_size_min) {
        return a.group_size_min - b.group_size_min
      }

      return a.group_size_max - b.group_size_max
    })

    setQuotation(sortedData)
    setBatchImportPriceVisible(false)
  }
  const quotationTableVisibleOK = () => {
    const tempQuotation = [...quotation]

    const sortedData = [...tempQuotation].sort((a, b) => {
      const aValidPeriod = dayjs(a.use_dates_end).diff(dayjs(a.use_dates_start))
      const bValidPeriod = dayjs(b.use_dates_end).diff(dayjs(b.use_dates_start))

      if (aValidPeriod !== bValidPeriod) {
        return aValidPeriod - bValidPeriod
      }
      const aGroupSize = a.group_size_max - a.group_size_min
      const bGroupSize = b.group_size_max - b.group_size_min

      return aGroupSize - bGroupSize
    })
    setQuotation(sortedData)
    setQuotationTableVisible(false)
  }
  const quotationTableVisibleCancel = () => {
    setQuotationTableVisible(false)
  }

  const handleDelete = (index) => {
    const newData = [...quotation]
    newData.splice(index, 1)
    const sortedData = [...newData].sort((a, b) => {
      const aValidPeriod = dayjs(a.use_dates_end).diff(dayjs(a.use_dates_start))
      const bValidPeriod = dayjs(b.use_dates_end).diff(dayjs(b.use_dates_start))
      if (aValidPeriod !== bValidPeriod) {
        return aValidPeriod - bValidPeriod
      }
      const aGroupSize = a.group_size_max - a.group_size_min
      const bGroupSize = b.group_size_max - b.group_size_min

      return aGroupSize - bGroupSize
    })
    setQuotation(sortedData)
  }

  const onQuotationSeleted = async (quotation) => {
    // 转换为 RangePicker 赋值格式
    quotation.use_dates = [dayjs(quotation.use_dates_start), dayjs(quotation.use_dates_end)]
    quotationForm.setFieldsValue(quotation)
    setQuotationModalOpen(true)
  }

  const onNewQuotation = () => {
    // const emptyQuotation = newEmptyQuotation()
    // quotationForm.setFieldsValue(emptyQuotation)
    // setQuotationModalOpen(true)
  }

  const onQuotationFinish = (values) => {
    console.info(values)
    // saveOrUpdateQuotation(values)
    //   .then(() => {
    //     setQuotationModalOpen(false)
    //   })
    //   .catch(ex => {
    //     notification.error({
    //       message: 'Notification',
    //       description: ex.message,
    //       placement: 'top',
    //       duration: 4,
    //     })
    //   })
  }

  const onQuotationFailed = (error) => {
    console.log('Failed:', error)
    // form.resetFields()
  }

  const quotationColumns = [
    { title: t('products:adultPrice'), dataIndex: 'adult_cost', width: '4rem' },
    { title: t('products:childrenPrice'), dataIndex: 'child_cost', width: '4rem' },
    { title: t('products:currency'), dataIndex: 'currency', width: '4rem' },
    {
      title: t('products:Types'),
      dataIndex: 'unit_name',
      width: '4rem',
      render: (text) => (text === '0' ? '每人' : text === '1' ? '每团' : text),
    },
    {
      title: t('products:number'),
      dataIndex: 'group_size',
      width: '4rem',
      render: (_, record) => `${record.group_size_min}-${record.group_size_max}`,
    },

    {
      title: t('products:validityPeriod'),
      dataIndex: 'use_dates',
      width: '6rem',
      render: (_, record) => `${record.use_dates_start}-${record.use_dates_end}`,
    },

    { title: t('products:Weekdays'), dataIndex: 'weekdays', width: '4rem' },
    {
      title: t('products:operation'),
      dataIndex: 'operation',
      width: '3%',
      render: (_, quotation) => {
        return (
          <Space>
            <Button type='link' onClick={() => onQuotationSeleted(quotation)}>{t('Edit')}</Button>
            <Button type='link' danger onClick={() => handleDelete(quotation)}>{t('Delete')}</Button>
          </Space>
        )
      },
    },
  ]

  return (
    <>
      <h2>{t('products:EditComponents.Quotation')}</h2>
      <Table
        rowKey={'id'}
        bordered
        dataSource={editingProduct.quotation}
        columns={quotationColumns}
        pagination={false}
      />
      {
        // editable &&
        <Button onClick={() => setQuotationModalOpen(true)} type='primary' ghost style={{ marginTop: 16 }}>
          {t('products:addQuotation')}
        </Button>
      }

      {
        // editable &&
        <Button onClick={() => setBatchImportPriceVisible(true)} type='primary' ghost style={{ marginTop: 16, marginLeft: 16 }}>
          批量添加
        </Button>
      }

      <Modal title='批量设置价格' open={batchImportPriceVisible} onOk={handleBatchImportOK} onCancel={() => setBatchImportPriceVisible(false)} width={'90%'}>
        <BatchImportPrice onBatchImportData={handleBatchImportData} />
      </Modal>

      <Modal
        centered
        okButtonProps={{
          autoFocus: true,
          htmlType: 'submit',
        }}
        title={t('account:detail')}
        open={isQuotationModalOpen} onCancel={() => setQuotationModalOpen(false)}
        destroyOnClose
        forceRender
        modalRender={(dom) => (
          <Form
            name='quotationForm'
            form={quotationForm}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            className='max-w-2xl'
            onFinish={onQuotationFinish}
            onFinishFailed={onQuotationFailed}
            autoComplete='off'
          >
            {dom}
          </Form>
        )}
      >
        <Form.Item name='id' className='hidden' ><Input /></Form.Item>
        <Form.Item
          label={t('products:adultPrice')}
          name='adult_cost'
          rules={[
            {
              required: true,
              message: t('products:Validation.adultPrice'),
            },
          ]}
        >
          <InputNumber style={{width: '100%'}} />
        </Form.Item>
        <Form.Item
          label={t('products:childrenPrice')}
          name='child_cost'
          rules={[
            {
              required: true,
              message: t('products:Validation.childrenPrice'),
            },
          ]}
        >
          <InputNumber style={{width: '100%'}} />
        </Form.Item>
        <Form.Item
          label={t('products:currency')}
          name='currency'
          rules={[
            {
              required: true,
              message: t('products:Validation.currency'),
            },
          ]}
        >
          <Radio.Group>
            <Radio value='RMB'>RMB</Radio>
            <Radio value='USD'>USD</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label={t('products:Types')}
          name='unit_name'
          rules={[
            {
              required: true,
              message: t('products:Validation.unit_name'),
            },
          ]}
        >
        <Radio.Group>
          <Radio value='0'>每人</Radio>
          <Radio value='1'>每团</Radio>
        </Radio.Group>
        </Form.Item>
        <Form.Item
          label={t('products:number')}
          name='group_size_min'
          rules={[
            {
              required: true,
              message: t('products:Validation.group_size_min'),
            },
          ]}
        >
          <InputNumber style={{width: '100%'}} />
        </Form.Item>
        <Form.Item
          label={t('products:number')}
          name='group_size_max'
          rules={[
            {
              required: true,
              message: t('products:Validation.group_size_max'),
            },
          ]}
        >
          <InputNumber style={{width: '100%'}} />
        </Form.Item>
        <Form.Item
          label={t('products:validityPeriod')}
          name='use_dates'
          rules={[
            {
              required: true,
              message: t('products:Validation.use_dates'),
            },
          ]}
        >
            <RangePicker presets={datePresets} style={{width: '100%'}} />
        </Form.Item>
        <Form.Item
          label={t('products:Weekdays')}
          name='weekdays'
        >
          <Checkbox.Group options={['5', '6', '7']} />
        </Form.Item>
      </Modal>
    </>
  )
}

export default ProductInfoQuotation
