import { useMemo } from 'react';

import { capitalize } from 'lodash-es';
import {
  IconBuildingSkyscraper,
  IconCalendarDue,
  IconDeviceDesktop,
  IconExternalLink,
  IconLink,
  IconMapPin,
  IconMoodSmile,
  IconUsersGroup,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider/Divider';
import Stack from '@material-hu/mui/Stack';
import { slideInUp } from '@material-hu/utils/animations';

import Image from '@material-hu/components/composed-components/Image';
import SeeMoreText from '@material-hu/components/composed-components/SeeMoreText';
import List from '@material-hu/components/design-system/List';
import ListItem from '@material-hu/components/design-system/List/components/ListItem';
import Skeleton from '@material-hu/components/design-system/Skeleton';
import Title from '@material-hu/components/design-system/Title';

import defaultSessionCover from 'src/assets/defaultSessionCover.webp';
import { appearFromLeft } from 'src/constants/animation';
import useAuth from 'src/contexts/JWTContext';
import useFormatDate from 'src/hooks/useFormatDate';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getCurrentLocale } from 'src/utils/locale';
import { getTimeZoneInfo } from 'src/utils/timeUtils';

import { type AttendanceSidebarItem, type SessionDetail } from '../../types';

type AttendanceSidebarProps = {
  session?: SessionDetail;
  totalAssigned?: number;
  isLoading: boolean;
};

export const AttendanceSidebar = ({
  session,
  totalAssigned,
  isLoading,
}: AttendanceSidebarProps) => {
  const { t } = useLokaliseTranslation('learning');
  const { user } = useAuth();
  const localeCode = getCurrentLocale(user).code;
  const { formatDate } = useFormatDate();

  const items: AttendanceSidebarItem[] = useMemo(() => {
    if (!session) return [];

    const sessionDate = `${t('general:date', {
      day: capitalize(formatDate(session.localDate, 'EEEE dd')),
      month: formatDate(session.localDate, 'LLLL'),
    })}`;
    const sessionTimezone = getTimeZoneInfo(session.timeZone);

    return [
      {
        id: 'session-date',
        copetin: t('session.detail.date'),
        title: `${sessionDate} - ${session.startTime} ${t('general:hours_short')} • ${sessionTimezone}`,
        icon: IconCalendarDue,
      },
      {
        id: 'session-type',
        copetin: t('session.type.title_one'),
        title: t(`session.type.${session.type.toLowerCase()}_one`),
        icon:
          session.type === 'PRESENTIAL'
            ? IconBuildingSkyscraper
            : IconDeviceDesktop,
      },
      {
        id: 'session-meeting-link',
        copetin: t('session.detail.link'),
        title: session.meetingLink || '',
        icon: IconLink,
        action: {
          Icon: IconExternalLink,
          onClick: () =>
            window.open(session.meetingLink!, '_blank', 'noopener,noreferrer'),
        },
        enabled: !!session.meetingLink,
      },

      {
        id: 'session-address',
        copetin: t('session.detail.location'),
        title: session.address || '',
        icon: IconMapPin,
        enabled: !!session.address,
      },
      {
        id: 'session-instructor',
        copetin: t('session.detail.instructor'),
        title: session.collaborator || '',
        icon: IconMoodSmile,
        enabled: !!session.collaborator,
      },
      {
        id: 'session-collaborator',
        copetin: t('common.colaborators.assigned'),
        title: totalAssigned?.toLocaleString(localeCode) || '',
        icon: IconUsersGroup,
      },
    ].filter(item => item.enabled ?? true);
  }, [session, totalAssigned, localeCode]);

  return (
    <Stack
      sx={{
        overflowY: 'auto',
        overflowX: 'hidden',
        overscrollBehavior: 'contain',
        maxWidth: '400px',
        flex: 1,
        minHeight: 0,
        p: 2,
        gap: 2,
        backgroundColor: ({ palette }) =>
          palette.new.background.layout.tertiary,
      }}
    >
      <Image
        src={session?.pictureUrl || defaultSessionCover}
        alt={session?.title}
        loading={isLoading}
        aspectRatio="1/1"
      />
      {isLoading && (
        <Stack sx={{ width: '100%', gap: 0.5 }}>
          <Skeleton
            width={114}
            height={16}
          />
          <Skeleton
            width="70%"
            height={24}
          />
        </Stack>
      )}
      {!isLoading && (
        <Title
          title={session?.title}
          copetin={t('session.detail.title')}
        />
      )}
      {isLoading && (
        <List>
          {Array.from({ length: 4 }).map((_, index) => (
            <ListItem
              loading={true}
              key={index}
              sx={{ '& div': { px: 0 } }}
            />
          ))}
        </List>
      )}
      {!isLoading && (
        <>
          <List>
            {items.map((item, index) => {
              const isLastItem = index === items.length - 1;
              return (
                <Stack
                  key={item.id}
                  sx={{
                    position: 'relative',
                    animation: `${slideInUp} 0.3s ease-in-out backwards`,
                    animationDelay: `${index * 0.1}s`,
                    '&:first-of-type li': { pt: 0 },
                  }}
                >
                  <Divider
                    orientation="vertical"
                    sx={{
                      height: isLastItem ? '0px' : '100%',
                      position: 'absolute',
                      zIndex: 0,
                      top: '50%',
                      left: 20,
                      borderColor: ({ palette }) =>
                        palette.border?.neutralDivider,
                    }}
                  />
                  <ListItem
                    avatar={{ Icon: item.icon, color: 'primary' }}
                    text={{ copetin: item.copetin, title: item.title }}
                    loading={isLoading}
                    action={item.action}
                    sx={{ zIndex: 20, '& li': { px: 0 } }}
                  />
                </Stack>
              );
            })}
          </List>
          <Stack
            sx={{
              animation: `${appearFromLeft} 0.4s ease-in-out backwards`,
              animationDelay: `${items.length * 0.1}s`,
              willChange: 'transform',
              contain: 'layout',
            }}
          >
            {session?.description && (
              <SeeMoreText
                buttonSx={{ p: '4px !important' }}
                text={session.description}
              />
            )}
          </Stack>
        </>
      )}
    </Stack>
  );
};
