import { Tabs } from '@/components/ui'
import TabContent from '@/components/ui/Tabs/TabContent'
import TabList from '@/components/ui/Tabs/TabList'
import TabNav from '@/components/ui/Tabs/TabNav'
import { useEffect, useState } from 'react'
import { FaChartBar, FaList } from 'react-icons/fa';
import { useLocation, useNavigate } from 'react-router-dom'
import Grid from '../list/Grid'
import Chart from '../chart/Chart'
import { GridDto, SubFormDto, SubFormTabTypeEnum } from '@/proxy/form/models'
import FormEdit from './FormEdit'
import FormNew from './FormNew'
import FormView from './FormView'

const SubForms = (props: {
  gridDto: GridDto
  formData: any
  level: number
  refreshData?: () => Promise<void>
}) => {
  const { gridDto, formData, level, refreshData } = props
  const { hash } = useLocation()
  const [currentTab, setCurrentTab] = useState<string>()
  const [subForms, setSubForms] = useState<SubFormDto[]>()
  const navigate = useNavigate()

  useEffect(() => {
    if (hash && level === 0) {
      setCurrentTab(hash.replace('#', ''))
    } else if (gridDto?.gridOptions?.subFormsDto?.length) {
      setCurrentTab(gridDto?.gridOptions?.subFormsDto[0].code)
    } else {
      setCurrentTab(undefined)
    }
  }, [hash, gridDto])

  useEffect(() => {
    if (!gridDto?.gridOptions?.subFormsDto?.length) {
      return
    }

    for (const subForm of gridDto.gridOptions.subFormsDto) {
      if (formData && subForm.relation?.length) {
        subForm.searchParams = new URLSearchParams(
          subForm.relation.reduce(
            (acc, a) => {
              if (formData?.[a.parentFieldName]) {
                acc[a.childFieldName] = formData[a.parentFieldName]
              }
              return acc
            },
            {} as Record<string, string>,
          ),
        )
        subForm.id = formData[subForm.relation[0].parentFieldName]
      }
    }

    setSubForms([...gridDto.gridOptions.subFormsDto])
  }, [gridDto, formData])

  if (!formData || !subForms?.length) {
    return <></>
  }

  return (
    <Tabs
      value={currentTab}
      onChange={(val: string) => {
        if (subForms.some((a) => a.code === val)) {
          setCurrentTab(val)
          if (level === 0) {
            navigate(`#${val}`)
          }
        }
      }}
    >
      <TabList>
        {subForms.map((subForm, i) => {
          return (
            <TabNav
              key={subForm.code}
              value={subForm.code}
              icon={subForm.tabType == SubFormTabTypeEnum.List ? <FaList /> : <FaChartBar />}
            >
              {subForm.tabTitle}
            </TabNav>
          )
        })}
      </TabList>
      {subForms.map((subForm, i) => {
        return (
          <TabContent key={subForm.code} value={subForm.code} className="pt-1">
            {subForm.tabType == SubFormTabTypeEnum.List && (
              <Grid
                listFormCode={subForm.code}
                searchParams={subForm.searchParams}
                isSubForm={true}
                level={level + 1}
                refreshData={refreshData}
              />
            )}
            {subForm.tabType == SubFormTabTypeEnum.Form &&
              (subForm.tabMode == 'edit' ? (
                <FormEdit
                  onActionNew={() => {
                    setSubForms(
                      subForms.map((a) => {
                        if (a.code == subForm.code) {
                          a.tabMode = 'new'
                        }
                        return a
                      }),
                    )
                  }}
                  onActionView={() => {
                    setSubForms(
                      subForms.map((a) => {
                        if (a.code == subForm.code) {
                          a.tabMode = 'view'
                        }
                        return a
                      }),
                    )
                  }}
                  listFormCode={subForm.code}
                  id={subForm.id}
                  level={level + 1}
                  isSubForm={true}
                />
              ) : subForm.tabMode == 'new' ? (
                <FormNew
                  listFormCode={subForm.code}
                  sParams={subForm.searchParams}
                  level={level + 1}
                  isSubForm={true}
                  onActionView={() => {
                    setSubForms(
                      subForms.map((a) => {
                        if (a.code == subForm.code) {
                          a.tabMode = 'view'
                        }
                        return a
                      }),
                    )
                  }}
                />
              ) : (
                <FormView
                  onActionNew={() => {
                    setSubForms(
                      subForms.map((a) => {
                        if (a.code == subForm.code) {
                          a.tabMode = 'new'
                        }
                        return a
                      }),
                    )
                  }}
                  onActionEdit={() => {
                    setSubForms(
                      subForms.map((a) => {
                        if (a.code == subForm.code) {
                          a.tabMode = 'edit'
                        }
                        return a
                      }),
                    )
                  }}
                  listFormCode={subForm.code}
                  id={subForm.id}
                  level={level + 1}
                  isSubForm={true}
                />
              ))}
            {subForm.tabType == SubFormTabTypeEnum.Chart && (
              <Chart
                chartCode={subForm.code}
                isSubForm={true}
                level={level + 1}
                refreshData={refreshData}
              />
            )}
          </TabContent>
        )
      })}
    </Tabs>
  )
}

export default SubForms
