import { type FC, type SyntheticEvent, useState } from 'react';

import {
  IconArrowRight,
  IconDoorEnter,
  IconDoorExit,
  IconMapPin,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Popover from '@material-hu/mui/Popover';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTitle from '@material-hu/components/design-system/Title';

import {
  type DraftEntry,
  EntrySource,
  EntryType,
  type SiteCoordinates,
  type SiteLocation,
  type TimePairs,
  type TimeTrackingEntry,
  type UserSite,
} from 'src/types/timeTracking';
import { formatToTime } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';

import { SOURCE_INFO } from '../../../../EmployeeTimesheet/utils';
import MarkingSource from '../MarkingSource';

import EditEntry from './EditEntry';

type Props = {
  data: TimeTrackingEntry | DraftEntry;
  type: EntryType;
  isEditing: boolean;
  summaryDay: string;
  reservedCycles: TimePairs[];
  pairId: string;
  enableNightShift: boolean;
  userId: number;
  userSites: UserSite[];
  onSiteClick?: (
    siteId: number | null,
    siteName: string,
    location: SiteLocation,
    markingLocation: SiteCoordinates | null,
    entrySource: EntrySource,
    entryType: EntryType,
  ) => void;
  enableRemoteWork?: boolean;
};

const formatEntryTime = (timestamp: string) =>
  formatToTime(new Date(timestamp));

const EntryDetail: FC<Props> = props => {
  const {
    data,
    isEditing,
    pairId,
    reservedCycles,
    summaryDay,
    type,
    enableNightShift,
    userId,
    userSites,
    onSiteClick,
    enableRemoteWork,
  } = props;
  const [popoverAnchor, setPopoverAnchor] = useState<HTMLDivElement | null>(
    null,
  );
  const { t } = useLokaliseTranslation('time_tracker');

  // Get site location from userSites if the entry has a siteId
  const siteData = data?.siteId
    ? userSites.find(site => site.id === data.siteId)
    : null;

  // In case a previous entry does not have source associated
  const entrySource = data?.source || EntrySource.APP;

  const hasLocation = !!data?.location;
  const isRemoteEntry = !!data?.isRemoteWork;
  const isAppWithoutLocation = entrySource === EntrySource.APP && !hasLocation;

  const getEntryLocationLabel = () => {
    if (isRemoteEntry) return t('policies.remote_work');
    if (data?.source === EntrySource.KIOSK)
      return data?.kiosk?.name || t('kiosk_terminal');
    return data?.siteName || t('no_site');
  };

  const canClickSite =
    onSiteClick &&
    (isRemoteEntry
      ? hasLocation
      : (siteData?.location && (hasLocation || isAppWithoutLocation)) ||
        (hasLocation && !siteData && entrySource === EntrySource.APP));

  // Create a minimal SiteLocation from data.location when there's no siteData
  const getLocationForMap = (): SiteLocation | null => {
    if (siteData?.location) {
      return siteData.location;
    }
    // If no site but has location, create a minimal SiteLocation
    if (data?.location) {
      return {
        latitude: data.location.latitude,
        longitude: data.location.longitude,
        tolerance: 0,
        address: '',
      };
    }
    return null;
  };

  const getSiteInfoForMap = ():
    | (Pick<UserSite, 'name' | 'location'> & {
        siteId: number | null;
      })
    | null => {
    if (isRemoteEntry && data?.location) {
      return {
        siteId: null,
        name: t('policies.remote_work'),
        location: {
          latitude: data.location.latitude,
          longitude: data.location.longitude,
          tolerance: 0,
          address: '',
        },
      };
    }
    if (siteData) {
      return {
        siteId: siteData.id,
        name: siteData.name,
        location: siteData.location,
      };
    }
    const locationForMap = getLocationForMap();
    if (locationForMap) {
      return {
        siteId: null,
        name: data?.siteName || t('no_site'),
        location: locationForMap,
      };
    }
    return null;
  };

  // Handle site click to open map
  const handleSiteClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    const siteInfo = getSiteInfoForMap();
    if (siteInfo && onSiteClick) {
      onSiteClick(
        siteInfo.siteId ?? null,
        siteInfo.name,
        siteInfo.location,
        data.location ?? null,
        entrySource,
        type,
      );
    }
  };

  const EntryTypeIcon = type === EntryType.START ? IconDoorEnter : IconDoorExit;

  if (isEditing) {
    return (
      <EditEntry
        type={type}
        reservedCycles={reservedCycles}
        pairId={pairId}
        summaryDay={summaryDay}
        kioskData={
          data?.kioskId
            ? {
                id: parseInt(data.kioskId),
                name: data.kiosk?.name || t('kiosk_terminal'),
              }
            : undefined
        }
        enableNightShift={enableNightShift}
        userId={userId}
        entryLocation={data?.location}
        entrySource={entrySource}
        enableRemoteWork={enableRemoteWork}
        onViewMap={onSiteClick}
      />
    );
  }

  return (
    <Stack sx={{ gap: 2, px: 3 }}>
      <Stack
        sx={{
          alignItems: 'center',
          flexDirection: 'row',
          gap: 1,
          mt: 1,
        }}
      >
        <HuAvatar
          Icon={EntryTypeIcon}
          color="primary"
        />
        <HuTitle
          variant="S"
          title={
            data?.time
              ? formatEntryTime(data.time)
              : t(`collab_didnt_mark_${type.toLowerCase()}`)
          }
          copetin={type === EntryType.START ? t('entry') : t('exit')}
          sx={{ flex: 1 }}
        />
        {data?.time && (
          <MarkingSource
            entrySource={entrySource}
            locationIncidence={!!data?.locationIncidence && !isRemoteEntry}
            handlePopoverOpen={event => {
              setPopoverAnchor(event.currentTarget);
            }}
          />
        )}
        {data?.time && (
          <>
            {canClickSite && (
              <Button
                variant="tertiary"
                onClick={handleSiteClick}
                endIcon={<IconArrowRight size={16} />}
                sx={{ fontSize: 14 }}
                disableRipple
              >
                {getEntryLocationLabel()}
              </Button>
            )}

            {!canClickSite && (
              <Typography variant="globalS">
                {getEntryLocationLabel()}
              </Typography>
            )}
          </>
        )}
      </Stack>
      {data?.comment && (
        <HuCardContainer
          sx={{
            backgroundColor: ({ palette }) =>
              palette.new.background.layout.default,
            border: 'none',
          }}
          fullWidth
        >
          <HuTitle
            variant="S"
            title={t(`note_${type.toLowerCase()}`)}
            description={data.comment}
          />
        </HuCardContainer>
      )}
      <Popover
        anchorEl={popoverAnchor}
        elevation={1}
        open={popoverAnchor !== null}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        onClose={(event: SyntheticEvent) => {
          event.stopPropagation();
          setPopoverAnchor(null);
        }}
        sx={{
          '.MuiPopover-paper': {
            borderRadius: ({ spacing }) => spacing(2),
            border: ({ palette }) =>
              `1px solid ${palette.new.border.neutral.default}`,
            bgcolor: ({ palette }) => palette.new.background.elements.default,
            py: 2,
            width: 360,
          },
        }}
      >
        <Stack
          sx={{ flexDirection: 'row', gap: 1, px: 2, alignItems: 'center' }}
        >
          <HuAvatar Icon={SOURCE_INFO[entrySource].icon} />
          <HuTitle
            variant="S"
            title={t('marking_source', {
              context: SOURCE_INFO[entrySource].context,
            })}
            description={t('marking_source_description', {
              context: SOURCE_INFO[entrySource].context,
            })}
          />
        </Stack>
        {data && data?.source === EntrySource.APP && (
          <>
            <Divider sx={{ borderWidth: 0.5, my: 2 }} />
            <Stack sx={{ px: 2 }}>
              <Button
                variant={data?.location ? 'secondary' : 'text'}
                endIcon={<IconArrowRight size={16} />}
                startIcon={<IconMapPin size={16} />}
                onClick={
                  canClickSite
                    ? e => {
                        handleSiteClick(e);
                        setPopoverAnchor(null);
                      }
                    : undefined
                }
                disabled={!canClickSite}
              >
                {data?.location ? t('view_map') : t('unavailable_location')}
              </Button>
            </Stack>
          </>
        )}
      </Popover>
    </Stack>
  );
};

export default EntryDetail;
