import React 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 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 ListTenants = ({ tenants, loading, onDelete, currentPage, numPages, onPageChange }: Props) => {
  const currentUser = useAppSelector((state) => state.auth.currentUser)
  const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_TENANTS')

  const corners = useAppSelector((state) => state.style.corners)
  const bgColor = useAppSelector((state) => state.style.cardsColor)

  return (
    <>
      <div className='relative space-y-4 overflow-x-auto p-4'>
        {loading && <LoadingSpinner />}
        {!loading &&
          tenants.map((item) => {
            const linkedOrganizations = Array.isArray(item.organizations) ? item.organizations : []

            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={`/tenants/tenants-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'>
                          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>

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

                      <div className='mt-3 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}
                      </div>

                      <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 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>
                              ))}
                            </>
                          ) : (
                            <span className='text-sm text-gray-500 dark:text-dark-600'>No linked organizations</span>
                          )}
                        </div>
                      </div>
                    </Link>

                    <div className='flex shrink-0 items-start p-4'>
                      <ListActionsPopover
                        onDelete={onDelete}
                        itemId={item.id}
                        pathEdit={`/tenants/tenants-edit/?id=${item.id}`}
                        pathView={`/tenants/tenants-view/?id=${item.id}`}
                        hasUpdatePermission={hasUpdatePermission}
                      />
                    </div>
                  </div>
                </CardBox>
              </div>
            )
          })}
        {!loading && tenants.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 ListTenants
