// src/sections/ContactFormSection.tsx
import React from "react";
import styled from "styled-components";
import {
  s_Text40_700 as Text40_700,
  s_f_Text18_400 as Text18_400,
} from "../Typography";
import Input from "../Input";
import CountrySelect from "../CountrySelect";

type GqlResponse<T> = { data?: T; errors?: Array<{ message: string }> };

const CREATE_MUTATION = `
mutation CreateContact($data: ContactRequestCreateInput!) {
  createContactRequest(data: $data) { id }
}
`;

function smoothScrollToContact(offset: number = 50) {
  const el = document.querySelector<HTMLElement>("#contact");
  if (!el) return;

  const top =
    el.getBoundingClientRect().top + window.scrollY - offset;

  console.log(top);

  window.scrollTo({
    top,
    behavior: "smooth",
  });
}

// универсальный helper
async function fetchGraphQL<T>(query: string, variables?: Record<string, any>) {
  const res = await fetch("/api/graphql", {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ query, variables }),
  });
  const json = (await res.json()) as GqlResponse<T>;
  if (json.errors?.length) throw new Error(json.errors[0].message);
  return json.data as T;
}

const ContactFormSection: React.FC = () => {
  const userLocale =
    typeof navigator !== "undefined" ? navigator.language : "en";

  const formRef = React.useRef<HTMLFormElement>(null);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);
  const [sent, setSent] = React.useState(false);

  // состояния согласий
  const [agreePrivacy, setAgreePrivacy] = React.useState(true);
  const [agreeComms, setAgreeComms] = React.useState(true);

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);

    const form = formRef.current;
    if (!form) return;

    // собираем значения
    const fd = new FormData(form);
    const name = String(fd.get("name") || "").trim();
    const country = String(fd.get("country") || "").trim(); // ISO код из CountrySelect
    const company = String(fd.get("company") || "").trim();
    const position = String(fd.get("position") || "").trim();
    const email = String(fd.get("email") || "").trim();
    const phone = String(fd.get("phone") || "").trim();

    // читаем согласия из формы (и дублируем защиту состояниями)
    const consentPrivacy = fd.get("consentPrivacy") === "on";
    const consentComms = fd.get("consentComms") === "on";

    // простая валидация
    if (!name) return setError("Please enter your name.");
    if (!country) return setError("Please choose a country from the list.");
    if (!email) return setError("Please enter your business email.");
    if (!consentPrivacy || !consentComms || !agreePrivacy || !agreeComms) {
      return setError("Please accept both consents.");
    }

    try {
      setBusy(true);

      // 1) создаём лид в Keystone
      await fetchGraphQL<{ createContactRequest: { id: string } }>(
        CREATE_MUTATION,
        {
          data: {
            name,
            countryCode: country,
            company,
            position,
            email,
            phone,
          },
        }
      );

      setSent(true);          // прячем форму, показываем «спасибо»
      form.reset();           // чистим поля, на всякий
      // на всякий возвращаем чекбоксы в true (форма уже скрыта)
      setAgreePrivacy(true);
      setAgreeComms(true);
      smoothScrollToContact(150);
    } catch (err: any) {
      setError(err?.message || "Failed to submit. Please try again.");
    } finally {
      setBusy(false);
    }
  };

  return (
    <Wrap id="contact">
      <Text40_700
        style={{
          textAlign: "center",
          margin: "0 auto 24px",
          maxWidth: "530px",
        }}
      >
        Let’s build the future of the industry together
      </Text40_700>

      {/* если отправлено — показываем «спасибо» */}
      {sent ? (
        <ThanksBox>
          <h3>Thank you!</h3>
          <p>
            Your request has been submitted. Our team will contact you shortly.
          </p>
        </ThanksBox>
      ) : (
        <Form ref={formRef} onSubmit={onSubmit} noValidate>
          <Grid>
            {/* имя — на 2 колонки */}
            <ColSpan2>
              <Input label="Your name" fullWidth name="name" required />
            </ColSpan2>

            {/* страна — на 2 колонки, обязательный выбор из списка */}
            <ColSpan2>
              <CountrySelect
                label="Country"
                name="country"
                locale={userLocale}
                fullWidth
              />
            </ColSpan2>

            {/* 2-я строка: 2 колонки */}
            <Input label="Company" fullWidth name="company" />
            <Input label="Position" fullWidth name="position" />

            {/* 3-я строка: 2 колонки */}
            <Input
              label="Business email"
              type="email"
              fullWidth
              name="email"
              autoComplete="email"
              required
            />
            <Input
              label="Telephone"
              type="tel"
              fullWidth
              name="phone"
              autoComplete="tel"
            />
          </Grid>

          {error ? <ErrorNote>{error}</ErrorNote> : null}

          {/* согласия */}
          <Consents>
            <ConsentRow>
              <Checkbox
                type="checkbox"
                id="c1"
                name="consentPrivacy"
                checked={agreePrivacy}
                onChange={(e) => setAgreePrivacy(e.target.checked)}
              />
              <label htmlFor="c1">
                I accept the{" "}
                <a href="/privacy" target="_blank" rel="noreferrer">
                  privacy policy
                </a>{" "}
                and consent to the processing of my personal data
              </label>
            </ConsentRow>

            <ConsentRow>
              <Checkbox
                type="checkbox"
                id="c2"
                name="consentComms"
                checked={agreeComms}
                onChange={(e) => setAgreeComms(e.target.checked)}
              />
              <label htmlFor="c2">
                I confirm my consent to receive information from the company via
                the provided contact methods of Email and/or Telephone
              </label>
            </ConsentRow>
          </Consents>

          <Actions>
            <SubmitButton type="submit" disabled={busy || !agreePrivacy || !agreeComms}>
              {busy ? "Sending…" : "Submit a request"}
            </SubmitButton>
          </Actions>
        </Form>
      )}
    </Wrap>
  );
};

export default ContactFormSection;

/* ================= styles ================= */

const Wrap = styled.section`
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 10px 72px;
`;

const Form = styled.form`
  max-width: 760px;
  margin: 0 auto;
  overflow: visible;
`;

const Grid = styled.div`
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;

  @media (min-width: 900px) {
    grid-template-columns: 1fr 1fr;
  }
`;

const ColSpan2 = styled.div`
  @media (min-width: 900px) {
    grid-column: 1 / span 2;
  }
`;

const ErrorNote = styled.div`
  margin-top: 8px;
  color: #dc2626;
  font-size: 14px;
`;

const Consents = styled.div`
  margin-top: 16px;
  display: grid;
  gap: 12px;

  label {
    ${Text18_400 as any};
    color: #1d2023;
  }

  a {
    color: #16a34a;
    text-decoration: underline;
    text-underline-offset: 2px;
  }
`;

const ConsentRow = styled.div`
  display: grid;
  grid-template-columns: 18px 1fr;
  align-items: start;
  gap: 12px;
`;

const Checkbox = styled.input`
  appearance: none;
  width: 18px;
  height: 18px;
  border: 1.5px solid #b7c0c8;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  position: relative;

  &:checked {
    background: #16a34a;
    border-color: #16a34a;
  }

  &:checked::after {
    content: "";
    position: absolute;
    left: 4px;
    top: 0px;
    width: 6px;
    height: 10px;
    border: 2px solid #fff;
    border-top: 0;
    border-left: 0;
    transform: rotate(45deg);
  }
`;

const Actions = styled.div`
  display: flex;
  justify-content: center;
  margin-top: 24px;
`;

const SubmitButton = styled.button<{ disabled?: boolean }>`
  background: #16a34a;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 16px 32px;
  cursor: pointer;
  ${Text18_400 as any};
  font-weight: 700;
  transition: transform 0.15s ease, filter 0.15s ease, opacity 0.15s ease;

  &:hover { transform: translateY(-1px); filter: brightness(0.98); }
  &:active { transform: scale(0.98); }
  &:disabled { opacity: .6; cursor: default; transform: none; }
`;

const ThanksBox = styled.div`
  max-width: 760px;
  margin: 0 auto;
  padding: 32px;
  border-radius: 12px;
  background: #f5f8fb;
  text-align: center;

  h3 { margin: 0 0 8px; font-weight: 700; }
  p  { margin: 0; }
`;
