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

import LinkedTenantsPreview from './LinkedTenantsPreview'
import ListActionsPopover from '../ListActionsPopover'
import LoadingSpinner from '../LoadingSpinner'
import { Pagination } from '../Pagination'
import { useAppSelector } from '../../stores/hooks'
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 CardOrganizations = ({
  organizations,
  loading,
  onDelete,
  currentPage,
  numPages,
  onPageChange,
}: Props) => {
  const asideScrollbarsStyle = useAppSelector((state) => state.style.asideScrollbarsStyle)
  const bgColor = useAppSelector((state) => state.style.cardsColor)
  const darkMode = useAppSelector((state) => state.style.darkMode)
  const corners = useAppSelector((state) => state.style.corners)
  const focusRing = useAppSelector((state) => state.style.focusRingColor)

  const currentUser = useAppSelector((state) => state.auth.currentUser)
  const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_ORGANIZATIONS')
  const canViewTenants = hasPermission(currentUser, 'READ_TENANTS')
  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 cards:', error)
        if (isActive) {
          setLinkedTenantSummaries({})
        }
      })

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

  return (
    <div className='p-4'>
      {loading && <LoadingSpinner />}
      <ul role='list' className='grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-3 2xl:grid-cols-4 xl:gap-x-8'>
        {!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 (
              <li
                key={item.id}
                className={`overflow-hidden ${corners !== 'rounded-full' ? corners : 'rounded-3xl'} border ${focusRing} border-gray-200 dark:border-dark-700 ${
                  darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
                }`}
              >
                <div
                  className={`relative border-b border-gray-900/5 bg-gray-50 p-6 ${bgColor} dark:bg-dark-800`}
                >
                  <div className='flex items-start gap-4'>
                    <div className='min-w-0 flex-1'>
                      <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>

                      <Link href={`/organizations/organizations-view/?id=${item.id}`} className='mt-3 block line-clamp-2 text-lg font-bold leading-6'>
                        {item.name || 'Unnamed organization'}
                      </Link>
                    </div>

                    <div className='ml-auto'>
                      <ListActionsPopover
                        onDelete={onDelete}
                        itemId={item.id}
                        pathEdit={`/organizations/organizations-edit/?id=${item.id}`}
                        pathView={`/organizations/organizations-view/?id=${item.id}`}
                        hasUpdatePermission={hasUpdatePermission}
                      />
                    </div>
                  </div>
                </div>

                <div className='space-y-4 px-6 py-4 text-sm leading-6'>
                  <div className='rounded-xl border border-blue-100 bg-blue-50/60 p-4 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-3'>
                      <LinkedTenantsPreview
                        summary={linkedSummary}
                        emptyMessage={canViewTenants ? 'This organization is not linked to a tenant yet.' : 'Tenant access restricted'}
                      />
                    </div>
                  </div>
                </div>
              </li>
            )
          })}
        {!loading && organizations.length === 0 && (
          <div className='col-span-full flex h-40 items-center justify-center'>
            <p>No data to display</p>
          </div>
        )}
      </ul>
      <div className='my-6 flex items-center justify-center'>
        <Pagination currentPage={currentPage} numPages={numPages} setCurrentPage={onPageChange} />
      </div>
    </div>
  )
}

export default CardOrganizations
