import {
  ArrowLeftIcon,
  CaretRightIcon,
  CurrencyDollarIcon,
  StarIcon,
} from '@phosphor-icons/react'
import classNames from 'classnames'
import React from 'react'
import type { Channel as ChannelType } from 'stream-chat'
import { useChannelStateContext, useChatContext } from 'stream-chat-react'

import { useChannelStar } from '../hooks/useChannelStar'
import { resolveConversationParticipant } from '../utils/resolveConversationParticipant'
import { resolveParticipantDisplayName } from '../utils/resolveParticipantDisplayName'

import { Avatar } from './Avatar'
import { ChannelActionsMenu } from './ChannelActionsMenu'

const ICON_BTN_CLASS =
  'flex size-10 flex-shrink-0 items-center justify-center rounded-full bg-white/65 shadow-[0px_4px_8px_0px_rgba(0,0,0,0.06),0px_0px_0px_1px_rgba(0,0,0,0.04)] backdrop-blur-[40px] transition-filter duration-150 hover:brightness-95 aria-expanded:brightness-95 focus-ring'

const CUSTOMER_PAID_TAG = 'CUSTOMER_PAID'

const isCustomerPaidTag = (value: unknown) =>
  typeof value === 'string' &&
  value
    .trim()
    .replace(/[\s-]+/g, '_')
    .toUpperCase() === CUSTOMER_PAID_TAG

interface ChannelHeaderProps {
  className?: string
  onBack?: () => void
  showBackButton: boolean
  showStarButton?: boolean
  onLeaveConversation?: (channel: ChannelType) => void
  onBlockParticipant?: (participantId?: string) => void
  showDeleteConversation?: boolean
  showBlockParticipant?: boolean
  showReportParticipant?: boolean
  onDeleteConversationClick?: () => void
  onBlockParticipantClick?: () => void
  onReportParticipantClick?: () => void
  customChannelActions?: React.ReactNode
  renderChannelActions?: React.ReactNode
  showChannelInfo?: boolean
  onParticipantNameClick?: () => void
}

const ChannelHeader: React.FC<ChannelHeaderProps> = ({
  className,
  onBack,
  showBackButton,
  showStarButton = false,
  onLeaveConversation,
  onBlockParticipant,
  showDeleteConversation = true,
  showBlockParticipant = true,
  showReportParticipant = true,
  onDeleteConversationClick,
  onBlockParticipantClick,
  onReportParticipantClick,
  customChannelActions,
  renderChannelActions,
  showChannelInfo = true,
  onParticipantNameClick,
}) => {
  const { channel } = useChannelStateContext()
  const { client } = useChatContext()

  const participant = React.useMemo(
    () =>
      resolveConversationParticipant(
        channel.state?.members,
        client?.userID,
        channel.type
      ),
    [channel.state?.members, client?.userID, channel.type]
  )

  const participantName = resolveParticipantDisplayName(participant?.user)
  const participantImage = participant?.user?.image
  const isStarred = useChannelStar(channel)
  const isPaidCustomer =
    isCustomerPaidTag(channel.data?.customer_tag) &&
    participant?.is_follower === true

  const showStarBadge = showStarButton && isStarred
  const hasNameAdornment =
    isPaidCustomer || showStarBadge || Boolean(onParticipantNameClick)

  const handleStarClick = async () => {
    try {
      if (isStarred) {
        await (channel as ChannelType).unpin()
      } else {
        await (channel as ChannelType).pin()
      }
    } catch (error) {
      console.error(
        '[ChannelHeaderRedesign] Failed to update pinned status:',
        error
      )
    }
  }

  const identityContent = (
    <>
      <Avatar
        id={participant?.user?.id || channel.id || 'unknown'}
        name={participantName}
        image={participantImage}
        shape="circle"
        size={48}
        className="-mb-2"
      />
      <span
        className={classNames(
          'relative z-10 flex max-w-full flex-col items-center justify-center rounded-full border border-white/10 bg-white/65 py-1.5 shadow-[0px_0px_0px_0px_rgba(0,0,0,0.04),0px_1px_2px_0px_rgba(0,0,0,0.04),0px_8px_32px_0px_rgba(0,0,0,0.1)] backdrop-blur-[2px] transition-filter duration-150 group-hover:brightness-95',
          hasNameAdornment ? 'pl-3 pr-2' : 'px-3'
        )}
      >
        <span className="flex max-w-full items-center justify-center">
          <span className="min-w-0 truncate text-sm font-bold leading-[1.43] tracking-[0.28px] text-black/90">
            {participantName}
          </span>
          {hasNameAdornment && (
            <span className="ml-2 flex gap-1">
              {isPaidCustomer && (
                <span
                  aria-label="Paid customer"
                  className="flex size-4 shrink-0 items-center justify-center rounded-full bg-[#34C759] text-white"
                >
                  <CurrencyDollarIcon className="size-2.5" weight="bold" />
                </span>
              )}
              {showStarBadge && (
                <span className="messaging-header-star-badge flex overflow-hidden">
                  <span
                    aria-label="Starred conversation"
                    className="flex size-4 shrink-0 items-center justify-center rounded-full bg-[#FFD60A] text-white"
                  >
                    <StarIcon className="size-2.5" weight="fill" />
                  </span>
                </span>
              )}
              {onParticipantNameClick && (
                <CaretRightIcon
                  aria-hidden="true"
                  className="size-4 shrink-0 text-black/65"
                  weight="bold"
                />
              )}
            </span>
          )}
        </span>
      </span>
    </>
  )

  return (
    <div
      className={classNames(
        '@container bg-[linear-gradient(180deg,#FBFAF9_0%,rgba(251,250,249,0.92)_58%,rgba(251,250,249,0)_100%)]',
        className
      )}
    >
      <div className="grid min-h-[100px] grid-cols-[minmax(40px,1fr)_auto_minmax(40px,1fr)] items-start pb-2 pt-5 @lg:min-h-[104px] @lg:pt-6">
        <div className="flex items-start">
          {showBackButton && (
            <button
              className={classNames(
                ICON_BTN_CLASS,
                'messaging-channel-view-back-button-mobile messaging-channel-view-back-button-desktop'
              )}
              onClick={onBack || (() => {})}
              type="button"
              aria-label="Back to conversations"
            >
              <ArrowLeftIcon className="size-5 text-black/90" />
            </button>
          )}
        </div>

        <div className="flex min-w-0 justify-center" data-dd-privacy="mask">
          {onParticipantNameClick ? (
            <button
              type="button"
              onClick={onParticipantNameClick}
              aria-label={`View details for ${participantName}`}
              className="group flex min-w-0 max-w-full appearance-none flex-col items-center border-0 bg-transparent px-2 focus-ring focus-visible:outline-none"
            >
              {identityContent}
            </button>
          ) : (
            <div className="flex min-w-0 max-w-full flex-col items-center px-2">
              {identityContent}
            </div>
          )}
        </div>

        <div className="flex items-start justify-end gap-2">
          {showStarButton && (
            <button
              className={ICON_BTN_CLASS}
              onClick={handleStarClick}
              type="button"
              aria-pressed={isStarred}
              aria-label={
                isStarred ? 'Unstar conversation' : 'Star conversation'
              }
            >
              <StarIcon
                className={classNames('size-5', {
                  'text-[#FFD60A]': isStarred,
                  'text-black/90': !isStarred,
                })}
                weight={isStarred ? 'fill' : 'regular'}
              />
            </button>
          )}
          {showChannelInfo &&
            (renderChannelActions !== undefined ? (
              renderChannelActions
            ) : (
              <ChannelActionsMenu
                channel={channel as ChannelType}
                participant={participant}
                showDeleteConversation={showDeleteConversation}
                showBlockParticipant={showBlockParticipant}
                showReportParticipant={showReportParticipant}
                onLeaveConversation={onLeaveConversation}
                onBlockParticipant={onBlockParticipant}
                onDeleteConversationClick={onDeleteConversationClick}
                onBlockParticipantClick={onBlockParticipantClick}
                onReportParticipantClick={onReportParticipantClick}
                customChannelActions={customChannelActions}
                triggerClassName={ICON_BTN_CLASS}
              />
            ))}
        </div>
      </div>
    </div>
  )
}

export default ChannelHeader
