'use client'

// React Imports
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useState } from 'react'

// MUI Imports
import { useSearchParams } from 'next/navigation'

import Card from '@mui/material/Card'

import CardContent from '@mui/material/CardContent'

// Third-party Imports
import { toast } from 'react-toastify'
import { useForm, Controller, SubmitHandler, FormProvider } from 'react-hook-form'

// Components Imports
import { Box, Button, Container, Grid, Tab, Tabs } from '@mui/material'

import { getTheMAinButtonOfScreens } from '@/views/Inventory/helpers/main-buttons-screen'

import { HandlePostDataWithGet } from '@/views/Inventory/helpers/HandlePostDataWithGet'

import { SaveDataAndChangeStateUpdate } from '@/views/Inventory/helpers/SaveDataAndChangeStateUpdate'
import { getData, postData, putData } from '@/utils/callApiwithToken'
import { fetchGenericData } from '@/views/Inventory/helpers/fetchGenericData'

import AddTermsForm from './AddTermsTemplateForm'
import PaymentTerms from '../PaymentTerms'
// Utility function import

type FormValues = {
  templateName: string
  foreignTemplateName: string
  discerption: string
  isActive: boolean
  paymentTermses: PaymentTerm[]
  id: number
}

type PaymentTerm = {
  paymentTermName: string
  foreignPaymentTermName: string
  invoicePortion: number
  dueDateBasedOn: number
  creditDays: number
  hasDiscount: boolean
  isDiscountValueOrRatio: number
  discount: number
  discountIfPaidWithIn: number
  paymentTemplateId: number
  isDeleted: boolean
}

interface AddMainItemProps {
  locale: any
  isDisabled: boolean
  variantVlaueData: number
  setVariantVlaueData: any
  setIsONEditorMaster: any
}
type Payload = {
  id: number
  tagId: number
  itemIds: number
}
const FetchingData = (id: any, transformData: any, setValue: any, setItemsData: any) => {
  return fetchGenericData(id, transformData, setValue, `/api/PurchasePaymentTemplate/GetAllPayment/`, 'PurchasePaymentTemplate', null, setItemsData)
}
const AddTermsTemplate = forwardRef((props: AddMainItemProps, ref) => {
  const searchParams = useSearchParams()
  const id = searchParams.get('id')
  const [ItemsData, setItemsData] = useState<any[]>([])
  const [selectedItemIds, setSelectedItemIds] = useState<number[]>([])
  const [view, setView] = useState<'newLinkItem' | 'linkedItem'>('linkedItem')
  const [uomCategoryId, setUomCategoryId] = useState(0)
  const [formData, setFormData] = useState<any>([])
  const [isNameExist, setIsNameExist] = useState(false)
  const [isCodeExist, setIsCodeExist] = useState(false)
  const [brandCode, setBrandCode] = useState('')
  const [orignData, setOriginData] = useState<any>([])

  const handleFormChangeGeneralItems = (data: any) => {
    setFormData((prevData: any) => ({ ...prevData, ...data }))
  }

  const formRef = React.useRef()
  const methods = useForm({
    mode: 'onSubmit' // or 'onSubmit', 'onChange' depending on when you want validation to occur
  })
  const [previousValues, setPreviousValues] = useState<FormValues>({
    id: 0,
    templateName: '',
    foreignTemplateName: '',
    discerption: '',
    isActive: true,
    paymentTermses: []
  })
  useImperativeHandle(ref, () => ({
    onSubmit,
    onreset
  }))
  // useImperativeHandle(ref, () => ({ onSubmit }))
  // useImperativeHandle(ref, () => ({ onreset }))

  const onreset = async () => {
    //setReset(true)
    methods.reset(orignData)

    // rows={rows.filter(x => !x.isDeleted)}

    props.setIsONEditorMaster(false)
  }
  useEffect(() => {
    if (id) {
      setUomCategoryId(Number(id))
      
    } else {
     
    }
  }, [id])
  const handleManualSubmit = () => {}
  // Hooks
  const {
    control,
    reset,
    handleSubmit,
    setValue,
    getValues,
    formState: { errors }
  } = useForm<FormValues>({
    defaultValues: {
      id: 0,
      templateName: '',
      foreignTemplateName: '',
      discerption: '',
      isActive: true,
      paymentTermses: []
    }
  })
  const transformData = (templateData: FormValues) => {
    methods.reset(templateData)
    setFormData(templateData)
    setOriginData(templateData)
    return templateData
  }

  const getTemplateData = useCallback(FetchingData(id, transformData, setValue, setItemsData), [])

  const onMaunalSubmit: SubmitHandler<FormValues> = async data => {
    try {
      const token = ''
      const isValid1 = await methods.trigger()
      if (!isValid1) {
        return
      }
      const response = await postData('/api/PurchasePaymentTemplate/AddOrUpdateUpdatePaymentTemplate', formData, token)

      if (response.status === '1') {
        setUomCategoryId(Number(response.data.id))
        transformData(response.data)
      }
    } catch (error) {
      console.error('Error adding or updating payment template:', error)
    }
  }

  

  

 

  const handleBlurBrandName = async (event: React.FocusEvent<HTMLInputElement>) => {
    const { name, value } = event.target
    const currentValues = getValues()
    const isValid1 = await methods.trigger()
    // if (!isValid1) {
    //   return
    // }
    if (value !== previousValues[name as keyof FormValues]) {
      setPreviousValues(currentValues)
     
      //onMaunalSubmit(currentValues)
    }
    handleBlur()
  }

  const handleBlurBrandCode = async (event: React.FocusEvent<HTMLInputElement>) => {
    const { name, value } = event.target
    const currentValues = getValues()
    const isValid1 = await methods.trigger()
    // if (!isValid1) {
    //   return
    // }
    if (value !== previousValues[name as keyof FormValues]) {
      setPreviousValues(currentValues)
     
      //onMaunalSubmit(currentValues)
    }
    handleBlur()
  }
  const [initialValues, setInitialValues] = useState<any>({})
  const [currentValues, setCurrentValues] = useState<any>({})
  // Handle change of inputs
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setCurrentValues((prev: any) => ({ ...prev, [name]: value }))
  }

  // Handle blur event to check whether form is in edit mode
  const handleBlur = () => {
    // If we're in "new mode" (initialValues is empty), check if any field has a value
    const isFormFilled = Object.values(currentValues).some(value => value && value !== '')

    // If we're in "edit mode", check if the current form differs from initial values
    const valuesChanged = Object.keys(orignData).some(key => currentValues[key] !== initialValues[key])

    // Set "isONEditorMaster" state based on changes or if the form is filled
    if (uomCategoryId > 0) {
      props.setIsONEditorMaster(valuesChanged) // For edit mode, check if values have changed
    } else {
      props.setIsONEditorMaster(isFormFilled) // For new mode, check if any field is filled
    }
  }

  const onSubmit = async (data: any) => {
    const isValid1 = await methods.trigger()
    if (!isValid1) {
      toast.error('error triger')
      return
    }
    const postDataWithGet = HandlePostDataWithGet<FormValues>(
      formData,
      '/api/PurchasePaymentTemplate/AddOrUpdateUpdatePaymentTemplate',
      ' قوالب شروط السداد ',
      'تم حفظ   بنجاح',
      null,
      uomCategoryId > 0 ? uomCategoryId.toString() : null, // Replace with actual itemId
      uomCategoryId == 0,
      setItemsData
    )

    postDataWithGet()
  }

  return (
    <Box>
      {/* {getTheMAinButtonOfScreens<FormValues>(reset, handleSubmit(onSubmit))} */}
      <Card>
        <CardContent>
          <FormProvider {...methods}>
            <AddTermsForm
              control1={control}
              errors1={errors}
              handleSubmit={handleSubmit(handleManualSubmit)}
              reset={reset}
              manualsumbit={onMaunalSubmit}
              formRef={formRef}
              handleBlur={handleBlurBrandName}
              handleBlurCode={handleBlurBrandCode}
              onChange={handleFormChangeGeneralItems}
              isDIsabled={props.isDisabled}
              isNameExist={isNameExist}
              isCodeExist={isCodeExist}
              brandCode={brandCode}
              handleChange={handleChange}
            />
          </FormProvider>
        </CardContent>
        <CardContent>
        <PaymentTerms
          paymentTerms={ItemsData} 
          onSelectionChange={setSelectedItemIds} 
        />
      </CardContent>
      </Card>
    </Box>
  )
})

export default AddTermsTemplate