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 ClickOutside from './ClickOutside'
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 organizationId = useMemo(
    () =>
      currentUser?.organizations?.id ||
      currentUser?.organization?.id ||
      currentUser?.organizationsId ||
      currentUser?.organizationId ||
      '',
    [
      currentUser?.organization?.id,
      currentUser?.organizationId,
      currentUser?.organizations?.id,
      currentUser?.organizationsId,
    ],
  )

  useEffect(() => {
    let isMounted = true

    if (!organizationId) {
      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
    }
  }, [organizationId])

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

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

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

    document.addEventListener('keydown', handleEscape)

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

  if (!currentUser) {
    return null
  }

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

  const appRoleName = currentUser?.app_role?.name || 'User'
  const linkedTenants = Array.isArray(linkedTenantSummary.rows) ? linkedTenantSummary.rows : []
  const linkedTenantCount = linkedTenantSummary.count || 0
  const tenantLabel = isLoadingTenants
    ? 'Loading tenants…'
    : `${linkedTenantCount} tenant${linkedTenantCount === 1 ? '' : 's'}`
  const canViewOrganizations = hasPermission(currentUser, 'READ_ORGANIZATIONS')
  const canViewTenants = hasPermission(currentUser, 'READ_TENANTS')
  const organizationHref =
    canViewOrganizations && organizationId ? getOrganizationViewHref(organizationId) : '/profile'

  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>
                    </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>
                    </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>
                    <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 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">
                        No tenant link surfaced yet for this workspace.
                      </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>
  )
}

export default CurrentWorkspaceChip
