import React, { useMemo } from 'react'
import { useSelector } from 'react-redux'

import { selectIsAnonymousUser } from '../../store/selectors/selectIsAnonymousUser'
import { selectUser } from '../../store/selectors/selectUser'
import { TraitValue } from '../TraitValue'
import { UserIndicator } from '../UserIndicator'

import {
  Alert,
  BasicTraits,
  SummaryBanner,
  TraitName,
  TraitRow,
  UserAvatar,
  UserDetailsContainer,
  UserName
} from './style'


const dateTimeFmter = new Intl.DateTimeFormat('en-US', {
  month: 'short',
  day: 'numeric',
  year: 'numeric'
})

export const UserDetails = () => {
  const isIdentified = !useSelector(selectIsAnonymousUser)
  const hasAlreadyIdentified = useMemo(() => isIdentified, [])
  const user = useSelector(selectUser)

  return (
    <UserDetailsContainer>
      <SummaryBanner>
        <UserAvatar>
          <UserIndicator identified={isIdentified} disableTransition={hasAlreadyIdentified} />
        </UserAvatar>
        <UserName>
          <TraitValue heading light placeholder='William'>
            {user?.traits?.firstName}
          </TraitValue>
          <TraitValue heading placeholder='Cook'>
            {user?.traits?.lastName}
          </TraitValue>
        </UserName>
      </SummaryBanner>
      {!isIdentified && (
        <Alert>
          <strong>This is an anonymous session</strong>
          Use Segment&apos;s{' '}
          <a target='_blank' href='https://segment.com/docs/connections/spec/identify/' rel='noreferrer'>
            identify
          </a>{' '}
          feature to associate the data to an individual and measure their activity across multiple sessions and
          devices.
        </Alert>
      )}
      <BasicTraits>
        <TraitRow>
          <TraitName>Gender:</TraitName>
          <TraitValue placeholder='Male'>{user?.traits?.gender}</TraitValue>
        </TraitRow>
        <TraitRow>
          <TraitName>Date of birth:</TraitName>
          <TraitValue placeholder='Mar 10, 1996'>
            {user?.traits?.birthday && dateTimeFmter.format(new Date(user.traits.birthday))}
          </TraitValue>
        </TraitRow>
        <TraitRow>
          <TraitName>Phone number:</TraitName>
          <TraitValue placeholder='+1 778 123 8976'>{user?.traits?.phone}</TraitValue>
        </TraitRow>
        <TraitRow>
          <TraitName>Email:</TraitName>
          <TraitValue placeholder='will.cook@gmail.com'>{user?.traits?.email}</TraitValue>
        </TraitRow>
        <TraitRow>
          <TraitName>Street address:</TraitName>
          <TraitValue placeholder='4521 E34 Ave'>{user?.traits?.address?.street}</TraitValue>
        </TraitRow>
      </BasicTraits>
      <p>
        Learn about other available traits{' '}
        <a target='_blank' href='https://segment.com/docs/connections/spec/identify/#traits' rel='noreferrer'>
          here
        </a>
        .
      </p>
    </UserDetailsContainer>
  )
}
