import React, { useEffect, useMemo, useRef, useState } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import {
  mdiChevronDown,
  mdiChevronUp,
  mdiDomain,
  mdiEmailOutline,
  mdiOfficeBuilding,
  mdiOpenInNew,
  mdiShieldAccount,
} from '@mdi/js'

import BaseButton from './BaseButton'
import BaseIcon from './BaseIcon'
import CardBoxModal from './CardBoxModal'
import ClickOutside from './ClickOutside'
import ConnectedEntityCard from './ConnectedEntityCard'
import TenantStatusChip from './TenantStatusChip'
import { useAppSelector } from '../stores/hooks'
import {
  emptyOrganizationTenantSummary,
  getOrganizationViewHref,
  getTenantViewHref,
  loadLinkedTenantSummary,
} from '../helpers/organizationTenants'
import { hasPermission } from '../helpers/userPermissions'

const CurrentWorkspaceChip = () => {
  const router = useRouter()
  const triggerRef = useRef(null)
  const { currentUser } = useAppSelector((state) => state.auth)
  const [linkedTenantSummary, setLinkedTenantSummary] = useState(emptyOrganizationTenantSummary)
  const [isLoadingTenants, setIsLoadingTenants] = useState(false)
  const [isPopoverActive, setIsPopoverActive] = useState(false)
  const [isWorkspaceModalActive, setIsWorkspaceModalActive] = useState(false)

  const organizationId = useMemo(
    () =>
      currentUser?.organizations?.id ||
      currentUser?.organization?.id ||
      currentUser?.organizationsId ||
      currentUser?.organizationId ||
      '',
    [
      currentUser?.organization?.id,
      currentUser?.organizationId,
      currentUser?.organizations?.id,
      currentUser?.organizationsId,
    ],
  )
  const canViewOrganizations = hasPermission(currentUser, 'READ_ORGANIZATIONS')
  const canViewTenants = hasPermission(currentUser, 'READ_TENANTS')

  useEffect(() => {
    let isMounted = true

    if (!organizationId || !canViewTenants) {
      setLinkedTenantSummary(emptyOrganizationTenantSummary)
      setIsLoadingTenants(false)
      return () => {
        isMounted = false
      }
    }

    setIsLoadingTenants(true)

    loadLinkedTenantSummary(organizationId)
      .then((summary) => {
        if (!isMounted) {
          return
        }

        setLinkedTenantSummary(summary)
      })
      .catch((error) => {
        console.error('Failed to load current workspace chip context:', error)

        if (!isMounted) {
          return
        }

        setLinkedTenantSummary(emptyOrganizationTenantSummary)
      })
      .finally(() => {
        if (isMounted) {
          setIsLoadingTenants(false)
        }
      })

    return () => {
      isMounted = false
    }
  }, [canViewTenants, organizationId])

  useEffect(() => {
    setIsPopoverActive(false)
    setIsWorkspaceModalActive(false)
  }, [router.asPath])

  useEffect(() => {
    if (!isPopoverActive && !isWorkspaceModalActive) {
      return () => undefined
    }

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsPopoverActive(false)
        setIsWorkspaceModalActive(false)
      }
    }

    document.addEventListener('keydown', handleEscape)

    return () => {
      document.removeEventListener('keydown', handleEscape)
    }
  }, [isPopoverActive, isWorkspaceModalActive])

  if (!currentUser) {
    return null
  }

  const organizationName =
    currentUser?.organizations?.name ||
    currentUser?.organization?.name ||
    currentUser?.organizationName ||
    'No organization assigned yet'

  const organizationSlug =
    currentUser?.organizations?.slug || currentUser?.organization?.slug || currentUser?.organizationSlug || ''

  const organizationDomain =
    currentUser?.organizations?.domain ||
    currentUser?.organization?.domain ||
    currentUser?.organizations?.primary_domain ||
    currentUser?.organization?.primary_domain ||
    currentUser?.organizationDomain ||
    ''

  const appRoleName = currentUser?.app_role?.name || 'User'
  const linkedTenants = Array.isArray(linkedTenantSummary.rows) ? linkedTenantSummary.rows : []
  const linkedTenantCount = linkedTenantSummary.count || 0
  const tenantLabel = !organizationId
    ? 'No workspace linked'
    : !canViewTenants
      ? 'Tenant access restricted'
      : isLoadingTenants
        ? 'Loading tenants…'
        : `${linkedTenantCount} tenant${linkedTenantCount === 1 ? '' : 's'}`
  const tenantEmptyStateMessage = !organizationId
    ? 'No organization is attached to this account yet.'
    : !canViewTenants
      ? 'Your current role can open the workspace, but it does not include tenant-read access.'
      : 'No tenant link surfaced yet for this workspace.'
  const organizationHref =
    canViewOrganizations && organizationId ? getOrganizationViewHref(organizationId) : '/profile'
  const hasOrganizationMetadata = Boolean(organizationSlug || organizationDomain)

  const handleOpenWorkspaceModal = () => {
    setIsPopoverActive(false)
    setIsWorkspaceModalActive(true)
  }

  const handleCloseWorkspaceModal = () => {
    setIsWorkspaceModalActive(false)
  }

  return (
    <>
      <div className="relative hidden xl:block" ref={triggerRef}>
        <button
          type="button"
          className="group flex items-center gap-3 rounded-xl border border-blue-200 bg-blue-50/80 px-3 py-2 text-left transition-colors hover:border-blue-300 hover:bg-blue-100/80 dark:border-blue-900/70 dark:bg-blue-950/30 dark:hover:border-blue-800 dark:hover:bg-blue-950/40"
          title={`Current workspace: ${organizationName}`}
          aria-haspopup="dialog"
          aria-expanded={isPopoverActive}
          onClick={() => setIsPopoverActive((currentValue) => !currentValue)}
        >
          <span className="flex h-8 w-8 flex-none items-center justify-center rounded-lg bg-blue-100 text-blue-900 dark:bg-blue-900/60 dark:text-blue-100">
            <BaseIcon path={mdiOfficeBuilding} size="18" />
          </span>

          <span className="min-w-0">
            <span className="block text-[10px] font-semibold uppercase tracking-[0.18em] text-blue-900 dark:text-blue-100">
              Current workspace
            </span>
            <span className="block truncate text-sm font-semibold text-gray-900 dark:text-gray-100">
              {organizationName}
            </span>
            <span className="mt-0.5 flex items-center gap-1 text-xs text-gray-600 dark:text-gray-300">
              <BaseIcon path={mdiDomain} size="14" />
              <span className="truncate">
                {tenantLabel} • {appRoleName}
              </span>
            </span>
          </span>

          <span className="flex-none text-blue-800 dark:text-blue-200">
            <BaseIcon path={isPopoverActive ? mdiChevronUp : mdiChevronDown} size="16" />
          </span>
        </button>

        {isPopoverActive ? (
          <div className="absolute right-0 top-full z-40 mt-2 w-[26rem] max-w-[calc(100vw-2rem)]">
            <ClickOutside onClickOutside={() => setIsPopoverActive(false)} excludedElements={[triggerRef]}>
              <div className="overflow-hidden rounded-2xl border border-blue-100 bg-white shadow-2xl dark:border-blue-950/70 dark:bg-dark-900">
                <div className="border-b border-blue-100 bg-blue-50/80 px-4 py-3 dark:border-blue-950/70 dark:bg-blue-950/30">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <p className="text-[10px] font-semibold uppercase tracking-[0.18em] text-blue-900 dark:text-blue-100">
                        Current workspace
                      </p>
                      <p className="mt-1 truncate text-base font-semibold text-gray-900 dark:text-gray-100">
                        {organizationName}
                      </p>
                      <div className="mt-2 flex flex-wrap gap-2 text-xs text-gray-700 dark:text-gray-200">
                        <span className="inline-flex items-center gap-1 rounded-full bg-white/80 px-2.5 py-1 dark:bg-dark-800">
                          <BaseIcon path={mdiShieldAccount} size="14" />
                          {appRoleName}
                        </span>
                        <span className="inline-flex items-center gap-1 rounded-full bg-white/80 px-2.5 py-1 dark:bg-dark-800">
                          <BaseIcon path={mdiDomain} size="14" />
                          {tenantLabel}
                        </span>
                        {organizationSlug ? (
                          <span className="inline-flex items-center gap-1 rounded-full bg-white/80 px-2.5 py-1 dark:bg-dark-800">
                            Slug: {organizationSlug}
                          </span>
                        ) : null}
                        {organizationDomain ? (
                          <span className="inline-flex items-center gap-1 rounded-full bg-white/80 px-2.5 py-1 dark:bg-dark-800">
                            Domain: {organizationDomain}
                          </span>
                        ) : null}
                      </div>
                    </div>

                    <BaseButton
                      href={organizationHref}
                      label={canViewOrganizations && organizationId ? 'Open' : 'Profile'}
                      color="info"
                      outline
                      small
                      icon={mdiOpenInNew}
                    />
                  </div>
                </div>

                <div className="space-y-4 px-4 py-4">
                  <div className="rounded-xl border border-gray-200 bg-gray-50 px-3 py-3 dark:border-dark-700 dark:bg-dark-800">
                    <div className="flex items-start gap-3">
                      <span className="mt-0.5 flex h-8 w-8 flex-none items-center justify-center rounded-lg bg-blue-100 text-blue-900 dark:bg-blue-900/60 dark:text-blue-100">
                        <BaseIcon path={mdiOfficeBuilding} size="16" />
                      </span>
                      <div className="min-w-0 flex-1">
                        <p className="text-xs font-semibold uppercase tracking-[0.14em] text-gray-500 dark:text-gray-300">
                          Organization access
                        </p>
                        <p className="mt-1 truncate text-sm font-semibold text-gray-900 dark:text-gray-100">
                          {organizationName}
                        </p>
                        <p className="mt-1 flex items-center gap-1 text-xs text-gray-600 dark:text-gray-300">
                          <BaseIcon path={mdiEmailOutline} size="14" />
                          <span className="truncate">{currentUser?.email || 'No email surfaced yet'}</span>
                        </p>
                        {hasOrganizationMetadata ? (
                          <div className="mt-2 flex flex-wrap gap-2">
                            {organizationSlug ? (
                              <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700 dark:bg-dark-900 dark:text-gray-100">
                                Slug: {organizationSlug}
                              </span>
                            ) : null}
                            {organizationDomain ? (
                              <span className="rounded-full bg-white px-2.5 py-1 text-xs font-medium text-gray-700 dark:bg-dark-900 dark:text-gray-100">
                                Domain: {organizationDomain}
                              </span>
                            ) : null}
                          </div>
                        ) : null}
                      </div>
                    </div>
                  </div>

                  <div>
                    <div className="flex items-center justify-between gap-2">
                      <p className="text-xs font-semibold uppercase tracking-[0.14em] text-gray-500 dark:text-gray-300">
                        Linked tenants
                      </p>
                      <div className="flex items-center gap-3">
                        <button
                          type="button"
                          className="text-xs font-semibold text-blue-700 hover:text-blue-800 dark:text-blue-200 dark:hover:text-blue-100"
                          onClick={handleOpenWorkspaceModal}
                        >
                          Workspace details
                        </button>
                        <Link
                          href="/profile"
                          className="text-xs font-semibold text-blue-700 hover:text-blue-800 dark:text-blue-200 dark:hover:text-blue-100"
                        >
                          View profile context
                        </Link>
                      </div>
                    </div>

                    <div className="mt-3 space-y-2">
                      {isLoadingTenants ? (
                        <div className="rounded-xl border border-dashed border-blue-200 bg-blue-50/60 px-3 py-3 text-sm text-blue-900 dark:border-blue-900/70 dark:bg-blue-950/20 dark:text-blue-100">
                          Loading tenant context…
                        </div>
                      ) : linkedTenants.length ? (
                        linkedTenants.slice(0, 3).map((tenant) => (
                          <div
                            key={tenant.id}
                            className="rounded-xl border border-gray-200 bg-white px-3 py-3 dark:border-dark-700 dark:bg-dark-800"
                          >
                            <div className="flex items-start justify-between gap-3">
                              <div className="min-w-0 flex-1">
                                <p className="truncate text-sm font-semibold text-gray-900 dark:text-gray-100">
                                  {tenant.name || 'Unnamed tenant'}
                                </p>
                                <div className="mt-2 flex flex-wrap gap-2">
                                  <TenantStatusChip isActive={tenant.is_active} />
                                  {tenant.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">
                                      Slug: {tenant.slug}
                                    </span>
                                  ) : null}
                                  {tenant.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">
                                      Domain: {tenant.primary_domain}
                                    </span>
                                  ) : null}
                                </div>
                              </div>

                              {canViewTenants && tenant.id ? (
                                <BaseButton
                                  href={getTenantViewHref(tenant.id, organizationId, organizationName)}
                                  label="Open"
                                  color="info"
                                  outline
                                  small
                                />
                              ) : null}
                            </div>
                          </div>
                        ))
                      ) : (
                        <div className="rounded-xl border border-dashed border-gray-200 bg-gray-50 px-3 py-3 text-sm text-gray-600 dark:border-dark-700 dark:bg-dark-800 dark:text-gray-300">
                          {tenantEmptyStateMessage}
                        </div>
                      )}
                    </div>

                    {!isLoadingTenants && linkedTenantCount > 3 ? (
                      <p className="mt-2 text-xs text-gray-500 dark:text-gray-300">
                        Showing 3 of {linkedTenantCount} linked tenants in this quick view.
                      </p>
                    ) : null}
                  </div>
                </div>
              </div>
            </ClickOutside>
          </div>
        ) : null}
      </div>

      <CardBoxModal
        title="Workspace details"
        buttonColor="info"
        buttonLabel="Done"
        isActive={isWorkspaceModalActive}
        onConfirm={handleCloseWorkspaceModal}
        onCancel={handleCloseWorkspaceModal}
      >
        <div className="space-y-4">
          <div>
            <p className="text-sm text-gray-600 dark:text-gray-300">
              This view expands the same workspace summary from the navbar so the user can inspect their organization context without leaving the current page.
            </p>
          </div>

          <ConnectedEntityCard
            entityLabel="Workspace"
            title={organizationName}
            titleFallback="No organization assigned yet"
            badges={[
              <span
                key="workspace-role"
                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"
              >
                Role: {appRoleName}
              </span>,
              <span
                key="workspace-tenants"
                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"
              >
                {tenantLabel}
              </span>,
            ]}
            details={[
              { label: 'Email', value: currentUser?.email },
              { label: 'Slug', value: organizationSlug },
              { label: 'Domain', value: organizationDomain },
            ]}
            actions={[
              {
                href: organizationHref,
                label: canViewOrganizations && organizationId ? 'Open workspace' : 'Open profile',
                color: 'info',
              },
              {
                href: '/profile',
                label: 'View profile',
                color: 'info',
                outline: true,
              },
            ]}
            helperText={
              organizationId
                ? 'This is the organization currently attached to the signed-in account context.'
                : 'This account does not have an organization link yet.'
            }
          />

          <div className="space-y-3">
            <div className="flex items-center justify-between gap-2">
              <p className="text-xs font-semibold uppercase tracking-[0.18em] text-gray-500 dark:text-gray-300">
                Linked tenants
              </p>
              {linkedTenantCount > linkedTenants.length && !isLoadingTenants ? (
                <p className="text-xs text-gray-500 dark:text-gray-300">
                  Showing {linkedTenants.length} of {linkedTenantCount} linked tenants.
                </p>
              ) : null}
            </div>

            {isLoadingTenants ? (
              <div className="rounded-xl border border-dashed border-blue-200 bg-blue-50/60 px-4 py-3 text-sm text-blue-900 dark:border-blue-900/70 dark:bg-blue-950/20 dark:text-blue-100">
                Loading tenant context for this workspace…
              </div>
            ) : linkedTenants.length ? (
              <div className="space-y-3">
                {linkedTenants.map((tenant) => (
                  <ConnectedEntityCard
                    key={tenant.id}
                    entityLabel="Tenant"
                    title={tenant.name || 'Unnamed tenant'}
                    badges={[<TenantStatusChip key={`${tenant.id}-status`} isActive={tenant.is_active} />]}
                    details={[
                      { label: 'Slug', value: tenant.slug },
                      { label: 'Domain', value: tenant.primary_domain },
                      { label: 'Timezone', value: tenant.timezone },
                      { label: 'Currency', value: tenant.default_currency },
                    ]}
                    actions={
                      canViewTenants && tenant.id
                        ? [
                            {
                              href: getTenantViewHref(tenant.id, organizationId, organizationName),
                              label: 'Open tenant',
                              color: 'info',
                              outline: true,
                            },
                          ]
                        : []
                    }
                    helperText="This tenant is linked behind the organization context attached to the current account."
                  />
                ))}
              </div>
            ) : (
              <div className="rounded-xl border border-dashed border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-600 dark:border-dark-700 dark:bg-dark-800 dark:text-gray-300">
                {tenantEmptyStateMessage}
              </div>
            )}
          </div>
        </div>
      </CardBoxModal>
    </>
  )
}

export default CurrentWorkspaceChip
