import { FC, useCallback } from "react"
import { Button, Checkbox, Image, Stack, Text } from "@mantine/core"
import { IconCloudUpload } from "@tabler/icons-react"
import { foTemplateRedactorUrl } from "@/shared/constants/front-office"
import { useFoTokenPresent } from "@/shared/hooks/useFoTokenPresent"
import { useGetLandingDetailQuery, useUpdateLandingTodoMutation } from "@/models/landings"
import { useCreateMutation, useUpdateMutation } from "@/models/megafon"

interface MegafonControlsProps {
  serviceKey: string
  landingKey: string
}

const MegafonControls: FC<MegafonControlsProps> = ({
  serviceKey,
  landingKey,
}) => {
  const { data: landing, refetch: refetchLanding } = useGetLandingDetailQuery({
    serviceKey,
    landingKey,
  })
  const [create, creationState] = useCreateMutation()
  const [update, updateState] = useUpdateMutation()
  const [updateTodo, updateTodoState] = useUpdateLandingTodoMutation()

  const canUploadLanding = useFoTokenPresent()

  const handleCreate = useCallback(() => {
    create({ serviceKey, landingKey })
  }, [create, serviceKey, landingKey])

  const handleUpdate = useCallback(() => {
    update({ serviceKey, landingKey })
  }, [update, serviceKey, landingKey])

  const handleTodoToggle = useCallback(
    async (itemId: string) => {
      if (!landing) return
      const items = landing.todoItems.map(item =>
        item.id === itemId ? { ...item, done: !item.done } : item
      )
      await updateTodo({
        serviceKey,
        landingKey,
        items,
      }).unwrap()
      await refetchLanding()
    },
    [landing, updateTodo, serviceKey, landingKey, refetchLanding]
  )

  const createErr =
    creationState.error &&
    typeof creationState.error === "object" &&
    "data" in creationState.error
      ? (creationState.error.data as
          | { message?: string; error?: string }
          | undefined)
      : undefined

  const updateErr =
    updateState.error &&
    typeof updateState.error === "object" &&
    "data" in updateState.error
      ? (updateState.error.data as
          | { message?: string; error?: string }
          | undefined)
      : undefined

  const updateMessage =
    updateErr?.message ||
    (updateErr?.error === "manifest_missing"
      ? "Нужен manifest.json в папке лендинга"
      : updateErr?.error === "no_auto_upload"
        ? "Заливка отключена в manifest (noAutoUpload)"
        : updateErr?.error === "auth_required"
          ? "Нужен вход в МегаФон или INTRA_FO_TOKEN на сервере"
          : undefined)

  const createMessage =
    createErr?.message ||
    (createErr?.error === "no_auto_upload"
      ? "Заливка отключена в manifest (noAutoUpload)"
      : createErr?.error === "auth_required"
        ? "Нужен вход в МегаФон (кнопка «Войти» в шапке), чтобы запросы к API шли с токеном в заголовке Authorization"
        : createErr?.error === "manifest_incomplete"
          ? "В manifest не хватает id, serviceId или providerId"
          : createErr?.error === "manifest_exists"
            ? "У лендинга уже есть manifest.json — удалите его вручную или используйте обновление"
            : undefined)

  if (!landing) {
    return (
      <Text size="xs" c="dimmed">
        Лендинг не найден
      </Text>
    )
  }

  return (
    <Stack gap="xs" p="sm" style={{ flexShrink: 0 }}>
      {!canUploadLanding ? (
        <Text size="xs" c="dimmed">
          Войдите в МегаФон через шапку, чтобы заливать лендинги и пользоваться
          другими действиями фронт-офиса.
        </Text>
      ) : landing.templatePackId ? (
        <>
          <Text size="xs" c="dimmed">
            ID лендинга: {landing.templatePackId}
          </Text>
          <Button
            size="xs"
            variant="light"
            component="a"
            href={foTemplateRedactorUrl(landing.templatePackId)}
            target="_blank"
            rel="noopener noreferrer"
            leftSection={
              <Image
                src="/megafon-mark.svg"
                alt=""
                w={14}
                h={14}
                style={{ flexShrink: 0 }}
              />
            }
          >
            Фронт-офис
          </Button>
          <Button
            leftSection={<IconCloudUpload size={18} />}
            loading={updateState.isLoading}
            onClick={handleUpdate}
            disabled={!landing}
          >
            Обновить лендинг в МегаФоне
          </Button>
        </>
      ) : (
        <Button
          leftSection={<IconCloudUpload size={18} />}
          loading={creationState.isLoading}
          onClick={handleCreate}
          disabled={!landing}
        >
          Залить в МегаФон
        </Button>
      )}

      <Stack gap={4} pt={4}>
        <Text size="xs" fw={600} c="dimmed">
          TODO ({landing.todoDone}/{landing.todoTotal})
        </Text>
        {(landing.todoItems || []).map(item => (
          <Checkbox
            key={item.id}
            size="xs"
            label={item.title}
            checked={item.done}
            disabled={updateTodoState.isLoading}
            onChange={() => handleTodoToggle(item.id)}
          />
        ))}
      </Stack>

      {creationState.isSuccess && (
        <Text size="xs" c="teal">
          Готово
          {creationState.data?.uploadedAssets?.length != null
            ? ` (файлов: ${creationState.data.uploadedAssets.length})`
            : ""}
          {creationState.data?.mainJs?.didUpload
            ? ` — main.js ${creationState.data.mainJs.bytes ?? "?"} байт`
            : ""}
        </Text>
      )}
      {updateState.isSuccess && (
        <Text size="xs" c="teal">
          Перезаливка выполнена
          {updateState.data?.uploadedAssets?.length != null
            ? ` (файлов: ${updateState.data.uploadedAssets.length})`
            : ""}
        </Text>
      )}
      {createMessage && (
        <Text size="xs" c="red">
          {createMessage}
        </Text>
      )}
      {updateMessage && (
        <Text size="xs" c="red">
          {updateMessage}
        </Text>
      )}
      {updateTodoState.error && (
        <Text size="xs" c="red">
          Не удалось сохранить TODO
        </Text>
      )}
    </Stack>
  )
}

export default MegafonControls
