import React from 'react'

import { Box } from '../box'
import { styled, useDown, useStyleConfig, vui, VuiComponent } from '../core'
import { Divider } from '../divider'
import { Link } from '../link'
import Menu from '../menu'
import { T } from '../t'
import { cs, getCurrentYear } from '../utils'
import { FooterProvider } from './context'
import { FooterLinkData, FooterProps } from './footer.types'
import FooterColumn from './footerColumn'
import FooterContent from './footerContent'
import FooterHeading from './footerHeading'
import FooterLink from './footerLink'
import FooterRow from './footerRow'
import FooterSection from './footerSection'
import FooterSlimColumn from './footerSlimColumn'
import { defaultLinkedInUrl, FooterTrademark } from './footerTrademark'

/*@formatter:off*/
export const FooterBase = styled.divBox`
  background-color: darkBlue.main;
  color: white;
  padding: 5 3;
`
/*@formatter:on*/

const currentYear = getCurrentYear()

/** Branded Veracity Footer with trademark and links sections. Controls max-width of the content. */
export const Footer = vui<'div', FooterProps>((props, ref) => {
  const {
    applicationLinks,
    applicationSocialLinks = [],
    applicationStaticItems = [],
    children,
    className,
    columns,
    isApplication = false,
    isDNV = false,
    linkedIn,
    size,
    variant,
    isSlim,
    ...rest
  } = props

  const context = { size, variant }

  const styles = useStyleConfig('Footer', props)

  if (isApplication && !applicationLinks) console.error('Footer: isApplication is true but applicationLinks  not set.')

  const slimLinks: FooterLinkData[] = [
    {
      id: 'home',
      text: 'veracity.com',
      url: 'https://www.veracity.com/',
    },
  ]

  columns?.map(column => {
    column.map(section => {
      section.links?.map(link => {
        if (!link) return
        if (['home', 'support', 'status'].includes(link.id || '')) slimLinks.push(link)
      })
    })
  })

  const downMd = useDown('md')
  const downLg = useDown('lg')

  return (
    <FooterProvider value={context}>
      <FooterBase
        className={cs('vui-footer', isApplication ? 'vui-footer-app' : '', className)}
        px={isApplication ? '40px' : 3}
        py={isSlim ? (downMd ? '16px' : '9px') : 5}
        role="contentinfo"
        {...styles.container}
        ref={ref}
        {...rest}
      >
        {isApplication && (
          <FooterContent alignContent="center" alignItems="center" maxW="100%">
            <FooterRow alignContent="space-between" w={1}>
              <Box
                alignItems="self-start"
                columnGap={3}
                flex={{ xs: '0 0 100%', sm: '0 0 100%', md: '0 0 100%', lg: '0 0 50%' }}
                py={{ xs: 1, sm: 1, md: 1.25, lg: 1.5 }}
                wrap
              >
                {applicationLinks?.map((link, index) => (
                  <Box flex={{ xs: '0 0 50%', sm: '0 0 auto' }} key={index}>
                    {link.items && (
                      <Menu isLazy={false} offset={[-16, 9]} placement="top-start" size="lg" {...rest}>
                        <Menu.Button
                          as={Link}
                          className="vui-footerLink-trigger"
                          pt="3px"
                          role="button"
                          text={link.text}
                          title={link.text}
                          {...styles.link}
                          {...rest}
                        />

                        <Menu.List maxH={400} right={0} w={320} {...styles.list}>
                          {link.items.map(({ text, url }, index) => (
                            <Menu.Item
                              isTruncated
                              key={index}
                              linkProps={{ href: url }}
                              text={text}
                              title={text}
                              {...styles.item}
                            />
                          ))}
                        </Menu.List>
                      </Menu>
                    )}

                    {!link.items && <FooterLink {...link} href={link.url} />}
                  </Box>
                ))}
              </Box>
              {downLg && <Divider borderColor="sandstone.main" mb={0.5} mt={1} w={1} />}
              <Box
                centerV
                columnGap={3}
                flex={{ xs: '0 0 100%', sm: '0 0 100%', md: '0 0 100%', lg: '0 0 50%' }}
                justifyContent={{ sm: 'center', lg: 'flex-end' }}
                py={{ xs: 1, sm: 1, md: 1.25, lg: 1.5 }}
                wrap
              >
                {applicationStaticItems?.map((text, index) => (
                  <Box key={index}>
                    <T size="sm">{text}</T>
                  </Box>
                ))}

                {isDNV ? (
                  <Box>
                    <T size="sm">&copy; DNV AS {currentYear}</T>
                  </Box>
                ) : (
                  <Box>
                    <T size="sm">
                      <T weight="demi">Veracity by DNV</T>, DNV AS
                    </T>
                  </Box>
                )}
                <Box>
                  {applicationSocialLinks?.map((link, index) => (
                    <Link
                      aria-label={link.text}
                      fontWeight="demi"
                      href={link.url}
                      iconLeft={<Link.Icon name={`cubCircle${link.text}`} radius="50%" size="xs" />}
                      isExternal
                      key={index}
                      mr={1}
                      size={{ _: 'sm', md: 'md' }}
                      {...styles.link}
                    ></Link>
                  ))}
                  <Link
                    fontWeight="demi"
                    href={linkedIn ?? defaultLinkedInUrl}
                    isExternal
                    size={{ _: 'sm', md: 'md' }}
                    {...styles.link}
                  >
                    <FooterHeading fontSize="16px" mb={0} text="Follow us" />
                  </Link>
                </Box>
              </Box>
            </FooterRow>
          </FooterContent>
        )}

        {!isApplication && isSlim && (
          <FooterContent alignContent="center" alignItems="center" maxW={{ xs: 343, sm: 305, md: 720, lg: 975 }}>
            <FooterRow>
              {slimLinks.map(({ text, url, id }, index) => {
                /** if the screen is small drop one specific link */
                if (downLg && id === 'support') return

                return (
                  <FooterSlimColumn key={index}>
                    <FooterLink href={url} text={text} />
                  </FooterSlimColumn>
                )
              })}

              {downMd && <Divider borderColor="sandstone.main" mb={0.5} mt={1} w={1} />}

              <FooterSlimColumn centerV>
                <T size="xs">
                  <T weight="demi">Veracity by DNV</T>, DNV AS
                </T>
              </FooterSlimColumn>
              <FooterSlimColumn>
                <Link
                  fontWeight="demi"
                  href={linkedIn ?? defaultLinkedInUrl}
                  iconLeft={<Link.Icon mr={1} name="cubCircleLinkedIn" radius="50%" size="xs" />}
                  isExternal
                  size={{ _: 'sm', md: 'md' }}
                  {...styles.link}
                >
                  <FooterHeading fontSize="16px" mb={0} text="Follow us" />
                </Link>
              </FooterSlimColumn>
            </FooterRow>
          </FooterContent>
        )}

        {!isApplication && !isSlim && (
          <FooterContent>
            {children ??
              (columns && (
                <FooterRow>
                  {columns.map((sections, index) => (
                    <FooterColumn key={index} sections={sections} />
                  ))}
                </FooterRow>
              ))}

            {children || columns ? <Divider borderColor="sandstone.main" my={4} /> : null}

            <FooterRow>
              <FooterTrademark linkedIn={linkedIn} />
            </FooterRow>
          </FooterContent>
        )}
      </FooterBase>
    </FooterProvider>
  )
}) as VuiComponent<'div', FooterProps> & {
  Column: typeof FooterColumn
  Content: typeof FooterContent
  Heading: typeof FooterHeading
  Link: typeof FooterLink
  Row: typeof FooterRow
  Section: typeof FooterSection
}

Footer.Column = FooterColumn
Footer.Content = FooterContent
Footer.Heading = FooterHeading
Footer.Link = FooterLink
Footer.Row = FooterRow
Footer.Section = FooterSection
Footer.displayName = 'Footer'

export default Footer
