// resources\assets\ts\share\aufgaben-shared\components\Card.tsx
// originally from: resources\assets\ts\DataPage\Card.tsx
// also used by: resources\assets\ts\ContactsPage\components\AufgabenTab\AufgabenTab.tsx

import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import Typography from '@mui/material/Typography';
import { Datetime } from '@Format';
import {
  TimeType,
  setOpen as openEditTimedialog,
} from '../../../DataPage/editTimeDialogSlice';
import { useDispatch } from 'react-redux';
import React, { useState } from 'react';
import '../../../DataPage/styles.css';
import { Trans, t } from '@lingui/macro';
import { i18n } from '@lingui/core';
const TimeTrackerEditWrapper = ({
  timeType,
  datetime,
  ergID,
  children,
}: {
  timeType: TimeType;
  datetime: string;
  ergID: number;
  children: React.ReactNode;
}) => {
  const d = useDispatch();
  const handleOpenTimeTracker = () => {
    d(
      openEditTimedialog({
        timeType,
        datetime,
        ergID,
      }),
    );
  };

  return (
    <Box style={{ cursor: 'pointer' }} onClick={handleOpenTimeTracker}>
      {children}
    </Box>
  );
};

const TimeView = ({
  timeType,
  isTimeTracker,
  time,
  ergID,
}: {
  timeType: TimeType;
  isTimeTracker: boolean;
  time: string;
  ergID: number;
}) => {
  let timeView;
  if (timeType === 'starttime') {
    timeView = <KeyValueContainer k='' v={<Datetime datetime={time} />} />;
  }
  if (timeType === 'endtime') {
    timeView = <KeyValueContainer k='' v={<Datetime datetime={time} />} />;
  }

  if (isTimeTracker === false) {
    return timeView;
  }

  return (
    <TimeTrackerEditWrapper timeType={timeType} datetime={time} ergID={ergID}>
      {timeView}
    </TimeTrackerEditWrapper>
  );
};

const KeyValueContainer = ({ k, v }) => (
  <Box display='flex' flexWrap='wrap' mr={1}>
    <Box>{k}</Box>
    <Box>
      <div className='value-text'>{v}</div>
    </Box>
  </Box>
);

const taskIconMap = {
  report: '/icon8/MLD/mld24.svg',
  disorder: '/icon8/STR/str24.svg',
  order: '/icon8/BST/bst28.svg',
  task: '/icon8/dyn/dyn25.svg',
  comment: '/icon8/bem/bem24.svg',
  maintenance: '/icon8/wtg/wtg24.svg',
  measurement: '/icon8/mwt/mwt24.svg',
  counter: '/icon8/VBG/vbg24.svg',
  complete: '/images/ok24.png',
  complaint: '/icon8/bsw/bsw24.svg',
  function: '/icon8/rgw24.png',
};

const toIconMap = {
  MLD: 'report',
  MLDi: 'report',
  STR: 'disorder',
  STRi: 'disorder',
  BST: 'order',
  BSTi: 'order',
  DYN: 'task',
  DYNi: 'task',
  BEM: 'comment',
  BEMi: 'comment',
  WTG: 'maintenance',
  WTGi: 'maintenance',
  MWT: 'measurement',
  MWTi: 'measurement',
  VBG: 'counter',
  VBGi: 'counter',
  BSW: 'complaint',
  BSWi: 'complaint',
  RWG: 'function',
  RWGi: 'function',
};

interface CardProps {
  index: number;
  comment: string;
  createdBy: string;
  currentTaskName: string;
  startTime: string;
  completeTime: string;
  taskID: number;
  taskName: string;
  taskType: string;
  taskColor: string;
  dueDate?: string;
  taskPathArr: string[];

  handleEdit(): any;

  controlView: any;
  aud_count: number;
  canEdit: boolean;
  isComplete: boolean;
  isBlocked: boolean;
  isUpcoming: boolean;
  isPlanned: boolean;
  commentCount: number;
  pointCount: number;
  pictureCount: number;
  markAsRead: () => void;
  toggleRead: () => void;
  handleIDClick(e): any;
  handleCommentToggle: (ergID: number) => () => Promise<void>;
  handlePointToggle: (ergID: number) => () => Promise<void>;
  handlePictureToggle: (ergID: number) => () => Promise<void>;

  commentView: any;
  tableView: any;
  picView: any;

  isShowOriginal: boolean;
  handleShowOriginalClick(e): any;

  isTimeTracker: boolean;
  isRead: boolean;
}
export default function Card({
  index,
  comment,
  createdBy,
  currentTaskName,
  startTime,
  completeTime,
  dueDate,
  taskID,
  taskColor,
  taskName,
  taskType,
  handleEdit,
  controlView,
  aud_count,
  canEdit,
  isComplete,
  isUpcoming,
  isBlocked,
  commentCount,
  pointCount,
  pictureCount,
  markAsRead,
  toggleRead,
  handleIDClick,
  handleCommentToggle,
  handlePointToggle,
  handlePictureToggle,

  taskPathArr,

  commentView,
  tableView,
  picView,

  isShowOriginal,
  handleShowOriginalClick,
  isPlanned,
  isTimeTracker,
  isRead,
}: CardProps) {
  const iconUrl = isComplete
    ? taskIconMap.complete
    : taskIconMap[toIconMap[taskType]];

  const [isCommentVisible, setIsCommentVisible] = useState(false);
  const [isPointVisible, setIsPointVisible] = useState(false);
  const [isPictureVisible, setIsPictureVisible] = useState(false);

  const toggleComment = async (e: React.MouseEvent) => {
    e.stopPropagation();

    const nextState = !isCommentVisible;

    setIsCommentVisible(nextState);

    try {
      await handleCommentToggle(taskID)();
      console.log(
        nextState ? 'Comments fetched' : 'Comments hidden',
        `for taskID: ${taskID}`,
      );
    } catch (error) {
      console.error('Error toggling comments:', error);
    }
  };

  const togglePoint = async (e: React.MouseEvent) => {
    e.stopPropagation();

    const nextState = !isPointVisible;

    setIsPointVisible(nextState);

    try {
      await handlePointToggle(taskID)();
      console.log(
        nextState ? 'Points fetched' : 'Points hidden',
        `for taskID: ${taskID}`,
      );
    } catch (error) {
      console.error('Error toggling points:', error);
    }
  };

  const togglePicture = async (e: React.MouseEvent) => {
    e.stopPropagation();

    const nextState = !isPictureVisible;

    setIsPictureVisible(nextState);

    try {
      await handlePictureToggle(taskID)();
      console.log(
        nextState ? 'Pictures fetched' : 'Pictures hidden',
        `for taskID: ${taskID}`,
      );
    } catch (error) {
      console.error('Error toggling pictures:', error);
    }
  };

  const toggleAll = async (e: React.MouseEvent) => {
    e.stopPropagation();

    const shouldExpand = !(
      isCommentVisible &&
      isPointVisible &&
      isPictureVisible
    );

    if (!isCommentVisible && shouldExpand) {
      setIsCommentVisible(true);
      await handleCommentToggle(taskID)();
    } else if (isCommentVisible && !shouldExpand) {
      setIsCommentVisible(false);
      await handleCommentToggle(taskID)();
    }

    if (!isPointVisible && shouldExpand) {
      setIsPointVisible(true);
      await handlePointToggle(taskID)();
    } else if (isPointVisible && !shouldExpand) {
      setIsPointVisible(false);
      await handlePointToggle(taskID)();
    }

    if (!isPictureVisible && shouldExpand) {
      setIsPictureVisible(true);
      await handlePictureToggle(taskID)();
    } else if (isPictureVisible && !shouldExpand) {
      setIsPictureVisible(false);
      await handlePictureToggle(taskID)();
    }
  };

  const pathView = taskPathArr.join('/');
  const toggleReadButton = (
    <Box
      ml={2}
      onClick={toggleRead}
      style={{
        width: '16px',
        height: '16px',
        borderRadius: '50%',
        cursor: 'pointer',
        alignSelf: 'center',
        backgroundColor: !isRead ? '#0099FF' : '#FFFFFF',
        border: '1px solid #ccc',

        transition: 'background-color 0.2s ease',
      }}
      title={isRead ? i18n._(t`markAsUnread`) : i18n._(t`markAsRead`)}
    />
  );

  const isReadColor = isRead ? undefined : '#E7E9ED';
  return (
    <>
      <Paper
        elevation={0}
        variant='outlined'
        sx={{ padding: '0 !important' }} //need important to prevent theme.ts padding override
        style={{ marginBottom: '20px', borderRadius: '10px' }}
      >
        <Box display='flex'>
          <div
            className='task-color-bar'
            style={{ backgroundColor: taskColor }}
          ></div>

          <Box
            className='card-content'
            style={{ backgroundColor: isReadColor }}
          >
            <Box className='card-padding'>
              <Grid container alignItems='stretch' className='grid-container'>
                <Grid size={4}>
                  <Box className='task-header'>
                    <img className='task-icon' src={iconUrl} alt={taskType} />
                    <Box className='task-header-text'>
                      <Typography>
                        <span className='task-name'>{currentTaskName}</span>
                      </Typography>
                    </Box>
                  </Box>
                </Grid>

                <Grid size={2}>
                  <KeyValueContainer
                    k={
                      <Box className='key-value-box'>
                        <span className='key-text'>
                          <Trans>Task</Trans>
                        </span>
                        <span className='value-text blue-text'>{taskName}</span>
                      </Box>
                    }
                    v={null}
                  />
                </Grid>

                <Grid size="grow">
                  <KeyValueContainer
                    k={
                      <Box className='key-value-box'>
                        <span className='key-text'>
                          <Trans>Done by</Trans>
                        </span>
                        <span className='value-text'>{createdBy}</span>
                      </Box>
                    }
                    v={null}
                  />
                </Grid>

                <Grid size="grow">
                  <Box className='key-value-box'>
                    <span className='key-text'>
                      <Trans>startingtime</Trans>
                    </span>
                    <TimeView
                      timeType='starttime'
                      time={startTime}
                      ergID={taskID}
                      isTimeTracker={isTimeTracker && isComplete}
                    />
                  </Box>
                </Grid>

                {isUpcoming && (
                  <Grid size="grow">
                    <Box className='key-value-box'>
                      <span className='key-text'>
                        <Trans>Geplantesdatum</Trans>
                      </span>
                      <TimeView
                        timeType='starttime'
                        time={dueDate}
                        ergID={taskID}
                        isTimeTracker={isTimeTracker}
                      />
                    </Box>
                  </Grid>
                )}

                {isComplete && (
                  <Grid size="grow">
                    <Box className='key-value-box'>
                      <span className='key-text'>
                        <Trans>endingtime</Trans>
                      </span>
                      <TimeView
                        timeType='endtime'
                        time={completeTime}
                        ergID={taskID}
                        isTimeTracker={isTimeTracker}
                      />
                    </Box>
                  </Grid>
                )}

                <Grid size={3}>
                  <Box className='key-value-box'>
                    <span className='key-text'>
                      <Trans>department</Trans>
                    </span>
                    <span className='value-text'>{pathView}</span>
                  </Box>
                </Grid>

                <Grid size="grow" style={{ alignContent: 'center' }}>
                  <Box className='id-box' onClick={handleIDClick}>
                    <span className='value-text'># {taskID}</span>
                  </Box>
                </Grid>
              </Grid>

              <Box mt={1} display='flex' alignItems='flex-start'>
                {comment && (
                  <span
                    className='comment-text'
                    dangerouslySetInnerHTML={{ __html: comment }}
                  ></span>
                )}
              </Box>
            </Box>

            {/* controls */}
            <Divider />
            <Box display='flex' flexWrap='wrap' className='bottomPart'>
              <Box ml={2}>{controlView}</Box>
              {/* {historyIcon} */}
              <Box mr='auto'></Box>
              {isShowOriginal && (
                <div
                  onClick={handleShowOriginalClick}
                  className='button'
                  style={{ marginRight: '1rem' }}
                >
                  <img
                    src='/icon8/return_arrow.png'
                    alt='Original Symbol'
                    className='return-icon'
                  />
                  <span>
                    <Trans>original</Trans>
                  </span>
                </div>
              )}
              <div className='button-container'>
                <div
                  className={`button ${isCommentVisible ? 'active' : ''}`}
                  onClick={(e) => toggleComment(e)}
                >
                  <span>
                    <Trans>comments</Trans>
                  </span>
                </div>
                <div
                  className={`button ${isPointVisible ? 'active' : ''}`}
                  onClick={(e) => togglePoint(e)}
                >
                  <span>
                    <Trans>points</Trans>
                  </span>
                </div>
                <div
                  className={`button ${isPictureVisible ? 'active' : ''}`}
                  onClick={(e) => togglePicture(e)}
                >
                  <span>
                    <Trans>pictures</Trans>
                  </span>
                </div>
                <div
                  className={`button ${isCommentVisible && isPointVisible && isPictureVisible ? 'active' : ''}`}
                  onClick={(e) => toggleAll(e)}
                >
                  <span>
                    <Trans>all</Trans>
                  </span>
                </div>
              </div>
              {!isComplete && !isPlanned ? toggleReadButton : null}
            </Box>
          </Box>
        </Box>
      </Paper>
      <div style={{ marginLeft: '3rem', marginRight: '3rem' }}>
        {commentView}
      </div>
      <div style={{ marginLeft: '3rem', marginRight: '3rem' }}>{tableView}</div>
      <div style={{ marginLeft: '3rem', marginRight: '3rem' }}>{picView}</div>
    </>
  );
}
