import React from 'react';
import * as DashboardStoreNs from '../dashboard-store';
import { observer } from 'mobx-react-lite';
import { DebugInfo } from '../../misc-components/debug-info';
import { Instance, onSnapshot, types } from 'mobx-state-tree';
import { v4 as uuidv4 } from 'uuid';

export const DailyEccmV2Data = types.model({
  id: types.string,
  dashboardId: types.string,
  widgetId: types.string,
  datetime: types.number,
  datetimeFormatted: types.string,
  reportIssues: types.array(types.frozen()),
  issuesMetrics: types.frozen(),
  latest: types.boolean,
});

export const DailyEccmV2Store = types
  .model({
    data: DailyEccmV2Data,
  })
  .actions((self) => ({
    setData(data: any) {
      self.data = data;
    },
  }));

export type IDailyEccmV2Store = Instance<typeof DailyEccmV2Store>;

const SimpleCounterViewComponent = (props: {
  key?: string;
  label: string;
  count: number;
  issueIds?: number[];
  detailsLabel?: string;
  details?: Record<string, number>;
}): JSX.Element => {
  let detailsHintComponent = <></>;
  if (props.details) {
    const parentKey = props.key
      ? props.key
      : `simple-counter-component-${uuidv4()}`;
    const detailsKey = `${parentKey}-details`;
    detailsHintComponent = (
      <DetailsHintViewComponent
        key={detailsKey}
        mainLabel={props.detailsLabel ?? 'Details'}
        details={props.details}
      />
    );
  }
  return (
    <span key={props.key}>
      {props.label}: {props.count} {detailsHintComponent}
    </span>
  );
};

const DetailsHintViewComponent = (props: {
  key?: string;
  mainLabel: string;
  details: Record<string, number>;
}): JSX.Element => {
  return (
    <span key={props.key} style={{ marginLeft: '10px', color: 'lightgray' }}>
      ({props.mainLabel}: {JSON.stringify(props.details)})
    </span>
  );
};

export const DailyEccmV2 = observer(
  (props: { store: IDailyEccmV2Store }): JSX.Element => {
    const dashboardId = props.store?.data?.dashboardId;
    const widgetId = props.store?.data?.widgetId;
    const keyPrefix = `dashboard-${dashboardId}-widget-${widgetId}`;

    const issuesByStatusCount: Record<string, any> =
      props.store?.data?.issuesMetrics?.issuesByStatusCount ?? {};
    const issuesByVersionsCount: Record<string, any> =
      props.store?.data?.issuesMetrics?.issuesByVersionsCount ?? {};
    const issuesByUsername: Record<string, any> =
      props.store?.data?.issuesMetrics?.issuesByUsername ?? {};

    const byStatusLi: JSX.Element[] = [];

    Object.keys(issuesByStatusCount).forEach((statusName) => {
      const byStatusData = issuesByStatusCount[statusName];
      const keyPrefixForCurrentStatusBlock = `${keyPrefix}-issuesByStatusCount-${statusName}`;
      byStatusLi.push(
        <li key={`${keyPrefixForCurrentStatusBlock}-li`}>
          <SimpleCounterViewComponent
            key={`${keyPrefixForCurrentStatusBlock}`}
            label={statusName}
            count={byStatusData.count}
            issueIds={byStatusData.issueIds}
            details={byStatusData.byVersion}
            detailsLabel="Версии"
          />
        </li>,
      );
    });

    const byVersionsLi: JSX.Element[] = [];

    Object.keys(issuesByVersionsCount).forEach((versionName) => {
      const byVersionData = issuesByVersionsCount[versionName];
      const keyPrefixForCurrentVersionBlock = `${keyPrefix}-issuesByVersionCount-${versionName}`;
      byVersionsLi.push(
        <li key={`${keyPrefixForCurrentVersionBlock}-li`}>
          <SimpleCounterViewComponent
            key={keyPrefixForCurrentVersionBlock}
            label={versionName}
            count={byVersionData.count}
            issueIds={byVersionData.issueIds}
            details={byVersionData.byStatus}
            detailsLabel="Статусы"
          />
        </li>,
      );
    });

    const byUsersLi: JSX.Element[] = [];

    Object.keys(issuesByUsername).forEach((username) => {
      const byUserNameData = issuesByUsername[username];
      const keyPrefixForCurrentUserBlock = `${keyPrefix}-issuesByUsername-${username}`;
      byUsersLi.push(
        <li key={`${keyPrefixForCurrentUserBlock}-li`}>
          <SimpleCounterViewComponent
            key={keyPrefixForCurrentUserBlock}
            label={username}
            count={byUserNameData.count}
            issueIds={byUserNameData.issueIds}
          />
        </li>,
      );
    });

    return (
      <div>
        <h1>Daily ECCM V2</h1>
        <p>Дата выгрузки: {props.store?.data?.datetimeFormatted}</p>
        <p>Метрики:</p>
        <ul>
          <li>
            Простые счётчики:
            <ul>
              <li>
                По статусам:
                <ul>{byStatusLi}</ul>
              </li>
              <li>
                По версиям:
                <ul>{byVersionsLi}</ul>
              </li>
              <li>
                По работникам:
                <ul>{byUsersLi}</ul>
              </li>
            </ul>
          </li>
        </ul>
        <DebugInfo value={JSON.stringify(props.store?.data, null, 2)} />
      </div>
    );
  },
);

export type Props = {
  store: DashboardStoreNs.IWidget;
};

export const DailyEccmV2Widget = observer((props: Props): JSX.Element => {
  const dailyEccmV2Store = DailyEccmV2Store.create();
  onSnapshot(props.store, (storeState) => {
    if (storeState.data) {
      dailyEccmV2Store.setData(storeState.data);
    }
  });
  return (
    <>
      <DailyEccmV2 store={dailyEccmV2Store} />
    </>
  );
});
