import { Divider, Tooltip } from '@mui/material'
import { useSigitProfiles } from '../../hooks/useSigitProfiles'
import {
  extractFileExtensions,
  formatTimestamp,
  fromUnixTimestamp,
  hexToNpub,
  npubToHex,
  shorten,
  SignStatus
} from '../../utils'
import { UserAvatar } from '../UserAvatar'
import { FlatMeta } 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'

type UsersDetailsProps = Pick<
  FlatMeta,
  | 'submittedBy'
  | 'signers'
  | 'viewers'
  | 'fileHashes'
  | 'parsedSignatureEvents'
  | 'createdAt'
  | 'signedStatus'
  | 'completedAt'
  | 'signersStatus'
>

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

  const ext = 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
                  title={
                    profile?.display_name ||
                    profile?.name ||
                    shorten(hexToNpub(submittedBy))
                  }
                  placement="top"
                  arrow
                  disableInteractive
                >
                  <TooltipChild>
                    <UserAvatar pubkey={submittedBy} image={profile?.picture} />
                  </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>
        {ext.length > 0 ? (
          <span className={styles.detailsItem}>
            {ext.length > 1 ? (
              <>
                <FontAwesomeIcon icon={faFile} /> Multiple File Types
              </>
            ) : (
              getExtensionIconLabel(ext[0])
            )}
          </span>
        ) : (
          <>
            <FontAwesomeIcon icon={faFileCircleExclamation} /> &mdash;
          </>
        )}
      </div>
    </div>
  ) : undefined
}
