'use client'

import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import Link from '@/next/link'
import { consoleQuery } from '@/service/client'
import { SectionState } from './common'
import { AccessStatusSection, AccessStatusSectionSkeleton, ApiTokenSummarySection, ApiTokenSummarySectionSkeleton } from './overview-tab/access-status-section'
import { EnvironmentStrip, EnvironmentStripSkeleton } from './overview-tab/environment-strip'
import { ReleaseHero, ReleaseHeroSkeleton } from './overview-tab/release-hero'

const OVERVIEW_RELEASE_WINDOW = 20

function OverviewLayout({ children }: { children: React.ReactNode }) {
  return (
    <div className="flex w-full min-w-0 flex-col gap-6 px-6 py-6">
      {children}
    </div>
  )
}

function LatestReleaseSection({ appInstanceId, children }: {
  appInstanceId: string
  children: React.ReactNode
}) {
  const { t } = useTranslation('deployments')

  return (
    <section className="flex min-w-0 flex-col gap-3">
      <div className="flex min-w-0 items-baseline justify-between gap-3">
        <h3 className="system-sm-semibold text-text-primary">
          {t('overview.latestReleaseTitle')}
        </h3>
        <Link
          href={`/deployments/${appInstanceId}/releases`}
          className="inline-flex shrink-0 items-center gap-1 system-xs-medium text-text-tertiary transition-colors hover:text-text-secondary"
        >
          {t('overview.previousReleases.viewAll')}
          <span aria-hidden className="i-ri-arrow-right-line size-3.5" />
        </Link>
      </div>
      <div className="flex min-w-0 flex-col gap-3">
        {children}
      </div>
    </section>
  )
}

function OverviewLoadingSkeleton({ appInstanceId }: {
  appInstanceId: string
}) {
  return (
    <OverviewLayout>
      <div className="flex min-w-0 flex-col gap-6">
        <EnvironmentStripSkeleton />
        <LatestReleaseSection appInstanceId={appInstanceId}>
          <ReleaseHeroSkeleton />
        </LatestReleaseSection>
        <AccessStatusSectionSkeleton />
        <ApiTokenSummarySectionSkeleton />
      </div>
    </OverviewLayout>
  )
}

export function OverviewTab({ appInstanceId }: {
  appInstanceId: string
}) {
  const { t } = useTranslation('deployments')
  const input = { params: { appInstanceId } }
  const instanceQuery = useQuery(consoleQuery.enterprise.appInstanceService.getAppInstance.queryOptions({ input }))
  const runtimeInstancesQuery = useQuery(consoleQuery.enterprise.deploymentService.listEnvironmentDeployments.queryOptions({ input }))
  const releasesQuery = useQuery(consoleQuery.enterprise.releaseService.listReleases.queryOptions({
    input: {
      params: { appInstanceId },
      query: { pageNumber: 1, resultsPerPage: OVERVIEW_RELEASE_WINDOW },
    },
  }))
  const accessChannelsQuery = useQuery(consoleQuery.enterprise.accessService.getAccessChannels.queryOptions({ input }))
  const instance = instanceQuery.data?.appInstance

  if (instanceQuery.isLoading)
    return <OverviewLoadingSkeleton appInstanceId={appInstanceId} />

  if (instanceQuery.isError) {
    return (
      <OverviewLayout>
        <SectionState>{t('common.loadFailed')}</SectionState>
      </OverviewLayout>
    )
  }

  if (!instance?.id) {
    return (
      <OverviewLayout>
        <SectionState>{t('detail.notFound')}</SectionState>
      </OverviewLayout>
    )
  }

  if (releasesQuery.isLoading)
    return <OverviewLoadingSkeleton appInstanceId={appInstanceId} />

  if (releasesQuery.isError) {
    return (
      <OverviewLayout>
        <SectionState>{t('common.loadFailed')}</SectionState>
      </OverviewLayout>
    )
  }

  const releaseRows = releasesQuery.data?.data ?? []
  const releaseCount = releasesQuery.data?.pagination?.totalCount ?? releaseRows.length
  const runtimeRows = runtimeInstancesQuery.data?.data?.filter(row => row.environment?.id) ?? []
  const latestRelease = releaseRows[0]
  const accessChannels = accessChannelsQuery.data?.accessChannels

  return (
    <OverviewLayout>
      <div className="flex min-w-0 flex-col gap-6">
        <EnvironmentStrip
          appInstanceId={appInstanceId}
          rows={runtimeRows}
          releaseRows={releaseRows}
          isLoading={runtimeInstancesQuery.isLoading}
          isError={runtimeInstancesQuery.isError}
        />
        <LatestReleaseSection appInstanceId={appInstanceId}>
          <ReleaseHero
            appInstanceId={appInstanceId}
            latestRelease={latestRelease}
            releaseCount={releaseCount}
          />
        </LatestReleaseSection>
        <AccessStatusSection appInstanceId={appInstanceId} accessChannels={accessChannels} />
        <ApiTokenSummarySection
          appInstanceId={appInstanceId}
          rows={runtimeRows}
          accessChannels={accessChannels}
          isEnvironmentLoading={runtimeInstancesQuery.isLoading}
          isEnvironmentError={runtimeInstancesQuery.isError}
        />
      </div>
    </OverviewLayout>
  )
}
