import { Box, Divider, Typography, IconButton, Collapse } from '@mui/material';
import type { BoxProps } from '@mui/material';
import Avatar from '@arcblock/ux/lib/Avatar';
import DID from '@arcblock/ux/lib/DID';
import { useMemoizedFn } from 'ahooks';
import { translate } from '@arcblock/ux/lib/Locale/util';
import { useLocaleContext } from '@arcblock/ux/lib/Locale/context';
import noop from 'lodash/noop';
import { useEffect, useState } from 'react';
import Toast from '@arcblock/ux/lib/Toast';
import type { AxiosError } from 'axios';
import { parseURL, joinURL } from 'ufo';
import {
  KeyboardArrowDown as KeyboardArrowDownIcon,
  KeyboardArrowUp as KeyboardArrowUpIcon,
} from '@mui/icons-material';

import { translations } from '../../libs/locales';
import type { User, UserAddress, UserMetadata } from '../../../@types';
import { formatAxiosError } from '../../libs/utils';
import { currentTimezone, getStatusDuration, isValidUrl, isDuplicateUrl } from './utils';
import SwitchRole from './switch-role';
import UserMetadataComponent from './metadata';
import UserStatus from './user-status';
import UserInfo from './user-info';
import { client } from '../../../libs/client';
import SocialActions from './social-actions';

export default function UserBasicInfo({
  user,
  isMyself = true,
  showFullDid = true,
  switchPassport,
  switchProfile,
  isMobile = false,
  onlyProfile = false,
  refreshProfile,
  isShowSocialActions = false,
  ...rest
}: {
  user: User;
  isMyself?: boolean;
  showFullDid?: boolean;
  switchPassport: () => void;
  switchProfile: () => void;
  size?: number;
  isMobile?: boolean;
  onlyProfile?: boolean;
  refreshProfile: () => void;
  isShowSocialActions?: boolean;
} & BoxProps) {
  const { locale } = useLocaleContext();
  const [userStatus, setUserStatus] = useState<UserMetadata['status']>(undefined);
  const t = useMemoizedFn((key, data = {}) => {
    return translate(translations, key, locale, 'en', data);
  });

  const [expanded, setExpanded] = useState(!isMobile || onlyProfile);

  useEffect(() => {
    setUserStatus(user?.metadata?.status);
  }, [user]);

  // Add effect to handle mobile state changes
  useEffect(() => {
    setExpanded(!isMobile || onlyProfile);
  }, [isMobile, onlyProfile]);

  const onUpdateUserStatus = async (v: UserMetadata['status']) => {
    if (!isMyself) {
      return;
    }
    try {
      if (v) {
        const dateRange = getStatusDuration(v);
        v.dateRange = dateRange.length > 0 ? dateRange : (userStatus?.dateRange ?? []);
      }
      setUserStatus(v);
      await client.user.saveProfile({
        // @ts-ignore
        metadata: {
          ...(user?.metadata ?? { joinedAt: user?.createdAt, email: user?.email, phone: user?.phone }),
          status: v || {},
        },
      });
      refreshProfile();
    } catch (err) {
      console.error(err);
      Toast.error(formatAxiosError(err as AxiosError));
    }
  };

  const toggleExpand = () => {
    setExpanded(!expanded);
  };

  const onSave = async (v: { metadata: UserMetadata; address: UserAddress }) => {
    if (!isMyself) {
      return;
    }
    const { metadata, address } = v;
    try {
      const newLinks =
        metadata?.links
          ?.map((link, index) => {
            if (!link.url || !isValidUrl(link.url)) return null;

            // 去重：如果 URL 相同则跳过（忽略协议和大  小写）
            if (index > 0) {
              const prevLinks = metadata.links?.slice(0, index);
              if (prevLinks?.some((l) => isDuplicateUrl(l.url, link.url))) {
                return null;
              }
            }

            try {
              const parsedUrl = parseURL(link.url);
              // 如果没有协议，添加 https
              if (!parsedUrl.protocol) {
                link.url = joinURL('https://', link.url);
              }
              return link;
            } catch (e) {
              console.error('Invalid URL:', link.url);
              return null;
            }
          })
          .filter((l) => !!l) || [];
      metadata.links = newLinks;
      // @ts-ignore
      await client.user.saveProfile({ metadata, address });
      refreshProfile();
    } catch (err) {
      console.error(err);
      Toast.error(formatAxiosError(err as AxiosError));
    }
  };

  return (
    <Box
      {...rest}
      sx={{
        position: 'relative',
        ...(rest.sx ?? {}),
      }}>
      <Box
        className="user-info"
        sx={{
          display: 'flex',
          flexDirection: isMobile ? 'row' : 'column',
          gap: 2,
        }}>
        <Box
          className="user-avatar"
          sx={{
            position: 'relative',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}>
          <Avatar
            //  @ts-ignore
            src={user?.avatar}
            did={user?.did}
            size={rest.size || (isMobile ? 64 : 100)}
            variant="circle"
            shape="circle"
            sx={{
              borderRadius: '100%',
              backgroundColor: '#fff',
              position: 'relative',
              overflow: 'hidden',
              flexShrink: 0,
              ...(isMyself
                ? {
                    cursor: 'pointer',
                    '&::after': {
                      content: `"${t('switchProfile')}"`,
                      color: 'white',
                      position: 'absolute',
                      fontSize: '12px',
                      bottom: 0,
                      left: 0,
                      right: 0,
                      height: '25%',
                      backgroundColor: 'rgba(0, 0, 0, 0.3)',
                      display: 'flex',
                      justifyContent: 'center',
                      alignItems: 'center',
                    },
                  }
                : {}),
            }}
            onClick={isMyself ? switchProfile : noop}
          />
          <UserStatus
            isMobile={isMobile}
            size={rest.size || (isMobile ? 64 : 100)}
            isMyself={isMyself}
            timezone={user?.metadata?.timezone || currentTimezone}
            status={userStatus}
            onChange={onUpdateUserStatus}
          />
        </Box>
        <Box
          sx={{
            flex: 1,
            overflow: 'hidden',
          }}>
          <Typography
            variant="h6"
            component="div"
            sx={{
              flex: 1,
              fontWeight: 600,
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              fontSize: '24px !important',
              flexWrap: 'wrap',
            }}>
            <span
              style={{
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}>
              {user?.fullName}
            </span>
            {isMyself ? <SwitchRole user={user} switchPassport={switchPassport} /> : null}
          </Typography>
          <DID
            did={user.did}
            size={16}
            showQrcode
            copyable
            compact={!showFullDid}
            responsive={!showFullDid}
            locale={locale}
          />
        </Box>
      </Box>
      {!isMyself && isShowSocialActions ? (
        <Box sx={{ mt: 2 }}>
          <SocialActions user={user} />
        </Box>
      ) : null}
      <UserMetadataComponent isMobile={isMobile} isMyself={isMyself} user={user} onSave={onSave} />
      {isMyself ? (
        <>
          <Divider sx={{ my: isMobile ? 1 : 3 }} />
          {isMobile && !onlyProfile ? (
            <Box
              sx={{
                display: 'flex',
                justifyContent: 'center',
                mb: 0,
              }}>
              <IconButton
                size="small"
                onClick={toggleExpand}
                sx={{
                  backgroundColor: 'grey.50',
                  '&:hover': {
                    backgroundColor: 'grey.50',
                    opacity: 0.8,
                  },
                }}>
                {expanded ? <KeyboardArrowUpIcon /> : <KeyboardArrowDownIcon />}
              </IconButton>
            </Box>
          ) : null}
          <Collapse in={expanded} timeout="auto">
            <Typography
              component="p"
              sx={{
                color: 'text.secondary',
                fontSize: '14px',
                mb: 2,
              }}>
              {t('profile.justForYou')}
            </Typography>
            <UserInfo user={user} isMySelf={isMyself} />
          </Collapse>
        </>
      ) : null}
    </Box>
  );
}
