import { Group, SegmentedControl } from '@tidbcloud/uikit'
import { useSessionStorageState } from 'ahooks'
import { Alert, Card, Divider, Menu, MenuProps, Layout } from 'antd'
import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'

import { useGetTenant } from 'apiClient/services/devops'
import {
  OperationOperationTarget,
  CloudconfigClusterType
} from 'apiClient/services/devops/interface'
import Issues from 'pages/AIOps/Issues'

import Operations from '../../Devops/Operations/Operations'
import { ClusterInfo } from '../TenantClusters'

import { AuditLog } from './AuditLog'
import { BasicInfo } from './BasicInfo'
import { BusinessInfo } from './BusinessInfo'
import PremiumReservedCapacity from './PremiumReservedCapacity'
import { Projects } from './Projects'
import { TechnicalInfo } from './TechnicalInfo'
import MetaProfile from './TenantDefaultTemplate/MetaProfile'
import TenantDefaultTemplateBinding from './TenantDefaultTemplate/TenantDefaultTemplateBinding'
import TenantDefaultTemplateList from './TenantDefaultTemplate/TenantDefaultTemplateList'
import TenantInitConfig from './TenantInitConfig'
import { TenantUsers } from './Users'

export default function TenantDetail() {
  const params = new URLSearchParams(window.location.search)
  const name = params.get('name') || ''
  const [, setTenantName] = useSessionStorageState('tenant_name', {
    defaultValue: name
  })
  const [activeTabKey, setActiveTabKey] = useState<string>('clusters')

  useEffect(() => {
    setTenantName(name)

    return () => {
      setTenantName('')
    }
  }, [name, setTenantName])

  const { org_id } = useParams<{ org_id: string }>()
  const { data } = useGetTenant(org_id, {
    query: { refetchOnWindowFocus: false, refetchInterval: false }
  })
  if (!data) {
    return null
  }

  const onTabChange = (key: string) => {
    setActiveTabKey(key)
  }
  const tabList = [
    {
      key: 'projects',
      tab: 'Projects'
    },
    {
      key: 'users',
      tab: 'Users'
    },
    {
      key: 'clusters',
      tab: 'Clusters'
    },
    {
      key: 'businessInfo',
      tab: 'Business Info'
    },
    {
      key: 'technicalInfo',
      tab: 'Technical Info'
    },
    {
      key: 'operationInfo',
      tab: 'Operation History'
    },
    {
      key: 'configuration',
      tab: 'Template & Initial Configs'
    },
    {
      key: 'premium_reserved_capacity',
      tab: 'Premium Reserved Capacity'
    },
    {
      key: 'console_audit',
      tab: 'Console Audit Logs'
    },
    {
      key: 'jira_tickets',
      tab: 'Jira Tickets'
    }
  ]
  const contentList: Record<string, React.ReactNode> = {
    projects: <Projects orgId={org_id} />,
    users: (
      <TenantUsers
        orgId={org_id}
        orgName={data?.data.alias || data?.data.name || ''}
      />
    ),
    clusters: <ClusterInfo />,
    businessInfo: <BusinessInfo tenant={data.data} />,
    technicalInfo: <TechnicalInfo />,
    operationInfo: (
      <Operations
        target_type={OperationOperationTarget.tenant}
        target_id={org_id}
      />
    ),
    configuration: <TenantConfiguration org_id={org_id} />,
    premium_reserved_capacity: <PremiumReservedCapacity orgId={org_id} />,
    console_audit: <AuditLog tenant={data.data} />,
    jira_tickets: <Issues preDefinedSearchParam={{ tenant_id_in: [org_id] }} />
  }

  return (
    <>
      <BasicInfo tenant={data.data} />
      <Divider />
      <Card
        tabList={tabList}
        tabProps={{ size: 'middle' }}
        bordered={false}
        activeTabKey={activeTabKey}
        onTabChange={(key) => {
          onTabChange(key)
        }}
      >
        {contentList[activeTabKey]}
      </Card>
    </>
  )
}

const TenantConfiguration = ({ org_id }: { org_id: string }) => {
  const [selectedType, setSelectedType] = useState<CloudconfigClusterType>(
    CloudconfigClusterType.DEDICATED_TIDB
  )
  const [activeMenuKey, setActiveMenuKey] = useState<string>('initial_configs')

  const segmentedData = [
    { value: CloudconfigClusterType.DEDICATED_TIDB, label: 'Dedicated' },
    { value: CloudconfigClusterType.SHARED_POOL, label: 'Resource Pool' }
  ]

  const renderContent = () => {
    const menuItems = [
      {
        key: 'initial_configs',
        label: 'Initial Configs'
      },
      {
        key: 'default_template_menu',
        label: 'Tenant Template',
        disabled:
          selectedType !== CloudconfigClusterType.DEDICATED_TIDB &&
          selectedType !== CloudconfigClusterType.SHARED_POOL
            ? true
            : false,
        children: [
          {
            key: 'tenant_templates',
            label: 'Template List'
          },
          {
            key: 'default_template_binding',
            label: 'Overwrite System',
            disabled: selectedType !== CloudconfigClusterType.DEDICATED_TIDB
          },
          {
            key: 'meta_profiles',
            label: 'Meta Profiles',
            disabled: selectedType !== CloudconfigClusterType.SHARED_POOL
          }
        ]
      }
    ]

    const menuContents: Record<string, React.ReactNode> = {
      initial_configs: (
        <div>
          <Alert
            message="These configurations will be used as initial values for user-defined configs when creating new clusters."
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <TenantInitConfig org_id={org_id} clusterType={selectedType} />
        </div>
      ),
      tenant_templates: (
        <TenantDefaultTemplateList
          org_id={org_id}
          cluster_type={selectedType}
        />
      ),
      default_template_binding: (
        <div>
          <Alert
            message="When a cluster is newly created or modified, if its state matches the rules below, these tenant templates will be used instead of the default system templates."
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />
          <TenantDefaultTemplateBinding
            org_id={org_id}
            cluster_type={selectedType}
          />
        </div>
      ),
      meta_profiles: <MetaProfile org_id={org_id} cluster_type={selectedType} />
    }

    return (
      <Layout style={{ background: 'transparent' }}>
        <Layout.Sider
          theme="light"
          style={{
            background: 'transparent',
            borderRight: '1px solid #f0f0f0'
          }}
          width={200}
        >
          <Menu
            mode="inline"
            selectedKeys={[activeMenuKey]}
            onClick={({ key }) => setActiveMenuKey(key)}
            style={{ height: '100%', borderRight: 0 }}
            items={menuItems}
          />
        </Layout.Sider>
        <Layout.Content style={{ padding: '0 24px', minHeight: 280 }}>
          {menuContents[activeMenuKey]}
        </Layout.Content>
      </Layout>
    )
  }

  return (
    <>
      <Group mb={16}>
        <SegmentedControl
          data={segmentedData}
          value={selectedType}
          onChange={(val: string) => {
            setSelectedType(val as CloudconfigClusterType)
          }}
          py={5}
        />
      </Group>
      {renderContent()}
    </>
  )
}
