import React, { useState, useRef } from "react"
import styles from "./contact-me.module.css"
import { LuMousePointerClick } from "react-icons/lu";
import { publicApi } from "@/api/publicClient";
import { useTranslation } from "react-i18next";
import { useTurnstile } from "@/hooks/useTurnstile";

export default function ContactMeForm() {
  const { t } = useTranslation("home");
  const [opened, setOpened] = useState(true)
  const [contentMoveUp, setContentMoveUp] = useState(true)
  const [openingBehind, setOpeningBehind] = useState(true)
  const [email, setEmail] = useState("")
  const [message, setMessage] = useState("")
  const [loading, setLoading] = useState(false)
  const [envelopeFading, setEnvelopeFading] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState("")
  const openingRef = useRef<HTMLDivElement>(null)
  const { containerRef, token: turnstileToken, enabled: turnstileEnabled, reset: resetTurnstile } = useTurnstile()

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!turnstileToken) return
    setLoading(true)
    setError("")
    try {
      await publicApi.post("/api/advertisement/contact-me/", { email, message, hp: "", turnstile_token: turnstileToken ?? "" })
      setEmail("")
      setMessage("")
      // Step 1: slide form into envelope (content drops down behind cover, 1s transition)
      setContentMoveUp(false)
      setOpeningBehind(false)
      // Step 2: close flap after form has slid in
      setTimeout(() => setOpened(false), 1100)
      // Step 3: fade out envelope after flap finishes closing
      setTimeout(() => setEnvelopeFading(true), 2300)
      // Step 4: show success panel
      setTimeout(() => setSuccess(true), 2700)
    } catch {
      setError(t("contact.sendError"))
      resetTurnstile()
    } finally {
      setLoading(false)
    }
  }

  const toggleOpen = () => {
    if (!opened) {
      setOpened(true)
      setOpeningBehind(false)
      setContentMoveUp(false)
    } else {
      setContentMoveUp(false)
      setOpeningBehind(false)
      setTimeout(() => setOpened(false), 1000)
    }
  }

  const handleTransitionEnd = (e: React.TransitionEvent<HTMLDivElement>) => {
    if (opened && e.propertyName === "transform") {
      setContentMoveUp(true)
      setTimeout(() => setOpeningBehind(true), 10)
    }
    if (!opened && e.propertyName === "transform") {
      setOpeningBehind(false)
    }
  }

  function handleNewMessage() {
    setSuccess(false)
    setEnvelopeFading(false)
    setOpened(true)
    setContentMoveUp(true)
    setOpeningBehind(true)
  }

  if (success) {
    return (
      <div className={styles["success-panel"]}>
        <div style={{ fontSize: "2.5rem" }}>✓</div>
        <p style={{ color: "var(--c-other)", fontWeight: 700, margin: 0 }}>{t("contact.messageSent")}</p>
        <p style={{ color: "color-mix(in hsl, var(--c-text), transparent 35%)", fontSize: "0.85rem", margin: 0 }}>
          {t("contact.replyIn24h")}
        </p>
        <button
          onClick={handleNewMessage}
          style={{
            marginTop: "0.5rem", background: "none", border: "1px solid var(--c-lines)",
            color: "var(--c-text)", padding: "0.4em 1.2em", borderRadius: "0.5em",
            cursor: "pointer", fontSize: "0.82rem",
          }}
        >
          {t("contact.newMessage")}
        </button>
      </div>
    )
  }

  return (
    <div className={[styles["contact-me"], envelopeFading ? styles["envelope-fadeout"] : ""].filter(Boolean).join(" ")}>
      <div
        ref={openingRef}
        className={[
          styles.opening,
          opened ? styles["rotate-opening"] : "",
          openingBehind ? styles["opening-behind"] : ""
        ].filter(Boolean).join(" ")}
        onClick={toggleOpen}
        onTransitionEnd={handleTransitionEnd}
      >
        <LuMousePointerClick />
      </div>

      <div className={[styles.content, contentMoveUp ? styles["content-moveup"] : ""].filter(Boolean).join(" ")}>
        <form onSubmit={handleSubmit}>
          <input
            type="email"
            name="email"
            placeholder={t("contact.emailPlaceholder")}
            required
            value={email}
            onChange={e => setEmail(e.target.value)}
          />
          <textarea
            name="message"
            placeholder={t("contact.messagePlaceholder")}
            required
            value={message}
            onChange={e => setMessage(e.target.value)}
          />
          {error && (
            <p style={{ color: "#ff6b6b", fontSize: "0.8rem", margin: "0", textAlign: "center" }}>{error}</p>
          )}
          {turnstileEnabled && <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}><div ref={containerRef} /></div>}
          <input type="submit" value={loading ? t("contact.sendingButton") : t("contact.sendButton")} disabled={loading || !turnstileToken} />
        </form>
      </div>

      <div className={styles.cover}></div>
      <div className={styles.triangle}></div>
    </div>
  )
}
