// 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";
import Textarea from "../Textarea";

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;
  window.scrollTo({ top, behavior: "smooth" });
}

/** Плавный скролл к элементу с учётом отступа (например, под фикс-хедер) */
function smoothScrollToEl(el: HTMLElement, offset: number = 150) {
  const top = el.getBoundingClientRect().top + window.scrollY - offset;
  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;
}

/** Поля, для которых показываем ошибки под элементом управления */
type FieldErrors = Partial<{
  name: string;
  country: string;
  email: string;
  phone: string;
  message: string;
  consents: string; // сводная ошибка по чекбоксам согласий
}>;

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

  const formRef = React.useRef<HTMLFormElement>(null);

  // refs контейнеров полей — чтобы проскроллить к первому с ошибкой
  const nameRef = React.useRef<HTMLDivElement>(null);
  const countryRef = React.useRef<HTMLDivElement>(null);
  const emailRef = React.useRef<HTMLDivElement>(null);
  const phoneRef = React.useRef<HTMLDivElement>(null);
  const messageRef = React.useRef<HTMLDivElement>(null);
  const consentsRef = React.useRef<HTMLDivElement>(null);

  const [busy, setBusy] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [submitError, setSubmitError] = React.useState<string | null>(null); // ошибка отправки (сервер/сеть)

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

  // ошибки по полям
  const [errors, setErrors] = React.useState<FieldErrors>({});

  /** Снять ошибку конкретного поля (используем в onChange) */
  const clearFieldError = React.useCallback((field: keyof FieldErrors) => {
    setErrors((prev) => {
      if (!prev[field]) return prev;
      const { [field]: _drop, ...rest } = prev;
      return rest as FieldErrors;
    });
    if (submitError) setSubmitError(null);
  }, [submitError]);

  const scrollToFirstError = (errs: FieldErrors) => {
    const cands: Array<[keyof FieldErrors, HTMLElement | null]> = [
      ["name", nameRef.current],
      ["country", countryRef.current],
      ["email", emailRef.current],
      ["phone", phoneRef.current],
      ["message", messageRef.current],
      ["consents", consentsRef.current],
    ];

    for (const [key, el] of cands) {
      if (errs[key] && el) {
        smoothScrollToEl(el, 150);
        break;
      }
    }
  };

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

    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 message = String(fd.get("message") || "").trim();

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

    // валидация по полям
    const nextErrors: FieldErrors = {};

    if (!name) nextErrors.name = "Please enter your name.";
    if (!country) nextErrors.country = "Please choose a country from the list.";

    if (!email) {
      nextErrors.email = "Please enter your business email.";
    } else if (!email.includes("@")) {
      nextErrors.email = "Please enter a valid email (must contain @).";
    }

    if (phone && !/^\+?\d+$/.test(phone)) {
      nextErrors.phone = "Phone number can contain only digits and '+'.";
    }

    if (message.length > 500) {
      nextErrors.message = "Message must be 500 characters or fewer.";
    }

    if (!consentPrivacy || !consentComms || !agreePrivacy || !agreeComms) {
      nextErrors.consents = "Please accept both consents.";
    }

    if (Object.keys(nextErrors).length) {
      setErrors(nextErrors);
      scrollToFirstError(nextErrors);
      return;
    }

    try {
      setBusy(true);

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

      setSent(true); // прячем форму, показываем «спасибо»
      form.reset(); // чистим поля, на всякий
      setAgreePrivacy(true);
      setAgreeComms(true);
      setErrors({});
      smoothScrollToContact(150);
    } catch (err: any) {
      setSubmitError(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 ref={nameRef}>
              <Field invalid={!!errors.name}>
                <Input
                  label="Your name"
                  fullWidth
                  name="name"
                  required
                  aria-invalid={!!errors.name}
                  onChange={() => clearFieldError("name")}
                />
                {errors.name ? <ErrorText>{errors.name}</ErrorText> : null}
              </Field>
            </ColSpan2>

            {/* страна — на 2 колонки, обязательный выбор из списка */}
            <ColSpan2 ref={countryRef}>
              <Field invalid={!!errors.country}>
                <CountrySelect
                  label="Country"
                  name="country"
                  locale={userLocale}
                  fullWidth
                  aria-invalid={!!errors.country}
                  onChange={() => clearFieldError("country")}
                />
                {errors.country ? <ErrorText>{errors.country}</ErrorText> : null}
              </Field>
            </ColSpan2>

            {/* 2-я строка: 2 колонки (необязательные) */}
            <div>
              <Field>
                <Input label="Company" fullWidth name="company" />
              </Field>
            </div>
            <div>
              <Field>
                <Input label="Position" fullWidth name="position" />
              </Field>
            </div>

            {/* 3-я строка: 2 колонки */}
            <div ref={emailRef}>
              <Field invalid={!!errors.email}>
                <Input
                  label="Business email"
                  type="email"
                  fullWidth
                  name="email"
                  autoComplete="email"
                  required
                  aria-invalid={!!errors.email}
                  onChange={() => clearFieldError("email")}
                />
                {errors.email ? <ErrorText>{errors.email}</ErrorText> : null}
              </Field>
            </div>

            <div ref={phoneRef}>
              <Field invalid={!!errors.phone}>
                <Input
                  label="Telephone"
                  type="tel"
                  fullWidth
                  name="phone"
                  autoComplete="tel"
                  aria-invalid={!!errors.phone}
                  onChange={() => clearFieldError("phone")}
                />
                {errors.phone ? <ErrorText>{errors.phone}</ErrorText> : null}
              </Field>
            </div>

            <ColSpan2 ref={messageRef}>
              <Field invalid={!!errors.message}>
                <Textarea
                  label="Your message to us"
                  name="message"
                  fullWidth
                  maxLength={500}
                  maxRows={4}
                  aria-invalid={!!errors.message}
                  onChange={() => clearFieldError("message")}
                />
                {errors.message ? <ErrorText>{errors.message}</ErrorText> : null}
              </Field>
            </ColSpan2>
          </Grid>

          {/* ошибка уровня формы (сервер/сеть) */}
          {submitError ? <GlobalErrorNote>{submitError}</GlobalErrorNote> : null}

          {/* согласия */}
          <Consents ref={consentsRef}>
            <ConsentRow>
              <Checkbox
                type="checkbox"
                id="c1"
                name="consentPrivacy"
                checked={agreePrivacy}
                onChange={(e) => {
                  const v = e.target.checked;
                  setAgreePrivacy(v);
                  if (v && agreeComms) clearFieldError("consents");
                }}
                aria-invalid={!!errors.consents}
              />
              <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) => {
                  const v = e.target.checked;
                  setAgreeComms(v);
                  if (v && agreePrivacy) clearFieldError("consents");
                }}
                aria-invalid={!!errors.consents}
              />
              <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>

            {errors.consents ? <ErrorText>{errors.consents}</ErrorText> : null}
          </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: 64px 10px 72px;
  @media (max-width: 768px) {
    padding: 48px 10px 48px;
  }
`;

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;
  }
`;

/** Обёртка поля: если invalid=true — подсветка (оставил отключённой по вашему текущему коду) */
const Field = styled.div<{ invalid?: boolean }>`
  & input,
  & textarea,
  & select,
  & [role="combobox"] {
    outline: ${({ invalid }) => (invalid ? "none" : "none")};
    outline-offset: 0;
    border-color: ${({ invalid }) => (invalid ? undefined : undefined)};
  }
`;

const ErrorText = styled.div`
  margin-top: 6px;
  color: #dc2626;
  font-size: 14px;
  line-height: 1.3;
`;

const GlobalErrorNote = styled.div`
  margin-top: 12px;
  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; }
`;
