import {memo, createElement, useState} from "react";
import {
  Avatar,
  Breadcrumb,
  Button,
  Card,
  ColorPicker,
  Input,
  InputNumber,
  Layout,
  Menu,
  Slider,
  Space,
  Radio, Select, Tooltip
} from "antd";
import {
  CloseOutlined, ExclamationCircleOutlined,
  GithubFilled,
  InfoCircleFilled,
  LaptopOutlined,
  QuestionCircleFilled,
  UserOutlined
} from "@ant-design/icons";
import {styled} from "styled-components";
import {COLOR_PRIMARY, ImageUrl, THEME_RESOURCE} from "../pages/LoginPage/constants";
import themeSlice from "../../styles/theme/slice";
import {useAppDispatch, useAppSelector} from "../../redux/configureStore";
import {
  selectColorPrimary,
  selectCompact,
  selectDesignerStatus, selectRadius,
  selectThemeKey
} from "../../styles/theme/slice/selectors";
import useI18NPrefix from "../hooks/useI18NPrefix";
import {themes} from "../../styles/theme/themes";
import {changeLang, getLang} from "../../locales/i18n";
const { Content, Sider } = Layout;

export const ThemeDesigner = memo((props)=>{
  const dispatch = useAppDispatch();
  /** 全局i18n */
  const t = useI18NPrefix('global');
  /** 主题设计器打开状态 */
  const open = useAppSelector(selectDesignerStatus);
  /** 关闭设计器 */
  const onClose = ()=>{
    dispatch(themeSlice.actions.openThemeDesigner(false));
  }
  const theme=useAppSelector(selectThemeKey);
  const color=useAppSelector(selectColorPrimary);
  const compact=useAppSelector(selectCompact);
  const radius=useAppSelector(selectRadius);
  const [lang,setLang]=useState(getLang());

  const setTheme=(e)=>{
    dispatch(themeSlice.actions.changeTheme({
      theme:e,
      color:themes[e].colorPrimary || COLOR_PRIMARY.LEVEL1,
      radius:themes[e].borderRadius || radius,
    }))
  }

  const setCompact=(e)=>{
    dispatch(themeSlice.actions.changeCompact(e))
  }

  const setRadius=(e)=>{
    dispatch(themeSlice.actions.changeRadius(e))
  }

  const setColor=(e)=>{
    dispatch(themeSlice.actions.changeColor(e));
  }

  const onSubmit = ()=>{
    changeLang(lang)
  }

  /** 主题预览 */
  const ThemeExample = ({items}) => (
    <div style={{alignItems: "center", display: "flex",marginBottom:20}}>
      <Label>{t('theme.self')}：</Label>
      {
        items.map((item) => (
          THEME_RESOURCE[item] &&
          <Cover key={item} checked={theme===item} onClick={()=>setTheme(item)}>
            <img alt="example" src={THEME_RESOURCE[item]}/>
          </Cover>
        ))
      }
    </div>
  )

  /** 主色预览 */
  const ColorExample = ({items}) => (
    <div style={{alignItems: "center", display: "flex",marginBottom:20}}>
      <Label>{t('title.colorPrimary')}：</Label>
      <Input value={COLOR_PRIMARY[color]||color} style={{width:100}} onChange={(e)=>setColor(e.target.value)}/>
      {
        items.map((item) => {
          if (COLOR_PRIMARY[item]==='chroma'){
            return <ColorPicker key={item} value={color} onChange={(c)=>setColor(c.toHexString())}>
              <ColorCell color={COLOR_PRIMARY[item]} checked={color===COLOR_PRIMARY[item]}/>
            </ColorPicker>
          }else {
            return <ColorCell key={item} color={COLOR_PRIMARY[item]} checked={color===COLOR_PRIMARY[item]} onClick={()=>setColor(item)}/>
          }
        })
      }
    </div>
  );

  /** 主色预览 */
  const RadiusExample = () => {
    return (
      <div style={{alignItems: "center", display: "flex", marginBottom: 20}}>
        <Label>{t('title.radius')}：</Label>
        <InputNumber value={radius} min={0} max={20} formatter={(value) => `${value}px`} parser={(value) => value?.replace('px', '')} onChange={setRadius}/>
        <Slider value={radius} min={0} max={20} style={{width: 200, marginLeft: 25}} onChange={setRadius}/>
      </div>
    )
  };

  /** 宽松度 */
  const LoosenessExample = () => (
    <div style={{alignItems: "center", display: "flex", marginBottom: 20}}>
      <Label>{t('title.looseness')}：</Label>
      <Radio.Group onChange={(e)=>setCompact(e.target.value)} value={compact}>
        <Radio value={false}>{t('title.default')}</Radio>
        <Radio value={true}>{t('title.compact')}</Radio>
      </Radio.Group>
    </div>
  );

  /** 语言 */
  const LangExample = () => (
    <div style={{alignItems: "center", display: "flex", marginBottom: 20}}>
      <Label>{t('lang.self')}：</Label>
      <Select
        style={{width:200}}
        showSearch
        value={lang}
        optionFilterProp="label"
        onChange={setLang}
        options={[
          {
            value: 'zh',
            label: t('lang.zh'),
          },
          {
            value: 'en',
            label: t('lang.en'),
          },
          {
            value: 'ko',
            label: t('lang.ko'),
          },
        ]}
      />
      <Tooltip title={t('placeholder.lang')}>
        <ExclamationCircleOutlined style={{marginLeft:10}}/>
      </Tooltip>
    </div>
  );

  return (
    !open ? null :
      <Container
        extra={<Button type="text" onClick={onClose}><CloseOutlined/></Button>}
        styles={{
          body: {
            padding: '10% 20%',
            height: '100%',
            width: '100%',
            overflow: "hidden",
            backgroundImage: ImageUrl
          }
        }}
      >
        <Card
          title="Index system"
          extra={
            <Space size={15}>
              <InfoCircleFilled key="InfoCircleFilled"/>
              <QuestionCircleFilled key="QuestionCircleFilled"/>
              <GithubFilled key="GithubFilled" />
              <Avatar shape="circle" src='https://gw.alipayobjects.com/zos/antfincdn/efFD%24IOql2/weixintupian_20170331104822.jpg' />
            </Space>
          }
          styles={{
            body:{
              padding:0,
              borderTop:'1px solid rgba(0, 0, 0, 0.05)'
            }
          }}
        >
          <Layout>
            <Sider width={200}>
              <Menu
                mode="inline"
                defaultSelectedKeys={['1']}
                defaultOpenKeys={['sub1','sub2']}
                style={{
                  height: '100%',
                  borderRight: 0,
                }}
                items={items2}
              />
            </Sider>
            <Layout style={{padding: '0 24px 24px'}}>
              <Breadcrumb items={[{title: 'Home'},{title: 'List'}, {title: 'App'}]} style={{margin: '16px 0 0 0'}}/>
              <h1 style={{margin:'14px 0'}}>{t("title.customTheme")}</h1>
              <Content>
                <Card
                  title={t("title.myTheme")}
                  style={{height:'100%',minHeight:500}}
                  extra={[
                    <Button onClick={onClose}>{t("button.default")}</Button>,
                    <Button onClick={onSubmit} type='primary' style={{marginLeft:15}}>{t("button.toUse")}</Button>
                  ]}
                >
                  <ThemeExample items={Object.keys(THEME_RESOURCE)}/>
                  <ColorExample items={Object.keys(COLOR_PRIMARY)}/>
                  <RadiusExample/>
                  <LoosenessExample/>
                  <LangExample/>
                </Card>
              </Content>
            </Layout>
          </Layout>
        </Card>
      </Container>
  )
})

const Cover = styled.div`
  cursor: pointer;
  margin-right: 25px;
  height: 80px;
  width: 120px;
  border: 1px solid inherit;
  overflow: hidden;
  border-radius: ${p=>p.theme.borderRadius}px;
  background-color: #f0f0f0;
  transition: transform 0.3s ease;
  box-shadow: ${p=>p?.checked && `0 0 0 1px #ffffff, 0 0 0 5px #1677FF;`};
  transform:${p=>p?.checked ?'scale(1.1)':'scale(1)'};
  &:hover {
    transform: scale(1.1); /* 鼠标悬停时整体放大0.1倍 */
  }
`

const ColorCell = styled.label`
  cursor: pointer;
  border-radius: 50%;
  border: 1px solid inherit;
  background-color: ${p => p?.color};
  width: 20px;
  height: 20px;
  margin-left: 20px;
  background: ${p => p?.color==='chroma' && 'conic-gradient(red, yellow, lime, aqua, blue, magenta, red)'} ;
  box-shadow: ${p => p?.checked && `0 0 0 1px #ffffff, 0 0 0 5px #1677FF;`};
  transition: all 0.1s;
`

const Container = styled(Card)`
  height: 100vh;
  width: 100vw;
  position:fixed;
  z-index: 999;
  box-shadow: 0px 0px 8px rgba(0, 0, 0, 0.2);
  opacity: 0;
  transform: scale(0);
  animation: diagonalAppear 0.5s ease forwards;
  @keyframes diagonalAppear {
    0% {
      transform: translate(-50%, 100%) scale(0);
      opacity: 0;
    }
    100% {
      transform: translate(0, 0) scale(1);
      opacity: 1;
    }
  }
`

const Label = styled.label`
  width: 100px;
  text-align: right;
  margin-right: 10px;
  &.required {
    // 添加必填红色*的样式
    &::before {
      display: inline-block;
      margin-inline-end: 4px;
      color: #ff4d4f;
      font-size: 14px;
      font-family: SimSun, sans-serif;
      line-height: 1;
      content: "*";
    }
  }
`

const items2 = [UserOutlined, LaptopOutlined].map((icon, index) => {
  const key = String(index + 1);
  return {
    key: `sub${key}`,
    icon: createElement(icon),
    label: `subnav ${key}`,
    children: new Array(3).fill(null).map((_, j) => {
      const subKey = index * 4 + j + 1;
      return {
        key: subKey,
        label: `option${subKey}`,
      };
    }),
  };
});

