import React, { useEffect, useState } from 'react'
import Link from 'next/link'

import CardBox from '../CardBox'
import ListActionsPopover from '../ListActionsPopover'
import { useAppSelector } from '../../stores/hooks'
import { Pagination } from '../Pagination'
import LoadingSpinner from '../LoadingSpinner'
import LinkedTenantsPreview from './LinkedTenantsPreview'
import { hasPermission } from '../../helpers/userPermissions'
import { loadLinkedTenantSummaries, OrganizationTenantSummaryMap } from '../../helpers/organizationTenants'

type Props = {
  organizations: any[]
  loading: boolean
  onDelete: (id: string) => void
  currentPage: number
  numPages: number
  onPageChange: (page: number) => void
}

const ListOrganizations = ({ organizations, loading, onDelete, currentPage, numPages, onPageChange }: Props) => {
  const currentUser = useAppSelector((state) => state.auth.currentUser)
  const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_ORGANIZATIONS')

  const corners = useAppSelector((state) => state.style.corners)
  const bgColor = useAppSelector((state) => state.style.cardsColor)
  const [linkedTenantSummaries, setLinkedTenantSummaries] = useState<OrganizationTenantSummaryMap>({})

  useEffect(() => {
    if (!Array.isArray(organizations) || !organizations.length || !canViewTenants) {
      setLinkedTenantSummaries({})
      return
    }

    let isActive = true

    loadLinkedTenantSummaries(organizations.map((item: any) => item?.id))
      .then((summaries) => {
        if (isActive) {
          setLinkedTenantSummaries(summaries)
        }
      })
      .catch((error) => {
        console.error('Failed to load linked tenants for organization list rows:', error)
        if (isActive) {
          setLinkedTenantSummaries({})
        }
      })

    return () => {
      isActive = false
    }
  }, [canViewTenants, organizations])

  return (
    <>
      <div className='relative space-y-4 overflow-x-auto p-4'>
        {loading && <LoadingSpinner />}
        {!loading &&
          organizations.map((item) => {
            const linkedSummary = linkedTenantSummaries[item.id]
            const linkedCount = linkedSummary?.count || 0
            const linkedTenantLabel = !canViewTenants
              ? 'Tenant access restricted'
              : linkedCount
                ? `${linkedCount} linked tenant${linkedCount === 1 ? '' : 's'}`
                : 'No tenant link'

            return (
              <div key={item.id}>
                <CardBox hasTable isList className='rounded shadow-none'>
                  <div
                    className={`flex items-start overflow-hidden border border-gray-600 ${bgColor} ${
                      corners !== 'rounded-full' ? corners : 'rounded-3xl'
                    } dark:bg-dark-900`}
                  >
                    <Link href={`/organizations/organizations-view/?id=${item.id}`} className='min-w-0 flex-1 p-4'>
                      <div className='flex flex-wrap items-center gap-2'>
                        <span className='rounded-full border border-blue-200 bg-blue-50 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-blue-900 dark:border-blue-900 dark:bg-blue-950/40 dark:text-blue-100'>
                          Organization
                        </span>
                        <span className='rounded-full bg-gray-100 px-2.5 py-1 text-xs font-medium text-gray-700 dark:bg-dark-700 dark:text-gray-100'>
                          {linkedTenantLabel}
                        </span>
                      </div>

                      <p className='mt-3 line-clamp-2 text-base font-semibold text-gray-900 dark:text-gray-100'>
                        {item.name || 'Unnamed organization'}
                      </p>

                      <div className='mt-3 rounded-xl border border-blue-100 bg-blue-50/60 p-3 dark:border-blue-950/60 dark:bg-blue-950/20'>
                        <p className='text-xs font-semibold uppercase tracking-[0.18em] text-blue-900 dark:text-blue-100'>
                          Connected entities
                        </p>
                        <div className='mt-2'>
                          <LinkedTenantsPreview
                            summary={linkedSummary}
                            emptyMessage={canViewTenants ? 'This organization is not linked to a tenant yet.' : 'Tenant access restricted'}
                            compact
                          />
                        </div>
                      </div>
                    </Link>

                    <div className='flex shrink-0 items-start p-4'>
                      <ListActionsPopover
                        onDelete={onDelete}
                        itemId={item.id}
                        pathEdit={`/organizations/organizations-edit/?id=${item.id}`}
                        pathView={`/organizations/organizations-view/?id=${item.id}`}
                        hasUpdatePermission={hasUpdatePermission}
                      />
                    </div>
                  </div>
                </CardBox>
              </div>
            )
          })}
        {!loading && organizations.length === 0 && (
          <div className='col-span-full flex h-40 items-center justify-center'>
            <p>No data to display</p>
          </div>
        )}
      </div>
      <div className='my-6 flex items-center justify-center'>
        <Pagination currentPage={currentPage} numPages={numPages} setCurrentPage={onPageChange} />
      </div>
    </>
  )
}

export default ListOrganizations
