import { Loading } from '@/components/shared'
import AdaptableCard from '@/components/shared/AdaptableCard'
import Container from '@/components/shared/Container'
import { Table } from '@/components/ui'
import { getTenants } from '@/proxy/admin/tenant/tenant.service'
import { TenantDto } from '@/proxy/config/models'
import { useLocalization } from '@/utils/hooks/useLocalization'
import useThemeClass from '@/utils/hooks/useThemeClass'
import isEmpty from 'lodash/isEmpty'
import { useEffect, useState } from 'react'
import { Helmet } from 'react-helmet'
import TenantsConnectionString from './TenantsConnectionString'

const { Tr, Th, Td, THead, TBody } = Table

const Tenants = () => {
  const { textTheme } = useThemeClass()
  const [loading, setLoading] = useState(true)
  const [tenantList, setTenantList] = useState<TenantDto[]>([])
  const [activeTenant, setActiveTenant] = useState<TenantDto>()

  const { translate } = useLocalization()

  const fetchData = async () => {
    setLoading(true)
    const response = await getTenants()
    if (response.data?.items) {
      setTenantList(response.data.items)
    }
    setLoading(false)
  }

  useEffect(() => {
    if (isEmpty(tenantList)) {
      fetchData()
    }
  }, [])

  const dialogOpen = (tenant: TenantDto) => {
    setActiveTenant(tenant)
  }

  return (
    <>
      <Helmet
        titleTemplate="%s | KursPlatform"
        title={translate('::AbpTenantManagement.Tenants')}
        defaultTitle="KursPlatform"
      ></Helmet>
      <Loading type="cover" loading={loading}>
        <Container>
          <AdaptableCard>
            <Table>
              <THead>
                <Tr>
                  <Th className="w-1/6"></Th>
                  <Th>Tenant</Th>
                </Tr>
              </THead>
              <TBody>
                {tenantList.map((tenant) => (
                  <Tr key={tenant.id}>
                    <Td>
                      <div
                        className={`${textTheme} cursor-pointer select-none font-semibold`}
                        onClick={() => dialogOpen(tenant)}
                      >
                        {translate('::AbpTenantManagement.Tenants.ManageConnectionStrings')}
                      </div>
                    </Td>
                    <Td>{tenant.name}</Td>
                  </Tr>
                ))}
              </TBody>
            </Table>
          </AdaptableCard>
        </Container>
      </Loading>
      {activeTenant && (
        <TenantsConnectionString
          open={!!activeTenant.id}
          id={activeTenant.id!}
          name={activeTenant.name!}
          onDialogClose={() => setActiveTenant(undefined)}
        ></TenantsConnectionString>
      )}
    </>
  )
}

export default Tenants
