import { css, cx } from "@emotion/css"
import { memo } from "react"
import { useTranslation } from "react-i18next"
import Icon from "@aet/icons/macro"
import { gql, useMutation, useQuery } from "~/generated/graphql"
import type * as types from "~/generated/graphql"
import { relativeTime } from "~/shared/relativeTime"
import { token } from "../theme"
import { useSelector } from "../store"
import { ButtonWrapper } from "~/shared/styled"

const STATISTICS_TAB_QUERY = gql<"StatisticsTabQuery">`
  query StatisticsTabQuery($id: ID!) {
    preferences {
      recordUsageData
    }
    file(id: $id) {
      createdAt
      updatedAt
      lastRequestedAt
      disabledLogging
    }
  }
`

const TOGGLE_DISABLED_LOGGING_MUTATION = gql<"ToggleDisabledLoggingMutation">`
  mutation ToggleDisabledLoggingMutation($id: ID!, $value: Boolean!) {
    toggleDisableLogging(fileId: $id, value: $value)
  }
`

const DELETE_LAST_REQUESTED_AT_MUTATION = gql<"DeleteLastRequestedAtMutation">`
  mutation DeleteLastRequestedAtMutation($id: ID!) {
    resetUsageData(fileId: $id)
  }
`

const StatisticsTab = memo<{
  fileId: string
  data: types.StatisticsTabQueryQuery
}>(props => {
  const { fileId: id, data } = props
  const { t } = useTranslation()
  const { recordUsageData } = data.preferences
  const { createdAt, updatedAt, lastRequestedAt } = data.file

  const [resume] = useMutation(TOGGLE_DISABLED_LOGGING_MUTATION, {
    refetchQueries: [STATISTICS_TAB_QUERY],
    variables: { id, value: false },
  })
  const [pause] = useMutation(TOGGLE_DISABLED_LOGGING_MUTATION, {
    refetchQueries: [STATISTICS_TAB_QUERY],
    variables: { id, value: true },
  })
  const [reset] = useMutation(DELETE_LAST_REQUESTED_AT_MUTATION, {
    variables: { id },
    refetchQueries: [STATISTICS_TAB_QUERY],
  })

  return (
    <div
      className={css`
        margin: 10px 20px;
        line-height: 1.5em;
      `}
    >
      <table
        className={css`
          border-collapse: collapse;
          th {
            text-align: left;
            font-weight: 600;
          }
          th,
          td {
            border: 1px solid ${token.border.muted};
            padding: 0.3em 0.7em;
          }
        `}
      >
        <tr>
          <th>{t("file.labelCreatedDate")}</th>
          <td>
            <time title={createdAt.toLocaleString()}>{relativeTime(createdAt)}</time>
          </td>
        </tr>
        <tr>
          <th>{t("file.labelUpdatedDate")}</th>
          <td>
            <time title={updatedAt.toLocaleString()}>{relativeTime(updatedAt)}</time>
          </td>
        </tr>
        <tr>
          <th>{t("file.labelRequestedDate")}</th>
          <td>
            <div
              className={css`
                display: flex;
                align-items: center;
              `}
            >
              {recordUsageData && (
                <ButtonWrapper
                  className={cx(
                    loggingToolIcon,
                    css`
                      margin-left: -4px;
                      margin-right: 3px;
                    `,
                  )}
                >
                  {data.file.disabledLogging ? (
                    <Icon icon="VscDebugStart" onClick={() => resume()} />
                  ) : (
                    <Icon icon="VscDebugPause" onClick={() => pause()} />
                  )}
                </ButtonWrapper>
              )}
              <time
                className={css`
                  flex: 1;
                `}
                title={lastRequestedAt?.toLocaleString()}
              >
                {lastRequestedAt ? relativeTime(lastRequestedAt) : t("never")}
              </time>
              {lastRequestedAt != null && (
                <ButtonWrapper
                  className={cx(
                    loggingToolIcon,
                    css`
                      margin-left: 8px;
                      margin-right: -3px;
                      &:hover {
                        background-color: ${token.danger.subtle};
                        color: ${token.danger.emphasis};
                        transition: 0.1s;
                      }
                    `,
                  )}
                >
                  <Icon icon="VscTrash" onClick={() => reset()} />
                </ButtonWrapper>
              )}
            </div>
          </td>
        </tr>
      </table>
    </div>
  )
})

const loggingToolIcon = css`
  border-radius: 2px;
  cursor: pointer;
  && {
    padding: 3px;
  }
  &:hover {
    background-color: ${token.accent.muted};
    color: ${token.accent.fg};
  }
`

export const Statistics = memo<ClassNameProp>(({ className }) => {
  const fileId = useSelector(state => state.activeFileId)
  const { data } = useQuery(STATISTICS_TAB_QUERY, {
    variables: { id: fileId! },
    skip: !fileId,
  })

  if (!data || !fileId) {
    return null
  }

  return (
    <div className={className}>
      <StatisticsTab fileId={fileId} data={data} />
    </div>
  )
})
