import { Button, Group, Modal, Stack, Typography } from '@tidbcloud/uikit'
import { MRT_ColumnDef, ProTable } from '@tidbcloud/uikit/biz'
import { IconPlus, IconRefreshCw01 } from '@tidbcloud/uikit/icons'
import { useMemo, useState } from 'react'
import { Link } from 'react-router-dom'

import {
  cloudConfigControllerListConfigurationTemplateChange,
  cloudConfigControllerListTemplates
} from 'apiClient/services/devops'
import {
  CloudconfigClusterType,
  CloudconfigConfigurationChange,
  CloudconfigTemplate,
  CloudconfigTemplateType
} from 'apiClient/services/devops/interface'
import { useTable } from 'components/Table'
import TemplateView from 'pages/ConfigCenter/Template/components/TemplateView'
import { toLocal } from 'pages/Devops/Maintenance/Detail'

import CreateTenantDefaultTemplateForm from './Form/CreateTenantDefaultTemplate'

export default function TenantDefaultTemplateList({
  org_id,
  cluster_type
}: {
  org_id: string
  cluster_type: CloudconfigClusterType
}) {
  const [openCreateModal, setOpenCreateModal] = useState<boolean>(false)
  const [viewTemplate, setViewTemplate] = useState<CloudconfigTemplate>()

  const fetchData = () =>
    cloudConfigControllerListTemplates({
      cluster_type: cluster_type,
      tenant_id: org_id,
      template_type: CloudconfigTemplateType.tenant_default
    })

  const fetchHistory = (params?: Partial<PageInfo>) =>
    cloudConfigControllerListConfigurationTemplateChange({
      cluster_type: cluster_type,
      page: params?.page,
      per_page: params?.pageSize,
      template_type: CloudconfigTemplateType.tenant_default,
      tenant_id: org_id
    })

  const {
    dataSource: templateData,
    loading: templateLoading,
    reload: templateReload
  } = useTable<ListData<CloudconfigTemplate>>(fetchData, [], {
    pagination: false
  })

  const {
    dataSource: historyData,
    loading: historyLoading,
    reload: historyReload
  } = useTable<ListData<CloudconfigConfigurationChange>>(fetchHistory, [], {
    pagination: false
  })

  const columns = useMemo<MRT_ColumnDef<CloudconfigTemplate>[]>(
    () => [
      {
        accessorFn: (record) => record.id || '-',
        header: 'ID',
        id: 'id',
        size: 120
      },
      {
        accessorFn: (record) => record.name || '-',
        header: 'Name',
        id: 'name',
        size: 260
      },
      {
        accessorFn: (record) => record.config_type || '-',
        header: 'Config Type',
        id: 'config_type',
        size: 180
      },
      {
        Cell: ({ row }) => (
          <Group gap="xs" wrap="nowrap">
            <Button
              size="xs"
              variant="subtle"
              onClick={() => {
                setViewTemplate(row.original)
              }}
            >
              View
            </Button>
            <Button
              component={Link}
              size="xs"
              target="_blank"
              to={`/template/${row.original.id}?cluster_type=${row.original.cluster_type}`}
              variant="subtle"
            >
              Detail
            </Button>
          </Group>
        ),
        header: 'Action',
        id: 'action',
        size: 160
      }
    ],
    []
  )

  const historyColumns = useMemo<
    MRT_ColumnDef<CloudconfigConfigurationChange>[]
  >(
    () => [
      {
        accessorFn: (record) => record.id || '-',
        header: 'ID',
        id: 'id',
        size: 120
      },
      {
        accessorFn: (record) => record.applicant || '-',
        header: 'Applicant',
        id: 'applicant',
        size: 180
      },
      {
        accessorFn: (record) => toLocal(record.created_at),
        header: 'Time',
        id: 'time',
        size: 220
      },
      {
        accessorFn: (record) => record.phase || '-',
        header: 'Phase',
        id: 'phase',
        size: 160
      },
      {
        Cell: ({ row }) => (
          <Button
            component={Link}
            size="xs"
            to={`/confighistories/${row.original.id}`}
            variant="subtle"
          >
            Detail
          </Button>
        ),
        header: 'Action',
        id: 'action',
        size: 100
      }
    ],
    []
  )

  const handleReload = async () => {
    await Promise.all([templateReload(), historyReload()])
  }

  const handleCreateSuccess = () => {
    setOpenCreateModal(false)
    void handleReload()
  }

  return (
    <>
      <Stack gap="lg">
        <Group justify="flex-end" gap="sm">
          <Button
            leftSection={<IconPlus size={16} />}
            onClick={() => setOpenCreateModal(true)}
          >
            Create
          </Button>
          <Button
            leftSection={<IconRefreshCw01 size={16} />}
            onClick={handleReload}
            variant="default"
          >
            Reload
          </Button>
        </Group>

        <Stack gap="sm">
          <Typography variant="title-md">Templates</Typography>
          <ProTable<CloudconfigTemplate>
            columns={columns}
            data={templateData || []}
            enableColumnActions={false}
            enableColumnFilters={false}
            enableDensityToggle={false}
            enableFullScreenToggle={false}
            enableHiding={false}
            enablePagination={false}
            enableSorting={false}
            enableTopToolbar={false}
            getRowId={(row, rowIndex) =>
              row.id?.toString() || rowIndex.toString()
            }
            loading={templateLoading}
          />
        </Stack>

        <Stack gap="sm">
          <Typography variant="title-md">History</Typography>
          <ProTable<CloudconfigConfigurationChange>
            columns={historyColumns}
            data={historyData || []}
            enableColumnActions={false}
            enableColumnFilters={false}
            enableDensityToggle={false}
            enableFullScreenToggle={false}
            enableHiding={false}
            enablePagination={false}
            enableSorting={false}
            enableTopToolbar={false}
            getRowId={(row, rowIndex) =>
              row.id?.toString() || rowIndex.toString()
            }
            loading={historyLoading}
          />
        </Stack>
      </Stack>

      <Modal
        centered
        closeOnClickOutside={false}
        opened={openCreateModal}
        onClose={() => setOpenCreateModal(false)}
        size={800}
        title="Create Tenant Default Template"
        trapFocus={false}
      >
        {openCreateModal ? (
          <CreateTenantDefaultTemplateForm
            org_id={org_id}
            cluster_type={cluster_type}
            onSuccess={handleCreateSuccess}
            onCancel={() => setOpenCreateModal(false)}
          />
        ) : null}
      </Modal>

      <Modal
        centered
        opened={viewTemplate !== undefined}
        onClose={() => {
          setViewTemplate(undefined)
        }}
        size={800}
        title="View Template"
        trapFocus={false}
      >
        {viewTemplate ? (
          <TemplateView
            template_id={viewTemplate.id?.toString()!}
            cluster_type={viewTemplate.cluster_type!}
            with_default_cases={false}
          />
        ) : null}
      </Modal>
    </>
  )
}
