import { Button, type ButtonProps } from '@mui/material';
import CookieConsent, { resetCookieConsentValue } from 'react-cookie-consent';

import { styled } from '../Theme';
import type { Locale, Translations } from '../type';

export { resetCookieConsentValue };

const translations: Translations = {
  en: {
    content:
      'We use cookies and other tracking technologies to improve your browsing experience on our website, to show you personalized content, to analyze our website traffic, and to understand where our visitors are coming from.',
    agree: 'I Understand',
  },
  zh: {
    content:
      '我们使用 cookies 和其他跟踪技术来改善您在我们网站上的浏览体验，向您展示个性化的内容，分析我们的网站流量，并了解我们的访问者来自哪里。',
    agree: '我知道了',
  },
};

function inIframe() {
  try {
    return window.self !== window.top;
  } catch (e) {
    return true;
  }
}

function AcceptButton(props: ButtonProps) {
  return <Button variant="contained" {...props} />;
}

export interface CookieConsentProps extends React.ComponentProps<typeof CookieConsent> {
  locale?: Locale;
  displayInIframe?: false | true;
}

/**
 * DefaultCookieConsent, 对 react-cookie-consent package 封装, 以便 arcblock 内部产品可以快速使用
 * - 默认内容
 * - 默认配置/样式
 */
export default function DefaultCookieConsent({
  children,
  locale = 'en',
  style = {},
  displayInIframe = false,
  ...rest
}: CookieConsentProps) {
  if (!displayInIframe && inIframe()) {
    return null;
  }
  if (locale && !translations[locale]) {
    // eslint-disable-next-line no-param-reassign
    locale = 'en';
  }
  return (
    <Wrapper style={style}>
      <CookieConsent
        disableStyles
        disableButtonStyles
        ButtonComponent={AcceptButton}
        buttonText={translations[locale].agree}
        buttonStyle={{ marginTop: 16, padding: '6px 16px' }}
        {...rest}>
        {children || <p style={{ margin: 0 }}>{translations[locale].content}</p>}
      </CookieConsent>
    </Wrapper>
  );
}

const Wrapper = styled('div')`
  box-sizing: border-box;
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 999;
  max-width: 440px;
  padding: 16px 24px;
  font-size: 16px;
  color: ${({ theme }) => theme.palette.grey[500]};
  background: ${({ theme }) => theme.palette.background.paper};
  border: 1px solid ${({ theme }) => theme.palette.divider};
  border-radius: ${({ theme }) => theme.shape.borderRadius}px;
  box-shadow: ${({ theme }) => theme.shadows[4]};
  &:empty {
    display: none;
  }
  button {
    min-width: 200px;
  }

  @media screen and (max-width: 480px) {
    left: 16px;
    right: 16px;
    bottom: 16px;
    width: auto;
    button {
      display: block;
      width: 100%;
    }
  }
`;
