import { Button, Checkbox, Form, FormInstance, InputNumber, Select } from 'antd'
import { Dayjs } from 'dayjs'
import { useEffect, useState } from 'react'

import {
  createCommitmentInvoice,
  useListTenantPaymentMethods
} from 'apiClient/services/billing'
import {
  FormsBillingConfig,
  FormsPaymentMethod
} from 'apiClient/services/billing/interface'
import DatePicker from 'components/DatePicker'
import ModalForm from 'components/ModalForm'

const PaymentCodeSelect = ({
  payment,
  form
}: {
  payment: FormsPaymentMethod
  form: FormInstance
}) => {
  const [showPaymentCode, setShowPaymentCode] = useState(false)
  useEffect(() => {
    if (showPaymentCode && !form.getFieldValue('payment_code')) {
      form.setFieldsValue({
        payment_code: payment.payment_code
      })
    }
  }, [payment, showPaymentCode, form])
  return (
    <>
      <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
        <Checkbox
          checked={showPaymentCode}
          onChange={(e) => setShowPaymentCode(e.target.checked)}
        >
          Specific Payment Code
        </Checkbox>
      </Form.Item>
      {showPaymentCode && (
        <Form.Item name="payment_code" label="Payment Code">
          <Select>
            <Select.Option value={payment.payment_code || ''}>
              {payment.payment_code}(Primary)
            </Select.Option>
            {!!payment.payment_sub_code && (
              <Select.Option value={payment.payment_sub_code}>
                {payment.payment_sub_code}(Secondary)
              </Select.Option>
            )}
          </Select>
        </Form.Item>
      )}
    </>
  )
}

export const CreateCommitmentInvoice: React.FC<
  React.PropsWithChildren<{
    billingConfig: FormsBillingConfig
    orgId: string
    onComplete?: () => void
  }>
> = ({ billingConfig, orgId, onComplete }) => {
  const [opened, setOpened] = useState(false)

  const onClose = () => {
    setOpened(false)
  }

  const { data: paymentData } = useListTenantPaymentMethods(
    orgId,
    billingConfig.billing_config_id
  )

  const payment = paymentData?.data?.[0] || {}

  const onSubmit = async (data: {
    amount: string
    time: Dayjs
    payment_code?: string
  }) => {
    await createCommitmentInvoice(orgId, billingConfig.billing_config_id, {
      binded_billing_config_id: billingConfig.billing_config_id,
      amount: data.amount,
      time: `${data.time.format('YYYY-MM-DD')}T00:00:00Z`,
      payment_code: data.payment_code
    })
    onComplete?.()
    onClose()
  }

  const renderFields = (form: FormInstance) => {
    return (
      <>
        <Form.Item
          name="amount"
          label="Amount"
          rules={[{ required: true, message: 'required' }]}
        >
          <InputNumber
            style={{ width: 200 }}
            stringMode
            min={'0'}
            step="0.01"
            precision={2}
          ></InputNumber>
        </Form.Item>
        <Form.Item
          name="time"
          label="Date"
          rules={[{ required: true, message: 'required' }]}
        >
          <DatePicker style={{ width: 200 }} picker="date" />
        </Form.Item>
        {!!payment.payment_sub_code && (
          <PaymentCodeSelect payment={payment} form={form} />
        )}
      </>
    )
  }

  return (
    <div>
      <Button type="primary" onClick={() => setOpened(true)}>
        Create Commitment Invoice
      </Button>
      <ModalForm
        width={560}
        visible={opened}
        title="Creat Commitment Invoice"
        name="create-commitment-invoice1"
        onSubmit={onSubmit}
        onCancel={onClose}
        getFields={renderFields}
        destoryOnClose
      ></ModalForm>
    </div>
  )
}
