import { cloneElement, useMemo } from 'react'
import Container from '@/components/shared/Container'
import Card from '@/components/ui/Card'
import Logo from '@/components/template/Logo'
import type { ReactNode, ReactElement } from 'react'
import type { CommonProps } from '@/@types/common'
import { HiArrowLeft, HiCheck } from 'react-icons/hi'
import { Avatar, Select } from '@/components/ui'
import i18n, { dateLocales } from '@/locales'
import { useStoreActions, useStoreState } from '@/store'
import appConfig from '@/configs/app.config'
import dayjs from 'dayjs'
import { components } from 'react-select'
import { ROUTES_ENUM } from '@/routes/route.constant'
import { hasSubdomain } from '@/utils/subdomain'

interface SimpleProps extends CommonProps {
  content?: ReactNode
}

const Simple = ({ children, content, ...rest }: SimpleProps) => {
  const { config } = useStoreState((state) => state.abpConfig)
  const { setLang } = useStoreActions((actions) => actions.locale)
  const currentCulture = config?.localization?.currentCulture?.cultureName

  const languageList = config?.localization.languages

  const languageOptions = useMemo(() => {
    return (
      languageList?.map((lang) => ({
        label: lang.displayName,
        value: lang.cultureName,
        cultureName: lang.cultureName,
        imgPath: `/img/countries/${lang.cultureName}.png`,
      })) || []
    )
  }, [languageList])

  const onLanguageSelect = (cultureName = appConfig.locale) => {
    const dispatchLang = () => {
      i18n.changeLanguage(cultureName)
      setLang(cultureName)
    }

    if (dateLocales[cultureName]) {
      dateLocales[cultureName]()
        .then(() => {
          dayjs.locale(cultureName)
          dispatchLang()
        })
        .catch(() => {
          dispatchLang()
        })
    } else {
      dispatchLang()
    }
  }

  const CustomSelectOption = ({ innerProps, label, data, isSelected }: any) => {
    return (
      <div
        className={`flex items-center justify-between p-2 ${
          isSelected ? 'bg-gray-100 dark:bg-gray-500' : 'hover:bg-gray-50 dark:hover:bg-gray-600'
        }`}
        {...innerProps}
      >
        <div className="flex items-center">
          <Avatar shape="circle" size={24} src={data.imgPath} title={data.label} />
        </div>
        {isSelected && <HiCheck className="text-emerald-500 text-xl" />}
      </div>
    )
  }

  const CustomSingleValue = ({ data, ...props }: any) => {
    return (
      <components.SingleValue {...props}>
        <div className="flex items-center">
          <Avatar
            className="ltr:mr-2 rtl:ml-2"
            shape="circle"
            size={24}
            src={`/img/countries/${data.cultureName}.png`}
            title={data.label}
          />
        </div>
      </components.SingleValue>
    )
  }

  return (
    <div className="h-full">
      <Container className="flex flex-col flex-auto items-center justify-center min-w-0 h-full">
        <Card className="min-w-[320px] md:min-w-[450px]" bodyClass="md:p-10">
          <div className="flex justify-between items-center mb-4">
            {!hasSubdomain() && (
              <a
                href={ROUTES_ENUM.public.home}
                rel="noopener noreferrer"
                className="text-gray-500 hover:text-gray-700"
              >
                <HiArrowLeft className="text-2xl" />
              </a>
            )}

            <div className="w-12">
              <Select
                className="cursor-pointer"
                options={languageOptions}
                components={{
                  Option: CustomSelectOption,
                  SingleValue: CustomSingleValue,
                }}
                value={languageOptions.find((lang) => lang.cultureName === currentCulture)}
                onChange={(option) => onLanguageSelect(option?.value)}
                styles={{
                  control: (base) => ({
                    ...base,
                    minHeight: 'auto',
                    border: 'none',
                    boxShadow: 'none',
                    backgroundColor: 'transparent',
                    cursor: 'pointer',
                  }),
                  indicatorsContainer: (base) => ({
                    ...base,
                    display: 'none',
                  }),
                }}
              />
            </div>
          </div>

          <div className="text-center">
            <Logo type="streamline" imgClass="mx-auto" />
          </div>

          <div className="text-center">
            {content}
            {children
              ? cloneElement(children as ReactElement, {
                  contentClassName: 'text-center',
                  ...rest,
                })
              : null}
          </div>
        </Card>
      </Container>
    </div>
  )
}

export default Simple
