import { Block, ParagraphSmall, Link, useStyletron } from "@mezo-org/mezo-clay"
import React, { useCallback } from "react"
import NestedViewLayout from "../NestedViewLayout"
import InlineEditField from "./InlineEditField"
import { useGetCurrentAccount, useUpdateUserProfile } from "../../../hooks"
import { validateEmail, validateTelegram } from "../../../utils/validation"

function Settings() {
  const [, theme] = useStyletron()

  const { data: account, isPending: isCurrentAccountPending } =
    useGetCurrentAccount()
  const { updateProfileAsync } = useUpdateUserProfile()

  const handleSaveEmail = useCallback(
    async (value: string) => {
      await updateProfileAsync({ email: value || "" })
    },
    [updateProfileAsync],
  )

  const handleSaveTelegram = useCallback(
    async (value: string) => {
      const handle = value.startsWith("@") ? value.slice(1) : value
      await updateProfileAsync({ telegram: handle || "" })
    },
    [updateProfileAsync],
  )

  return (
    <NestedViewLayout>
      <ParagraphSmall
        marginTop={0}
        marginBottom={theme.sizing.scale800}
        color={theme.colors.contentSecondary}
      >
        Update your contact information to stay connected.
      </ParagraphSmall>

      <Block
        display="flex"
        flexDirection="column"
        overrides={{
          Block: {
            style: {
              gap: theme.sizing.scale600,
            },
          },
        }}
      >
        <InlineEditField
          label="Email"
          value={account?.email || ""}
          placeholder="Enter your email"
          onSave={handleSaveEmail}
          validate={validateEmail}
          isLoading={isCurrentAccountPending}
        />

        <InlineEditField
          label="Telegram"
          value={account?.telegram || ""}
          placeholder="Enter your Telegram handle"
          onSave={handleSaveTelegram}
          validate={validateTelegram}
          isLoading={isCurrentAccountPending}
        />
      </Block>

      <ParagraphSmall
        marginTop={theme.sizing.scale800}
        marginBottom={0}
        color={theme.colors.contentTertiary}
      >
        By providing your contact information, you agree to receive service
        notifications and occasional promotional messages. Promotional messages
        will always include an opt out link. The Privacy Policy is available{" "}
        <Link href="https://mezo.org/privacy" target="_blank">
          here
        </Link>
        .
      </ParagraphSmall>
    </NestedViewLayout>
  )
}

export default Settings
