import { Divider, Tooltip } from '@mui/material'
import { useSigitProfiles } from '../../hooks/useSigitProfiles'
import {
  formatTimestamp,
  fromUnixTimestamp,
  hexToNpub,
  npubToHex,
  shorten,
  SignStatus
} from '../../utils'
import { useSigitMeta } from '../../hooks/useSigitMeta'
import { UserAvatarGroup } from '../UserAvatarGroup'

import styles from './style.module.scss'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
  faCalendar,
  faCalendarCheck,
  faCalendarPlus,
  faEye,
  faFile,
  faFileCircleExclamation
} from '@fortawesome/free-solid-svg-icons'
import { getExtensionIconLabel } from '../getExtensionIconLabel'
import { useSelector } from 'react-redux'
import { State } from '../../store/rootReducer'
import { TooltipChild } from '../TooltipChild'
import { DisplaySigner } from '../DisplaySigner'
import { Meta } from '../../types'
import { extractFileExtensions } from '../../utils/file'

interface UsersDetailsProps {
  meta: Meta
}

export const UsersDetails = ({ meta }: UsersDetailsProps) => {
  const {
    submittedBy,
    signers,
    viewers,
    fileHashes,
    signersStatus,
    createdAt,
    completedAt,
    parsedSignatureEvents,
    signedStatus,
    isValid
  } = useSigitMeta(meta)
  const { usersPubkey } = useSelector((state: State) => state.auth)
  const profiles = useSigitProfiles([
    ...(submittedBy ? [submittedBy] : []),
    ...signers,
    ...viewers
  ])
  const userCanSign =
    typeof usersPubkey !== 'undefined' &&
    signers.includes(hexToNpub(usersPubkey))

  const { extensions, isSame } = extractFileExtensions(Object.keys(fileHashes))

  return submittedBy ? (
    <div className={styles.container}>
      <div className={styles.section}>
        <p>Signers</p>
        <div className={styles.users}>
          {submittedBy &&
            (function () {
              const profile = profiles[submittedBy]
              return (
                <Tooltip
                  key={submittedBy}
                  title={
                    profile?.display_name ||
                    profile?.name ||
                    shorten(hexToNpub(submittedBy))
                  }
                  placement="top"
                  arrow
                  disableInteractive
                >
                  <TooltipChild>
                    <DisplaySigner
                      status={isValid ? SignStatus.Signed : SignStatus.Invalid}
                      profile={profile}
                      pubkey={submittedBy}
                    />
                  </TooltipChild>
                </Tooltip>
              )
            })()}

          {submittedBy && signers.length ? (
            <Divider orientation="vertical" flexItem />
          ) : null}

          <UserAvatarGroup max={20}>
            {signers.map((signer) => {
              const pubkey = npubToHex(signer)!
              const profile = profiles[pubkey]

              return (
                <Tooltip
                  key={signer}
                  title={
                    profile?.display_name || profile?.name || shorten(pubkey)
                  }
                  placement="top"
                  arrow
                  disableInteractive
                >
                  <TooltipChild>
                    <DisplaySigner
                      status={signersStatus[signer]}
                      profile={profile}
                      pubkey={pubkey}
                    />
                  </TooltipChild>
                </Tooltip>
              )
            })}
            {viewers.map((signer) => {
              const pubkey = npubToHex(signer)!
              const profile = profiles[pubkey]

              return (
                <Tooltip
                  key={signer}
                  title={
                    profile?.display_name || profile?.name || shorten(pubkey)
                  }
                  placement="top"
                  arrow
                  disableInteractive
                >
                  <TooltipChild>
                    <DisplaySigner
                      status={SignStatus.Viewer}
                      profile={profile}
                      pubkey={pubkey}
                    />
                  </TooltipChild>
                </Tooltip>
              )
            })}
          </UserAvatarGroup>
        </div>
      </div>
      <div className={styles.section}>
        <p>Details</p>

        <Tooltip
          title={'Publication date'}
          placement="top"
          arrow
          disableInteractive
        >
          <span className={styles.detailsItem}>
            <FontAwesomeIcon icon={faCalendarPlus} />{' '}
            {createdAt ? formatTimestamp(createdAt) : <>&mdash;</>}
          </span>
        </Tooltip>

        <Tooltip
          title={'Completion date'}
          placement="top"
          arrow
          disableInteractive
        >
          <span className={styles.detailsItem}>
            <FontAwesomeIcon icon={faCalendarCheck} />{' '}
            {completedAt ? formatTimestamp(completedAt) : <>&mdash;</>}
          </span>
        </Tooltip>

        {/* User signed date */}
        {userCanSign ? (
          <Tooltip
            title={'Your signature date'}
            placement="top"
            arrow
            disableInteractive
          >
            <span className={styles.detailsItem}>
              <FontAwesomeIcon icon={faCalendar} />{' '}
              {hexToNpub(usersPubkey) in parsedSignatureEvents ? (
                parsedSignatureEvents[hexToNpub(usersPubkey)].created_at ? (
                  formatTimestamp(
                    fromUnixTimestamp(
                      parsedSignatureEvents[hexToNpub(usersPubkey)].created_at
                    )
                  )
                ) : (
                  <>&mdash;</>
                )
              ) : (
                <>&mdash;</>
              )}
            </span>
          </Tooltip>
        ) : null}
        <span className={styles.detailsItem}>
          <FontAwesomeIcon icon={faEye} /> {signedStatus}
        </span>
        {extensions.length > 0 ? (
          <span className={styles.detailsItem}>
            {!isSame ? (
              <>
                <FontAwesomeIcon icon={faFile} /> Multiple File Types
              </>
            ) : (
              getExtensionIconLabel(extensions[0])
            )}
          </span>
        ) : (
          <>
            <FontAwesomeIcon icon={faFileCircleExclamation} /> &mdash;
          </>
        )}
      </div>
    </div>
  ) : undefined
}
