import React from 'react'
import Link from 'next/link'

import ListActionsPopover from '../ListActionsPopover'
import { useAppSelector } from '../../stores/hooks'
import dataFormatter from '../../helpers/dataFormatter'
import { Pagination } from '../Pagination'
import LoadingSpinner from '../LoadingSpinner'
import TenantStatusChip from '../TenantStatusChip'
import { hasPermission } from '../../helpers/userPermissions'

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

const CardTenants = ({
  tenants,
  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_TENANTS')

  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 &&
          tenants.map((item) => {
            const linkedOrganizations = Array.isArray(item.organizations) ? item.organizations : []

            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 dark:bg-dark-800 ${bgColor}`}>
                  <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'>
                          Tenant
                        </span>
                        <TenantStatusChip isActive={item.is_active} />
                        <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'>
                          {linkedOrganizations.length
                            ? `${linkedOrganizations.length} linked organization${linkedOrganizations.length === 1 ? '' : 's'}`
                            : 'No linked organizations'}
                        </span>
                      </div>

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

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

                <dl className='h-64 overflow-y-auto space-y-4 px-6 py-4 text-sm leading-6'>
                  <div className='flex flex-wrap gap-2'>
                    {item.slug ? (
                      <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'>
                        <span className='font-semibold text-gray-900 dark:text-gray-100'>Slug:</span> {item.slug}
                      </span>
                    ) : null}
                    {item.primary_domain ? (
                      <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'>
                        <span className='font-semibold text-gray-900 dark:text-gray-100'>Domain:</span> {item.primary_domain}
                      </span>
                    ) : null}
                    {item.timezone ? (
                      <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'>
                        <span className='font-semibold text-gray-900 dark:text-gray-100'>Timezone:</span> {item.timezone}
                      </span>
                    ) : null}
                    {item.default_currency ? (
                      <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'>
                        <span className='font-semibold text-gray-900 dark:text-gray-100'>Currency:</span> {item.default_currency}
                      </span>
                    ) : null}
                    {item.legal_name ? (
                      <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'>
                        <span className='font-semibold text-gray-900 dark:text-gray-100'>Legal:</span> {item.legal_name}
                      </span>
                    ) : null}
                  </div>

                  <div className='rounded-xl border border-blue-100 bg-blue-50/60 p-4 dark:border-blue-950/60 dark:bg-blue-950/20'>
                    <dt className='text-xs font-semibold uppercase tracking-[0.18em] text-blue-900 dark:text-blue-100'>
                      Connected entities
                    </dt>
                    <dd className='mt-3 flex flex-wrap items-center gap-2'>
                      {linkedOrganizations.length ? (
                        <>
                          <span className='rounded-full bg-blue-100 px-2.5 py-1 text-xs font-semibold text-blue-900 dark:bg-blue-950/50 dark:text-blue-100'>
                            {linkedOrganizations.length} linked
                          </span>
                          {linkedOrganizations.map((organization: any) => (
                            <span
                              key={organization.id || organization.name}
                              className='rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700 dark:bg-dark-700 dark:text-gray-100'
                              title={organization.name}
                            >
                              {organization.name || 'Unnamed organization'}
                            </span>
                          ))}
                        </>
                      ) : (
                        <div className='font-medium text-gray-500 dark:text-dark-600'>No linked organizations</div>
                      )}
                    </dd>
                  </div>

                  {dataFormatter.propertiesManyListFormatter(item.properties).length ? (
                    <div>
                      <dt className='text-gray-500 dark:text-dark-600'>Properties</dt>
                      <dd className='mt-1 font-medium line-clamp-3'>
                        {dataFormatter.propertiesManyListFormatter(item.properties).join(', ')}
                      </dd>
                    </div>
                  ) : null}

                  {dataFormatter.audit_logsManyListFormatter(item.audit_logs).length ? (
                    <div>
                      <dt className='text-gray-500 dark:text-dark-600'>Audit logs</dt>
                      <dd className='mt-1 font-medium line-clamp-3'>
                        {dataFormatter.audit_logsManyListFormatter(item.audit_logs).join(', ')}
                      </dd>
                    </div>
                  ) : null}
                </dl>
              </li>
            )
          })}
        {!loading && tenants.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 CardTenants
