import { SegmentedControl } from '@tidbcloud/uikit'
import { Tabs } from 'antd'
import { lazy, useMemo, useState } from 'react'

import {
  useGetCustomerByOrgId,
  useGetTenantByID
} from 'apiClient/services/account'
import { FormsPartnerCustomerPartnerType } from 'apiClient/services/account/interface'
import {
  useGetBillingConfigsByManagedTenant,
  useListBillingConfigs
} from 'apiClient/services/billing'
import { TenantGetTenantResp } from 'apiClient/services/devops/interface'

import { useCustomerType } from '../shared/useCustomerType'
import { useOrgType } from '../shared/useOrgType'

import { BillingPanel } from './Billing'
import { BudgetAlert } from './Billing/BudgetAlert'
import { PartnerCostExplorer } from './Billing/PartnerCostExplorer'
import { Contracts } from './Contract'
import { ManageCreditRiskLevel } from './CreditRiskLevel'
import { ManageCredits } from './Credits'
import { ManageDiscounts } from './Discount'
import { Metering } from './Metering'
import { StripePaymentMethod } from './PaymentMethod'
import { TenantQuotas } from './Quotas'
import { SupportPlan } from './SupportPlan'

const CostExplorer = lazy(() => import('./Billing/CostExplorer'))

const MSP_BILLING_CONFIG_TYPE = [
  { value: 'current_bill', label: 'Current Bills' },
  { value: 'history_bill', label: 'History Bills' }
]

const CPPO_BILLING_CONFIG_TYPE = [
  { value: 'cppo_discount_bill', label: 'Bills After Marketplace Discount' },
  { value: 'current_bill', label: 'PingCAP Listing Price Bills' },
  { value: 'history_bill', label: 'History Bills' }
]

export const BusinessInfo: React.FC<
  React.PropsWithChildren<{ tenant: TenantGetTenantResp }>
> = ({ tenant }) => {
  const { data: customer } = useGetCustomerByOrgId(tenant.id || '', {
    query: {
      retry: false,
      refetchOnWindowFocus: false
    }
  })
  const {
    isMarketResellerCustomer,
    isMSPCustomer,
    isDirectCustomer,
    isResellerCustomer
  } = useCustomerType(customer?.data)

  const [billingConfigType, setBillingConfigType] = useState(
    isMarketResellerCustomer ? 'cppo_discount_bill' : 'current_bill'
  )

  const { data: billingConfigs } = useListBillingConfigs(tenant.id || '', {
    query: { retry: false, refetchOnWindowFocus: false }
  })
  const { data: managedBillingConfig } = useGetBillingConfigsByManagedTenant(
    tenant.id || '',
    {
      query: {
        enabled: isMarketResellerCustomer,
        retry: false,
        refetchOnWindowFocus: false
      }
    }
  )

  const activeBillingConfig = useMemo(() => {
    return (billingConfigs?.data || []).find((cfg) => cfg.status === 'Active')!
  }, [billingConfigs])

  const isCPPODiscountBillSelected = billingConfigType === 'cppo_discount_bill'

  const selectedBillingConfig = useMemo(() => {
    const MSPConfig =
      (billingConfigs?.data || []).find((cfg) => cfg.type === 'MSPCustomer')! ||
      activeBillingConfig
    const CPPOConfig =
      (billingConfigs?.data || []).find(
        (cfg) => cfg.type === 'CPPOCustomer'
      )! || activeBillingConfig
    const historyConfig = (billingConfigs?.data || []).find(
      (cfg) => cfg.status === 'Closing' || cfg.status === 'Closed'
    )!

    const isCurrentBillSelected = billingConfigType === 'current_bill'
    const isHistoryBillSelected = billingConfigType === 'history_bill'

    if (isMSPCustomer) {
      return isCurrentBillSelected ? MSPConfig : historyConfig
    }
    if (isMarketResellerCustomer) {
      if (isCPPODiscountBillSelected) {
        return managedBillingConfig?.data!
      }
      if (isCurrentBillSelected) {
        return CPPOConfig
      }
      if (isHistoryBillSelected) {
        return historyConfig
      }
    }

    return activeBillingConfig
  }, [
    billingConfigs,
    billingConfigType,
    isMSPCustomer,
    isMarketResellerCustomer,
    managedBillingConfig,
    activeBillingConfig,
    isCPPODiscountBillSelected
  ])

  const { data: org } = useGetTenantByID(tenant.id || '', {
    query: {
      retry: false,
      refetchOnWindowFocus: false,
      refetchInterval: false,
      refetchIntervalInBackground: false
    }
  })
  const { isPartner } = useOrgType(org?.data, customer?.data)

  return (
    <>
      {!isDirectCustomer && (
        <SegmentedControl
          data={
            isMSPCustomer || isResellerCustomer
              ? MSP_BILLING_CONFIG_TYPE
              : CPPO_BILLING_CONFIG_TYPE
          }
          value={billingConfigType}
          onChange={setBillingConfigType}
        />
      )}
      {!activeBillingConfig || !selectedBillingConfig ? (
        <div></div>
      ) : (
        <Tabs
          // tabPosition="left"
          defaultActiveKey="invoiceAndBill"
        >
          <Tabs.TabPane tab="Invoice And Bill" key="invoiceAndBill">
            <BillingPanel
              isPartner={isPartner}
              billingConfig={selectedBillingConfig}
              key={
                selectedBillingConfig.billing_config_id +
                (selectedBillingConfig.tenant_id || '')
              }
            />
          </Tabs.TabPane>
          <Tabs.TabPane tab="Budgets" key="budgets">
            <BudgetAlert
              billingConfig={selectedBillingConfig}
              key={
                selectedBillingConfig.billing_config_id +
                (selectedBillingConfig.tenant_id || '')
              }
            />
          </Tabs.TabPane>
          {/* {isMSPCustomer && !!historyBillingConfig && (
          <Tabs.TabPane tab="History" key="history">
            <BillingPanel
              key={historyBillingConfig.billing_config_id}
              billingConfig={historyBillingConfig}
            />
          </Tabs.TabPane>
        )} */}
          <Tabs.TabPane tab="Cost Explorer" key="costExplorer">
            {isPartner ? (
              <PartnerCostExplorer
                billingConfig={selectedBillingConfig}
                key={
                  selectedBillingConfig.billing_config_id +
                  (selectedBillingConfig.tenant_id || '')
                }
              />
            ) : (
              <CostExplorer
                billingConfig={selectedBillingConfig}
                key={
                  selectedBillingConfig.billing_config_id +
                  (selectedBillingConfig.tenant_id || '')
                }
              />
            )}
          </Tabs.TabPane>
          {isResellerCustomer && (
            <>
              <Tabs.TabPane tab="Support Plan" key="supportPlan">
                <SupportPlan billingConfig={activeBillingConfig} />
              </Tabs.TabPane>
              <Tabs.TabPane tab="Credits" key="credits">
                <ManageCredits billingConfig={selectedBillingConfig} />
              </Tabs.TabPane>
            </>
          )}
          {!isMSPCustomer && !isResellerCustomer && (
            <>
              <Tabs.TabPane tab="Payment Method" key="paymentMethod">
                <StripePaymentMethod billingConfig={selectedBillingConfig} />
              </Tabs.TabPane>
              {!isCPPODiscountBillSelected && (
                <Tabs.TabPane tab="Support Plan" key="supportPlan">
                  <SupportPlan billingConfig={activeBillingConfig} />
                </Tabs.TabPane>
              )}
              <Tabs.TabPane tab="Credits" key="credits">
                <ManageCredits
                  billingConfig={selectedBillingConfig}
                  isPartner={isPartner}
                />
              </Tabs.TabPane>
              {!isCPPODiscountBillSelected && (
                <>
                  <Tabs.TabPane tab="Credit Risk Level" key="creditRiskLevel">
                    <ManageCreditRiskLevel tenant={tenant} />
                  </Tabs.TabPane>
                  <Tabs.TabPane tab="Contracts" key="contracts">
                    <Contracts billingConfig={selectedBillingConfig} />
                  </Tabs.TabPane>
                </>
              )}
              <Tabs.TabPane tab="Discounts" key="discounts">
                <ManageDiscounts
                  billingConfig={selectedBillingConfig}
                  isPartner={org?.data.org_tag === 'resale_partner'}
                />
              </Tabs.TabPane>
              {!isCPPODiscountBillSelected && (
                <Tabs.TabPane tab="Metering" key="metering">
                  <Metering />
                </Tabs.TabPane>
              )}
              <Tabs.TabPane tab="Quotas" key="quotas">
                <TenantQuotas />
              </Tabs.TabPane>
            </>
          )}
        </Tabs>
      )}
    </>
  )
}
