import React, { useState } from "react";
import styled from "styled-components";
import jsonp from "jsonp";
import {
  Body,
  Checkbox,
  Heading,
  Input,
  Alert,
  Button,
} from "@equilab/ui-curated";
import CuratedLogo from "./curated-logo.png";
import CuratedTxt from "./curated-txt.png";
import { useFirebase } from "../../contexts/firebase";
import { useRouter } from "next/router";
import queryString from "querystring";

const InitiativesContainer = styled.div`
  display: flex;
  flex-direction: column;
  background-color: #707cb9;
  padding-bottom: 104px;
  ${({ theme }) => theme.breakpoints.up("m")} {
    padding-bottom: 64px;
  }
  & .list {
    display: flex;
    gap: 64px;
    flex-direction: column;
    ${({ theme }) => theme.breakpoints.up("m")} {
      gap: 50px;
      flex-direction: row;
      & > div {
        flex-basis: 50%;
      }
    }
  }

  & .initiativeHeading {
    margin: 24px 0px 16px 0px;
  }

  & .comingSoon {
    margin-top: 24px;
    width: 100%;
  }

  & .heading {
    ${({ theme }) => theme.breakpoints.up("m")} {
      margin: 40px 0px 48px 0px;
    }
    margin: 40px 0px 23px 0px;
  }

  & .curatedLogo {
    width: 100%;
    height: 327px;
    position: relative;
    ${({ theme }) => theme.breakpoints.up("m")} {
      width: 28vw;
      height: 28vw;
    }
    &::after {
      content: "";
      z-index: 10;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
      background-position: center;
      background-size: cover;
      background-image: url(${CuratedLogo.src});
      background-repeat: no-repeat;
    }
    &::before {
      content: "";
      z-index: 9;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
      background-position: center;
      background-size: cover;
      filter: blur(20px);
      background-repeat: no-repeat;
      background-image: url(${CuratedLogo.src});
    }
  }
  & .mailInput {
    margin-top: 24px;
  }

  & .curatedTxt {
    width: 100%;
    height: 327px;
    ${({ theme }) => theme.breakpoints.up("m")} {
      width: 28vw;
      height: 28vw;
    }
    position: relative;
    &::after {
      content: "";
      z-index: 10;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
      background-position: center;
      background-size: cover;
      background-image: url(${CuratedTxt.src});
      background-repeat: no-repeat;
    }
    &::before {
      content: "";
      z-index: 9;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
      background-position: center;
      background-size: cover;
      filter: blur(20px);
      background-repeat: no-repeat;
      background-image: url(${CuratedTxt.src});
    }
  }
`;

const Initiatives: React.FC<{ className?: string }> = ({ className }) => {
  const [alertMsg, setAlertMsg] = useState("");
  const [agreementSigned, setAgreementSigned] = useState(false);
  const [email, setEmail] = useState("");
  const router = useRouter();
  const { createRecord } = useFirebase();

  const [errors, setErrors] = useState({
    email: false,
    agreement: false,
  });

  const validateEmail = (email: string) => {
    let re = /\S+@\S+\.\S+/;
    return re.test(email);
  };

  const handleEmailSubmit = async () => {
    if (!email) {
      setAlertMsg("Enter your email");
      setErrors((prev) => ({ ...prev, email: true }));
    } else if (!validateEmail(email)) {
      setAlertMsg("Enter the correct email");
      setErrors((prev) => ({ ...prev, email: true }));
    } else if (!agreementSigned) {
      setAlertMsg("You have to agree to our policies to subscribe");
      setErrors((prev) => ({ ...prev, agreement: true }));
    } else {
      const { result } = await sendEmailToCms();
      if (result === "success") {
        setAlertMsg("Thanks for subscribing!");
      }
    }
  };

  const sendToMailchimp = () => {
    return new Promise<{ msg: string; result: "success" | "error" }>(
      (resolve, reject) => {
        jsonp(
          `https://curated.us13.list-manage.com/subscribe/post-json?u=68e5152830d2c99417012a400&amp;id=dd59d55ff3&${queryString.stringify(
            { MERGE0: email, tags: "6654249" }
          )}`,
          { param: "c" },
          (err, data) => {
            resolve(data);
            reject(err);
          }
        );
      }
    );
  };

  const sendEmailToCms = async (): Promise<{ result: "success" | "error" }> => {
    try {
      const res = await sendToMailchimp();
      if (res.result === "success") {
        if (createRecord) {
          createRecord("emails", { email, platform: "foundation" });
        }
        return { result: "success" };
      } else {
        setAlertMsg(res.msg);
        return { result: "error" };
      }
    } catch (err) {
      return { result: "error" };
    }
  };

  return (
    <InitiativesContainer className={className}>
      <Heading size="m" className="heading">
        Our ongoing initiatives
      </Heading>
      <div className="list">
        <div>
          <div className="curatedLogo" />
          <Heading size="s" className="initiativeHeading" as="div">
            Curated!
          </Heading>
          <Body as="div">
            The most awaited newsletter on the NFT art by art professionals and
            NFT geeks
          </Body>
          <Input
            value={email}
            onChange={(e) => {
              setEmail(e.target.value);
              setErrors((prev) => ({ ...prev, email: false }));
            }}
            onActionClick={handleEmailSubmit}
            placeholder="Your email"
            withAction
            name="email"
            autoComplete="on"
            error={Boolean(errors.email)}
            className="mailInput"
          />
          <div>
            <Checkbox
              checked={agreementSigned}
              onChange={(e) => {
                setAgreementSigned(e.target.checked);
                setErrors((prev) => ({ ...prev, agreement: false }));
              }}
              error={errors.agreement}
              label={
                <Body className="privacy-link">
                  I have reviewed and agree to{" "}
                  <a
                    href="/privacy-policy"
                    target="_blank"
                    style={{ textDecoration: "underline" }}
                  >
                    Privacy Policy
                  </a>
                </Body>
              }
            />
          </div>
        </div>
        <div>
          <div className="curatedTxt" />
          <Heading size="s" className="initiativeHeading" as="div">
            Curated/txt
          </Heading>
          <Body>
            Online media uniting widely known contemporary art experts to
            analyze NFT-related creative practices
          </Body>
          <Button className="comingSoon" disabled type="secondary">
            coming soon
          </Button>
        </div>
      </div>
      <Alert msg={alertMsg} onDelete={() => setAlertMsg("")} />
    </InitiativesContainer>
  );
};

export default Initiatives;
