import { PageProps, Link, graphql } from 'gatsby'
import React, { useState } from 'react'

import Layout from '../components/layout'
import Seo from '../components/seo'

import { Section } from '../components/shared'
import {
  SectionHeading,
  SectionDesc,
  SolidButton
} from '../components/shared/styledComponents'

import {
  StyledHeading,
  StyledLabel,
  ContactBackground
} from '../styledComponents/contact'

import contactBg from '../images/contact_bg.jpg'

import '../styledComponents/contact.css'
import { NostrController } from '../controllers'

type DataProps = {
  site: {
    meta: {
      title: string
      description: string
      social: { linkedin: string }
    }
  }
}

const Contact: React.FC<PageProps<DataProps>> = ({ data, location }) => {
  const nostrController = NostrController.getInstance()

  const [name, setName] = useState<string>()
  const [email, setEmail] = useState<string>()
  const [emailError, setEmailError] = useState<boolean>(false)
  const [subject, setSubject] = useState<string>()
  const [message, setMessage] = useState<string>()
  const [notification, setNotification] = useState<string>()

  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setEmail(value)

    if (
      value &&
      (value.toLowerCase().includes('@gmail.com') ||
        value.toLowerCase().includes('@googlemail.com'))
    ) {
      setEmailError(true)
      setNotification('Gmail addresses are not allowed.')
    } else {
      setEmailError(false)
      setNotification(undefined)
    }
  }

  const getBorderStyle = (value: string | undefined) =>
    value === undefined ? {} : value ? {} : { border: '1px solid red' }

  return (
    <Layout
      location={location}
      heading="Book a Demo"
      desc="Schedule a demonstration of the Data Controller to see our latest features and explore use cases"
    >
      <Seo title="Contact" />
      <Section color="black" bgColor="white" bottomArrow={false}>
        <div className="row">
          <div className="col-md-6">
            <SectionHeading center="no">Schedule a Call</SectionHeading>
            <SectionDesc center="no">
              Feel free to contact us at any time to book a demo and start your
              Data Controller journey. Our team will respond within 24 hours and
              help you proceed with the registration process.
            </SectionDesc>
            <StyledHeading>Contact Us</StyledHeading>

            <form
              onSubmit={async (evt) => {
                evt.preventDefault()

                // Prevent sending if emailError is set
                if (emailError) {
                  return
                }

                if (name && email && subject && message) {
                  const res = await nostrController
                    .sendDM(
                      'npub1dc0000002dtkw7et06sztc9nvk79r6yju8gk69sr88rgrg0e8cvsnptgyv',
                      `Name: ${name}
Email: ${email}
Subject: ${subject}
Message: ${message}`
                    )
                    .catch((err) => {
                      setNotification(
                        `Something went wrong. Please check the console for more information. Please try one more time.`
                      )

                      console.log(`Sending message error: `, err)
                    })

                  if (res && res.length) {
                    setNotification(`Message sent. We'll contact you shortly.`)
                  } else {
                    setNotification(
                      `Something went wrong. Please try one more time.`
                    )
                  }
                }
              }}
            >
              <div className="mb-3">
                <StyledLabel htmlFor="name" className="form-label">
                  Name
                </StyledLabel>
                <input
                  type="text"
                  className="form-control contactFormStyles"
                  id="name"
                  name="name"
                  rules="required|max:50"
                  onChange={(evt) => {
                    setName(evt.target.value)
                    setNotification(undefined)
                  }}
                  style={getBorderStyle(name)}
                />
              </div>
              <div className="mb-3">
                <StyledLabel htmlFor="email" className="form-label">
                  Email address
                </StyledLabel>
                <input
                  type="email"
                  className="form-control contactFormStyles"
                  id="email"
                  name="email"
                  rules="required|email"
                  aria-describedby="emailHelp"
                  onChange={handleEmailChange}
                  style={getBorderStyle(email)}
                />
                <div id="emailHelp" className="form-text">
                  We'll never share your email with anyone else.
                </div>
              </div>
              <div className="mb-3">
                <StyledLabel htmlFor="subject" className="form-label">
                  Subject
                </StyledLabel>
                <input
                  type="text"
                  className="form-control contactFormStyles"
                  id="subject"
                  name="subject"
                  rules="required|max:50"
                  onChange={(evt) => {
                    setSubject(evt.target.value)
                    setNotification(undefined)
                  }}
                  style={getBorderStyle(subject)}
                />
              </div>
              <div className="mb-3">
                <StyledLabel htmlFor="mesage" className="form-label">
                  Message
                </StyledLabel>
                <textarea
                  className="form-control contactFormStyles"
                  id="mesage"
                  name="message"
                  rows="5"
                  rules="required|max:200"
                  onChange={(evt) => {
                    setMessage(evt.target.value)
                    setNotification(undefined)
                  }}
                  style={getBorderStyle(message)}
                ></textarea>
              </div>
              <div className="mb-3">
                <SolidButton theme="dark">Submit</SolidButton>
              </div>
            </form>
            {notification && <span>{notification}</span>}
          </div>
          <div className="col-md-6">
            <ContactBackground src={contactBg} info="Book a Demo" />
          </div>
        </div>
      </Section>
    </Layout>
  )
}

export default Contact
