import { Globe, Mail, MapPin } from "lucide-react";
import { motion } from "motion/react";
import { useEffect, useRef, useState } from "react";
import { Button, Checkbox, Form, Input, message } from "antd";
import { apiRequest, type ApiResponse } from "../../services/request";

const sectionReveal = {
  initial: { opacity: 0, y: 40 },
  whileInView: { opacity: 1, y: 0 },
  viewport: { once: true, amount: 0.25 },
  transition: { duration: 0.7, ease: "easeOut" as const },
};

/** 与 Tailwind lg 断点一致：窄屏下表单在首屏下方，whileInView 可能长期不触发，改为进场动画直接播放 */
const formColumnRevealMobile = {
  initial: { opacity: 0, y: 40 },
  animate: { opacity: 1, y: 0 },
  transition: { duration: 0.7, ease: "easeOut" as const },
};

type SubmittedLeadSnapshot = {
  user_name: string;
  company_name: string;
  phone: string;
  code: string;
  position?: string;
};

export default function ContactPage() {
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [sentJustNow, setSentJustNow] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [submittedSnapshot, setSubmittedSnapshot] = useState<SubmittedLeadSnapshot | null>(
    null,
  );
  const [isNarrowViewport, setIsNarrowViewport] = useState(() =>
    typeof window !== "undefined"
      ? window.matchMedia("(max-width: 1023px)").matches
      : false,
  );
  const sentTimerRef = useRef<number | null>(null);

  useEffect(() => {
    if (countdown <= 0) return;
    const timer = window.setInterval(() => {
      setCountdown((prev) => (prev <= 1 ? 0 : prev - 1));
    }, 1000);
    return () => window.clearInterval(timer);
  }, [countdown]);

  useEffect(() => {
    return () => {
      if (sentTimerRef.current) window.clearTimeout(sentTimerRef.current);
    };
  }, []);

  useEffect(() => {
    const mq = window.matchMedia("(max-width: 1023px)");
    const sync = () => setIsNarrowViewport(mq.matches);
    sync();
    mq.addEventListener("change", sync);
    return () => mq.removeEventListener("change", sync);
  }, []);

  const isSuccessResponse = (res: ApiResponse) => {
    if (res?.code === undefined || res?.code === null || res?.code === "")
      return true;
    return ["success"].includes(res.code as string);
  };

  const handleSendCode = async () => {
    try {
      const { phone } = await form.validateFields(["phone"]);
      setSendingCode(true);
      const res = await apiRequest("/api/website/lead_message/send_code", {
        method: "POST",
        data: { phone },
      });
      if (!isSuccessResponse(res)) {
        messageApi.error(res?.msg || "验证码发送失败，请稍后重试");
        return;
      }
      messageApi.success(res?.msg || "验证码发送成功");
      setSentJustNow(true);
      if (sentTimerRef.current) window.clearTimeout(sentTimerRef.current);
      sentTimerRef.current = window.setTimeout(() => {
        setSentJustNow(false);
        setCountdown(60);
      }, 900);
    } catch {
      // form 校验失败时不提示额外文案
    } finally {
      setSendingCode(false);
    }
  };

  const handleSubmit = async (values: {
    user_name: string;
    position?: string;
    phone: string;
    code: string;
    company_name: string;
    privacy: boolean;
  }) => {
    try {
      setSubmitting(true);
      const { privacy, ...payload } = values;
      const res = await apiRequest("/api/website/lead_message/add", {
        method: "POST",
        data: payload,
      });
      if (!isSuccessResponse(res)) {
        messageApi.error(res?.msg || "提交失败，请稍后重试");
        return;
      }
      messageApi.success(res?.msg || "提交成功");
      setSubmittedSnapshot({
        user_name: payload.user_name,
        company_name: payload.company_name,
        phone: payload.phone,
        code: payload.code,
        position: payload.position,
      });
      setSubmitSuccess(true);
    } finally {
      setSubmitting(false);
    }
  };

  const handleBackFromSuccess = () => {
    form.resetFields([
      "user_name",
      "position",
      "phone",
      "code",
      "company_name",
      "privacy",
    ]);
    setSubmittedSnapshot(null);
    setSubmitSuccess(false);
    setCountdown(0);
  };

  return (
    <div className="pb-16 px-6 max-w-7xl mx-auto text-slate-100 max-lg:pt-[calc(5rem+env(safe-area-inset-top,0px)+2.75rem)] lg:pt-32 lg:pb-24">
      {contextHolder}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 lg:gap-12 items-start">
        <motion.div
          className="mt-0 lg:mt-[82px] lg:col-span-5 space-y-10"
          {...sectionReveal}
        >
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex flex-col gap-3 lg:gap-0"
          >
            <h1 className="font-headline text-5xl font-extrabold tracking-tight text-white leading-tight">
              联系我们
              <div className="mt-3 text-secondary lg:mt-9">
                开启企微私域一体化增长之旅
              </div>
            </h1>
            <p className="mt-4 text-lg text-slate-300 leading-relaxed max-w-md lg:mt-[76px]">
              填写您的信息，专业顾问将在24小时内与您取得联系，为您提供专属的解决方案。
            </p>
          </motion.div>

          {/* <div className="space-y-8">
            {[
              // {
              //   icon: Globe,
              //   title: "公司名称",
              //   value: "深圳大方无隅科技有限公司",
              //   color: "bg-blue-500/15 text-blue-400",
              // },
              // {
              //   icon: MapPin,
              //   title: "公司地址",
              //   value: "深圳市龙华区",
              //   color: "bg-slate-800 text-slate-300",
              // },
              {
                icon: Mail,
                title: "商务合作",
                value: "bd@dotouch.tech",
                color: "bg-slate-800 text-slate-300",
              },
            ].map((item, i) => (
              <div key={i} className="flex items-start gap-6 group">
                <div
                  className={`w-14 h-14 rounded-xl ${item.color} flex items-center justify-center shrink-0 transition-transform group-hover:-translate-y-1`}
                >
                  <item.icon className="w-7 h-7" />
                </div>
                <div>
                  <h3 className="font-headline font-bold text-white mb-1">{item.title}</h3>
                  <p className="text-slate-300 font-medium">{item.value}</p>
                </div>
              </div>
            ))}
          </div> */}
        </motion.div>

        <motion.div
          className="lg:col-span-7"
          {...(isNarrowViewport ? formColumnRevealMobile : sectionReveal)}
        >
          <motion.div
            initial={{ opacity: 0, y: 16 }}
            animate={{ opacity: 1, y: 0 }}
            className="bg-slate-900 rounded-2xl p-8 md:p-12 shadow-xl border border-slate-800"
          >
            {submitSuccess && submittedSnapshot ? (
              <div className="space-y-8">
                <h2 className="font-headline text-2xl md:text-3xl font-bold text-white leading-snug">
                  信息提交成功，专业顾问将在24小时内与您取得联系，为您提供专属的解决方案。
                </h2>
                <div className="rounded-xl border border-slate-800 bg-slate-950/80 p-6 space-y-4">
                  <p className="text-xs font-semibold uppercase tracking-wider text-slate-500">
                    您提交的信息
                  </p>
                  <dl className="space-y-3 text-sm">
                    <div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
                      <dt className="shrink-0 text-slate-500 w-28">姓名</dt>
                      <dd className="text-slate-100 font-medium">{submittedSnapshot.user_name}</dd>
                    </div>
                    <div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
                      <dt className="shrink-0 text-slate-500 w-28">公司名称</dt>
                      <dd className="text-slate-100 font-medium">{submittedSnapshot.company_name}</dd>
                    </div>
                    <div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
                      <dt className="shrink-0 text-slate-500 w-28">手机号</dt>
                      <dd className="text-slate-100 font-medium">{submittedSnapshot.phone}</dd>
                    </div>
                    <div className="flex flex-col gap-0.5 sm:flex-row sm:gap-3">
                      <dt className="shrink-0 text-slate-500 w-28">部门和职务</dt>
                      <dd className="text-slate-100 font-medium">
                        {submittedSnapshot.position?.trim()
                          ? submittedSnapshot.position
                          : "—"}
                      </dd>
                    </div>
                  </dl>
                </div>
                <Button
                  type="default"
                  size="large"
                  onClick={handleBackFromSuccess}
                  className="!h-auto !w-full !py-4 !rounded-lg !font-headline !text-base !font-bold !bg-slate-800 !text-white !border-slate-600 hover:!bg-slate-700 hover:!text-white hover:!border-slate-500"
                >
                  返回
                </Button>
              </div>
            ) : (
              <>
                <div className="mb-10">
                  <h2 className="font-headline text-3xl font-bold text-white mb-2">
                    留下您的信息
                  </h2>
                </div>
                <Form
                  form={form}
                  layout="vertical"
                  className="space-y-6"
                  onFinish={handleSubmit}
                  initialValues={{
                    privacy: true,
                  }}
                >
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 ml-1">
                        姓名（必填）
                      </label>
                      <Form.Item
                        name="user_name"
                        className="!mb-0"
                        rules={[{ required: true, message: "请输入称呼" }]}
                      >
                        <Input
                          className="!w-full !bg-slate-950 !border !border-slate-800 !rounded-lg !px-4 !py-3 !text-slate-100 placeholder:!text-slate-500"
                          placeholder="请输入您的姓名"
                        />
                      </Form.Item>
                    </div>
                    <div className="space-y-2">
                      <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 ml-1">
                        公司名称（必填）
                      </label>
                      <Form.Item
                        name="company_name"
                        className="!mb-0"
                        rules={[{ required: true, message: "请输入公司名称" }]}
                      >
                        <Input
                          className="!w-full !bg-slate-950 !border !border-slate-800 !rounded-lg !px-4 !py-3 !text-slate-100 placeholder:!text-slate-500"
                          placeholder="请输入您的公司全称"
                        />
                      </Form.Item>
                    </div>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 ml-1">
                        手机号（必填）
                      </label>
                      <Form.Item
                        name="phone"
                        className="!mb-0"
                        rules={[
                          { required: true, message: "请输入手机号" },
                          {
                            pattern: /^1\d{10}$/,
                            message: "请输入正确的11位手机号",
                          },
                        ]}
                      >
                        <Input
                          className="!w-full !bg-slate-950 !border !border-slate-800 !rounded-lg !px-4 !py-3 !text-slate-100 placeholder:!text-slate-500"
                          placeholder="请输入手机号码"
                        />
                      </Form.Item>
                    </div>
                    <div className="space-y-2">
                      <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 ml-1">
                        验证码（必填）
                      </label>
                      <div className="relative">
                        <Form.Item
                          name="code"
                          className="!mb-0"
                          rules={[{ required: true, message: "请输入验证码" }]}
                        >
                          <Input
                            className="!w-full !bg-slate-950 !border !border-slate-800 !rounded-lg !px-4 !py-3 !pr-24 !text-slate-100 placeholder:!text-slate-500"
                            placeholder="请输入验证码"
                            maxLength={6}
                          />
                        </Form.Item>
                        <Button
                          type="text"
                          loading={sendingCode}
                          disabled={sendingCode || sentJustNow || countdown > 0}
                          onClick={handleSendCode}
                          className="!absolute !right-2 !top-1.5 !bottom-1.5 !px-3 !text-xs !font-bold !text-blue-300 !bg-slate-800 !rounded-md hover:!bg-secondary hover:!text-white !transition-all"
                        >
                          {sentJustNow
                            ? "已发送"
                            : countdown > 0
                              ? `${countdown}s`
                              : "获取验证码"}
                        </Button>
                      </div>
                    </div>
                  </div>
                  <div className="space-y-2">
                    <label className="text-xs font-semibold uppercase tracking-wider text-slate-500 ml-1">
                      部门和职务（可选）
                    </label>
                    <Form.Item name="position" className="!mb-0">
                      <Input
                        className="!w-full !bg-slate-950 !border !border-slate-800 !rounded-lg !px-4 !py-3 !text-slate-100 placeholder:!text-slate-500"
                        placeholder="例如：销售部 总监"
                      />
                    </Form.Item>
                  </div>
                  <div className="flex items-center gap-3 py-2">
                    <Form.Item
                      name="privacy"
                      valuePropName="checked"
                      className="!mb-0"
                      rules={[
                        {
                          validator: (_, value) =>
                            value
                              ? Promise.resolve()
                              : Promise.reject(
                                  new Error("请先阅读并同意隐私协议与用户协议"),
                                ),
                        },
                      ]}
                    >
                      <Checkbox className="[&_.ant-checkbox-inner]:!bg-slate-900 [&_.ant-checkbox-inner]:!border-slate-600">
                        <span className="text-xs text-slate-400">
                          我已阅读并同意
                          <a
                            className="text-secondary hover:underline"
                            href="/privacy"
                            target="_blank"
                            rel="noreferrer"
                          >
                            《隐私协议》
                          </a>
                          <a
                            className="text-secondary hover:underline"
                            href="/agreement"
                            target="_blank"
                            rel="noreferrer"
                          >
                            《用户协议》
                          </a>
                        </span>
                      </Checkbox>
                    </Form.Item>
                  </div>
                  <button
                    type="submit"
                    disabled={submitting}
                    className="w-full bg-primary text-white py-4 rounded-lg font-bold text-lg shadow-lg hover:bg-secondary transition-all active:scale-95 disabled:opacity-60 disabled:cursor-not-allowed"
                  >
                    提交信息
                  </button>
                </Form>
              </>
            )}
          </motion.div>
        </motion.div>
      </div>
    </div>
  );
}
