import _identity from 'lodash/identity'
import _isEmpty from 'lodash/isEmpty'
import React, { useMemo, useState } from 'react'
import SVG from 'react-inlinesvg'

import EditSvg from '../../assets/images/edit.svg'
import { CustomFieldsForm } from './CustomFieldsForm'
import { CustomFieldTypes } from './index'
import { ITicketTypes } from './ticketsTable'
import {
  createCustomFieldsUpdateBody,
  isFieldUpdatable,
  renderCustomFieldValue,
} from './utils'

interface HolderCustomFieldsProps {
  ticket: ITicketTypes;
  holderCustomFields: CustomFieldTypes[];
  handleTicketHoldersUpdate: (values: Record<string, any>, ticketHash: string) => void;
}

const TicketHolderCustomFields = ({
  ticket,
  holderCustomFields,
  handleTicketHoldersUpdate = _identity,
}: HolderCustomFieldsProps) => {
  const [showHolderCustomFieldsSection, setShowHolderCustomFieldsSection] =
    useState(false)

  const [allowedHolderCustomFields, notAllowedHolderCustomFields] = useMemo(() => {
    const allowedFields: CustomFieldTypes[] = []
    const notAllowedFields: CustomFieldTypes[] = []

    holderCustomFields.forEach((field: CustomFieldTypes) => {
      if (isFieldUpdatable(field)) {
        allowedFields.push(field)
      } else {
        notAllowedFields.push(field)
      }
    })
    return [allowedFields, notAllowedFields]
  }, [holderCustomFields])

  const holderEditableFieldsFormInitialValues = useMemo(
    () => getHolderCustomFieldsInitialValues(holderCustomFields),
    [holderCustomFields]
  )

  const handleFormClose = () => {
    setShowHolderCustomFieldsSection(false)
  }

  const handleForSubmit = (values: Record<string, any>) => {
    // Collect all updatable and non updatable values for bulk update
    const fullUpdatableValues = createCustomFieldsUpdateBody(
      values,
      notAllowedHolderCustomFields
    )
    setShowHolderCustomFieldsSection(false)
    handleTicketHoldersUpdate(fullUpdatableValues, ticket.hash)
  }

  function getHolderCustomFieldsInitialValues(fields: Array<CustomFieldTypes>) {
    const initialValues: { [key: string]: string | boolean | string[] } = {}

    for (const field of fields) {
      if (isFieldUpdatable(field)) {
        initialValues[field.name] =
          field.type === 'checkbox' ? Boolean(field.value) : field.value || ''
      }
    }
    return initialValues
  }

  return (
    <>
      <div className="holder-custom-fields">
        {!_isEmpty(allowedHolderCustomFields) && <SVG src={EditSvg} onClick={() => setShowHolderCustomFieldsSection(true)} />}
        {holderCustomFields.map((customField: CustomFieldTypes) => (
          <div className="info-item" key={customField.id}>
            <b>{customField.label} :</b> {renderCustomFieldValue(customField)}
          </div>
        ))}
      </div>
      {showHolderCustomFieldsSection && (
        <div className="custom-fields-block show">
          <p className="editable-ticket-id">Edit ticket {ticket.hash}</p>
          <CustomFieldsForm
            initialValues={holderEditableFieldsFormInitialValues}
            fields={allowedHolderCustomFields}
            handleFormSubmit={handleForSubmit}
            handleFormClose={handleFormClose}
          />
        </div>
      )}
    </>
  )
}

export { TicketHolderCustomFields }
