import { useHistory } from 'react-router-dom'
import { useCallback, useEffect, useState } from 'react'
import {
  ChipFilterProps,
  EmailTemplateListPage,
  useToast
} from '@komi-app/creator-ui'
import { GetSystemTemplatesQuery } from '@komi-app/messaging-sdk'
import { getSystemTemplatesSDK } from 'services'
import { dcaTemplatesCreateUrl, dcaTemplatesUrl } from 'constants/dca'
import { useSystemTemplates, useSystemCategories } from './utils'
import { allCategoriesOption, blankSystemTemplate } from './config'
import { TemplateCreateRouteState } from '../TemplateBuilderPage/TemplateBuilderPage'

const SystemTemplates: React.FC = () => {
  const [filters, setFilters] = useState<GetSystemTemplatesQuery>({})
  const [categories, setCategories] = useState<ChipFilterProps[]>([])

  const systemTemplates = useSystemTemplates(filters)
  const { systemCategories, hasFetchedCategories } = useSystemCategories()
  const router = useHistory()
  const { createToast } = useToast()

  const handleCategoryClick = useCallback(
    (id: string) => {
      try {
        // Update selected state for categories
        setCategories(
          categories.map(category => ({
            ...category,
            selected: category.id === id
          }))
        )

        // Update filters
        if (id === allCategoriesOption.id) {
          const { category, ...rest } = filters
          setFilters(rest)
        } else {
          setFilters({ ...filters, category: id })
        }
      } catch (error) {
        createToast({
          semantic: 'error',
          text: 'We couldn’t load goals. Try again.',
          dismissible: true
        })
      }
    },
    [categories, filters]
  )

  const handleTemplateSelect = useCallback(async (templateId: string) => {
    try {
      const redirectState: TemplateCreateRouteState = {}

      if (templateId !== blankSystemTemplate.id) {
        const { template } =
          await getSystemTemplatesSDK().getSystemTemplate(templateId)
        redirectState.selectedTemplate = template.json
      }

      router.push(dcaTemplatesCreateUrl, redirectState)
    } catch (error) {
      createToast({
        semantic: 'error',
        text: 'We couldn’t load the selected template. Try again.',
        dismissible: true
      })
    }
  }, [])

  useEffect(() => {
    setCategories(systemCategories)
  }, [hasFetchedCategories])

  return (
    <>
      <EmailTemplateListPage
        isPageLoading={!categories.length || !systemTemplates.length}
        previousPageURL={dcaTemplatesUrl}
        templateCategories={categories}
        templates={systemTemplates}
        onCategoryClick={handleCategoryClick}
        onTemplateSelect={handleTemplateSelect}
      />
    </>
  )
}

export default SystemTemplates
