import { skipToken } from "@reduxjs/toolkit/query"
import { FC, useCallback, useEffect, useMemo, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/router"
import { Box, Button, Flex, Image, Paper, Stack } from "@mantine/core"
import { foTemplateRedactorUrl } from "@/shared/constants/front-office"
import UrlHelper from "@/shared/helpers/UrlHelper"
import {
  EventLog,
  PreviewFrame,
  ServiceLandingSelectableList,
  ServiceSelectionBlock,
} from "@/features/landings"
import MainLayout from "@/ensembles/MainLayout"
import {
  useGetLandingsListQuery,
  useGetServiceListQuery,
} from "@/models/landings"

function singleQueryValue(value: string | string[] | undefined): string {
  if (Array.isArray(value)) return value[0] || ""
  return value || ""
}

const IndexView: FC = () => {
  const router = useRouter()
  const { data: services = [] } = useGetServiceListQuery()

  const [activeServiceKey, setActiveServiceKey] = useState<string | undefined>()

  const { data: landings = [] } = useGetLandingsListQuery(
    activeServiceKey ? { serviceKey: activeServiceKey } : skipToken
  )

  const [selectedLandingKey, setSelectedLandingKey] = useState<
    string | undefined
  >()

  useEffect(() => {
    if (!router.isReady) return
    const queryService = singleQueryValue(router.query.service)
    const queryLanding = singleQueryValue(router.query.landing)
    if (queryService) {
      setActiveServiceKey(prev => (prev === queryService ? prev : queryService))
    }
    if (queryService && queryLanding) {
      const path = `${queryService}/${queryLanding}`
      setSelectedLandingKey(prev => (prev === path ? prev : path))
    }
  }, [router.isReady, router.query.service, router.query.landing])

  useEffect(() => {
    if (activeServiceKey || services.length === 0) return
    setActiveServiceKey(String(services[0].key))
  }, [services, activeServiceKey])

  const syncQuery = useCallback(
    (serviceKey?: string, landingPath?: string) => {
      const nextQuery: Record<string, string> = {}
      if (serviceKey) nextQuery.service = serviceKey
      if (landingPath) {
        const slash = landingPath.indexOf("/")
        const landingKey =
          slash >= 0 ? landingPath.slice(slash + 1) : landingPath
        if (landingKey) nextQuery.landing = landingKey
      }
      void router.replace(
        { pathname: router.pathname, query: nextQuery },
        undefined,
        { shallow: true }
      )
    },
    [router]
  )

  const handleServiceSelect = useCallback(
    (serviceKey: string) => {
      setActiveServiceKey(serviceKey)
      setSelectedLandingKey(undefined)
      syncQuery(serviceKey)
    },
    [syncQuery]
  )

  const handleLandingSelect = useCallback(
    (path: string) => {
      setSelectedLandingKey(path)
      const slash = path.indexOf("/")
      const serviceKey =
        slash >= 0 ? path.slice(0, slash) : (activeServiceKey ?? "")
      if (serviceKey && serviceKey !== activeServiceKey) {
        setActiveServiceKey(serviceKey)
      }
      syncQuery(serviceKey, path)
    },
    [activeServiceKey, syncQuery]
  )

  const selectedLanding = landings.find(l => l.path === selectedLandingKey)

  const landingNav = useMemo(() => {
    if (!selectedLanding) {
      return {
        internalHref: null as string | null,
        foEditHref: null as string | null,
      }
    }
    const slash = selectedLanding.path.indexOf("/")
    const serviceKey =
      slash >= 0
        ? selectedLanding.path.slice(0, slash)
        : (activeServiceKey ?? "")
    const landingKey =
      slash >= 0 ? selectedLanding.path.slice(slash + 1) : selectedLanding.path
    const internalHref =
      serviceKey && landingKey ? UrlHelper.lp(landingKey) : null
    const foEditHref = selectedLanding.templatePackId
      ? foTemplateRedactorUrl(selectedLanding.templatePackId)
      : null
    return { internalHref, foEditHref }
  }, [selectedLanding, activeServiceKey])

  return (
    <MainLayout>
      <Flex
        direction={{ base: "column", md: "row" }}
        flex={1}
        miw={0}
        mih={0}
        style={{ overflow: "hidden" }}
      >
        <Paper
          withBorder
          p="xs"
          radius={0}
          w={{ base: "100%", md: 300 }}
          mih={{ base: 220, md: 0 }}
          style={{ flexShrink: 0 }}
        >
          <Stack gap="sm" h="100%" mih={0}>
            <ServiceSelectionBlock
              services={services}
              activeServiceKey={activeServiceKey}
              onSelect={handleServiceSelect}
            />
            <ServiceLandingSelectableList
              landings={landings}
              selectedKey={selectedLandingKey}
              onSelect={handleLandingSelect}
            />
          </Stack>
        </Paper>
        <Box
          flex={1}
          miw={0}
          mih={{ base: 280, md: 0 }}
          style={{ display: "flex", flexDirection: "column", minHeight: 0 }}
        >
          <PreviewFrame src={selectedLanding?.indexUrl || ""} />
        </Box>
        <Paper
          withBorder
          p={0}
          radius={0}
          w={{ base: "100%", md: 320 }}
          mih={{ base: 200, md: 0 }}
          style={{ flexShrink: 0 }}
        >
          {selectedLanding && (
            <Stack gap="xs" p="sm">
              {landingNav.foEditHref && (
                <Button
                  size="xs"
                  variant="light"
                  component="a"
                  href={landingNav.foEditHref}
                  target="_blank"
                  rel="noopener noreferrer"
                  leftSection={
                    <Image
                      src="/megafon-mark.svg"
                      alt=""
                      w={14}
                      h={14}
                      style={{ flexShrink: 0 }}
                    />
                  }
                >
                  Фронт-офис
                </Button>
              )}
              <Button
                size="xs"
                variant="light"
                component={Link}
                href={UrlHelper.lp(selectedLandingKey!)}
              >
                Редактирование
              </Button>
            </Stack>
          )}
          <EventLog />
        </Paper>
      </Flex>
    </MainLayout>
  )
}

export default IndexView
