import { Button, Card, Col, Divider, Row, Tabs, Typography } from 'antd'
import React, { useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'

import {
  FormsBindedSupportPlan,
  FormsSupportPlan,
  FormsSupportPlanInput
} from 'apiClient/api/interface'
import {
  getPublicSupportPlan,
  updatePublicSupportPlan
} from 'apiClient/services/billing'
import {
  formatMonthlyUsage,
  formatSupportPlanType,
  PlanLevels,
  SuopportPlanForm,
  SupportPlanCostType
} from 'pages/Tenants/TenantDetail/BusinessInfo/SupportPlan'

import { ARTable } from './ARTable'
import { GlobalDiscount } from './GlobalDiscount'
import { Invoices } from './Invoices'
import { Rate } from './Rate'
import { RiskLevelPanel } from './RiskLevel'

const { TabPane } = Tabs

export const SupportPlanPanel: React.FC<React.PropsWithChildren<{}>> = () => {
  const [activeTab, setActiveTab] = useState<string>(PlanLevels.BASIC)

  const [plans, setPlans] = useState<FormsSupportPlan[]>([])

  const plansMap = plans.reduce(
    (prev, next) => {
      prev[next.level || ''] = next
      return prev
    },
    {
      [PlanLevels.BASIC]: {
        level: PlanLevels.BASIC,
        type: SupportPlanCostType.FIXED_PRICE
      }
    } as Record<string, FormsBindedSupportPlan>
  )

  const fetchPlans = () => {
    getPublicSupportPlan()
      .then((resp) => {
        setPlans(resp.data)
      })
      .catch((e) => {})
  }

  const items = [
    {
      key: 'type',
      label: 'Type',
      formatter: (value: string) => {
        return formatSupportPlanType(value)
      }
    },
    {
      key: 'fixed_charge_price',
      label: 'Monthly Costs',
      formatter: (value: string | number | undefined) => {
        if (value === undefined) {
          return '-'
        }
        return `$${value}`
      }
    },
    plansMap[activeTab]?.type === SupportPlanCostType.FIXED_PRICE
      ? null
      : {
          key: 'support_price_percentage',
          label: 'Percentage of monthly usage',
          formatter: (value: string | undefined) => {
            if (value === undefined) {
              return '-'
            }
            return `${formatMonthlyUsage(value)}%`
          }
        }
  ]

  const onSubmit = async (data: FormsSupportPlanInput) => {
    await updatePublicSupportPlan(
      plansMap[activeTab].support_plan_id?.toString() || '',
      {
        ...plansMap[activeTab],
        ...data
      }
    )
    fetchPlans()
  }

  useEffect(() => {
    fetchPlans()
  }, [])

  return (
    <div>
      <Card style={{ width: '45%' }}>
        <Tabs
          defaultActiveKey={PlanLevels.BASIC}
          onChange={(tab) => setActiveTab(tab)}
        >
          {[
            PlanLevels.BASIC,
            PlanLevels.DEVELOPER,
            PlanLevels.ENTERPRISE,
            PlanLevels.PREMIUM
          ].map((pl) => {
            const currentPlan = plansMap[activeTab] || {}
            return (
              <TabPane tab={pl} key={pl}>
                {items.map((item) => {
                  if (!item) {
                    return null
                  }
                  const key = item.key as keyof FormsBindedSupportPlan
                  return (
                    <Row key={item.key}>
                      <Col flex="auto">
                        <Typography.Text>{item.label}</Typography.Text>
                      </Col>
                      <Col flex="none">
                        <Typography.Text>
                          {item.formatter
                            ? item.formatter(currentPlan[key] as string)
                            : currentPlan[key]}
                        </Typography.Text>
                      </Col>
                      <Divider />
                    </Row>
                  )
                })}
                {pl !== PlanLevels.BASIC && (
                  <Row>
                    <Col flex="auto"></Col>
                    <Col flex="none">
                      <SuopportPlanForm
                        onSubmit={onSubmit}
                        withDate={false}
                        trigger={<Button type="primary">Edit</Button>}
                        disabeld={true}
                        initValues={{
                          ...plansMap[activeTab]
                        }}
                      ></SuopportPlanForm>
                    </Col>
                  </Row>
                )}
              </TabPane>
            )
          })}
        </Tabs>
      </Card>
    </div>
  )
}

enum SettingTabs {
  INVOICES = 'Invoices',
  SUPPORT_PLAN = 'Support Plan',
  RISK_LEVEL = 'Risk Level',
  DISCOUNTS = 'Discounts',
  AR_TABLE = 'AR Table',
  RATE = 'Exchange Rate'
}

export const SettingsPanel = () => {
  const location = useLocation<{ activeTab?: string }>()
  const [activeTab, setActiveTab] = useState<string>(
    location.state?.activeTab || SettingTabs.INVOICES
  )

  useEffect(() => {
    if (location.state?.activeTab) {
      setActiveTab(location.state.activeTab)
    }
  }, [location.state])

  return (
    <Tabs activeKey={activeTab} onChange={setActiveTab}>
      <TabPane tab={SettingTabs.INVOICES} key={SettingTabs.INVOICES}>
        <Invoices />
      </TabPane>
      <TabPane tab={SettingTabs.SUPPORT_PLAN} key={SettingTabs.SUPPORT_PLAN}>
        <SupportPlanPanel />
      </TabPane>
      <TabPane tab={SettingTabs.RISK_LEVEL} key={SettingTabs.RISK_LEVEL}>
        <RiskLevelPanel />
      </TabPane>
      <TabPane tab={SettingTabs.DISCOUNTS} key={SettingTabs.DISCOUNTS}>
        <GlobalDiscount />
      </TabPane>
      <TabPane tab={SettingTabs.AR_TABLE} key={SettingTabs.AR_TABLE}>
        <ARTable />
      </TabPane>
      <TabPane tab={SettingTabs.RATE} key={SettingTabs.RATE}>
        <Rate />
      </TabPane>
    </Tabs>
  )
}
