import { observer } from 'mobx-react-lite';
import KanbanCardCss from './kanban-card.module.css';
import React from 'react';
import { ICardStore } from './store';
import { getStyleObjectFromString } from '../utils/style';
import * as TimePassedNs from '../misc-components/time-passed';
import * as TagsNs from '../misc-components/tags';
import * as IssueDetailsDialogNs from '../misc-components/issue-details-dialog';
import * as UnreadedFlagNs from '../misc-components/unreaded-flag';

export type Props = {
  store: ICardStore;
};

export type TagProps = {
  style?: string;
  tag: string;
};

export const KanbanCardTag = (props: TagProps): JSX.Element => {
  const inlineStyle = getStyleObjectFromString(props.style || '');
  return (
    <span className={KanbanCardCss.kanbanCardTag} style={inlineStyle}>
      {props.tag}
    </span>
  );
};

/**
 * Какие дальше требования к карточкам?
 *
 * 1. Отобразить как было в статичной доске
 * 2. Переделать отображение с учётом store.params
 */

export const KanbanCard = observer((props: Props) => {
  let tagsSection = <></>;
  const tagsParams = props.store.params.fields.find((field) => {
    return field.component === 'tags';
  });
  console.debug('Tag params:', tagsParams); // DEBUG
  console.debug('Issue:', props.store.issue); // DEBUG
  if (tagsParams && props.store.issue[tagsParams.path]) {
    const tags = props.store.issue[tagsParams.path] as TagProps[];
    console.debug(`Tags:`, tags); // DEBUG
    tagsSection = <TagsNs.Tags params={{ tags: tags }} />;
  }
  const timePassedParams: TimePassedNs.Params = {
    fromIssue: {
      issue: props.store.issue,
      keyName: 'timePassedClass',
    },
  };
  const unreadedStore = UnreadedFlagNs.CreateStoreFromLocalStorage(
    props.store.issue,
  );
  const detailsStore = IssueDetailsDialogNs.Store.create({
    issue: props.store.issue,
    visible: false,
    unreadedFlagStore: unreadedStore,
  });
  return (
    <div
      className={KanbanCardCss.kanbanCard}
      onClick={(e) => {
        e.stopPropagation();
        detailsStore.show();
      }}
    >
      <IssueDetailsDialogNs.IssueDetailsDialog store={detailsStore} />
      <div className={KanbanCardCss.kanbanCardTitle}>
        <UnreadedFlagNs.UnreadedFlag store={unreadedStore} />
        <TimePassedNs.TimePassed params={timePassedParams} />
        <a href={props.store.issue.url.url}>
          {props.store.issue.tracker.name} #{props.store.issue.id} -{' '}
          {props.store.issue.subject}
        </a>
      </div>
      <div>Исп.: {props.store.issue.current_user.name}</div>
      <div>Прио.: {props.store.issue.priority.name}</div>
      <div>Версия: {props.store.issue.fixed_version?.name || ''}</div>
      <div>Прогресс: {props.store.issue.done_ratio}</div>
      <div>
        Трудозатраты: {props.store.issue.total_spent_hours} /{' '}
        {props.store.issue.total_estimated_hours}
      </div>
      {tagsSection}
    </div>
  );
});

export default KanbanCard;
