'use client';

import { useState, useRef, useCallback } from 'react';
import { Send, CheckCircle } from 'lucide-react';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000/v1';

export default function CTASection() {
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const formStartTime = useRef<number | null>(null);

  const handleFocus = useCallback(() => {
    if (!formStartTime.current) {
      formStartTime.current = Date.now();
    }
  }, []);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError('');
    setLoading(true);

    const form = e.currentTarget;
    const formData = new FormData(form);

    // Honeypot check (client-side early exit)
    if (formData.get('website')) {
      setSubmitted(true);
      setLoading(false);
      return;
    }

    const formFilledMs = formStartTime.current ? Date.now() - formStartTime.current : undefined;

    // Extract UTM from URL
    const params = new URLSearchParams(window.location.search);
    const utmFields: Record<string, string> = {};
    for (const key of ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term']) {
      const val = params.get(key);
      if (val) utmFields[key] = val;
    }

    const body = {
      name: formData.get('name') as string,
      phone: formData.get('phone') as string,
      email: formData.get('email') as string,
      message: formData.get('club') as string,
      source: 'landing',
      honeypot: formData.get('website') as string,
      formFilledMs,
      ...utmFields,
    };

    try {
      const res = await fetch(`${API_URL}/crm/deals/from-form`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });

      const data = await res.json();

      if (data.success === false && data.error === 'captcha_required') {
        setError('Пожалуйста, попробуйте позже');
        return;
      }

      if (data.success === false && data.error === 'spam') {
        // Silently accept to not reveal spam detection
        setSubmitted(true);
        return;
      }

      setSubmitted(true);
    } catch {
      setError('Ошибка отправки. Попробуйте позже.');
    } finally {
      setLoading(false);
    }
  }

  return (
    <section id="demo" className="py-20 bg-navy relative overflow-hidden">
      <div className="absolute inset-0 opacity-10">
        <div className="absolute top-0 left-1/4 w-96 h-96 rounded-full bg-primary blur-3xl" />
        <div className="absolute bottom-0 right-1/4 w-96 h-96 rounded-full bg-primary blur-3xl" />
      </div>
      <div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
        <div className="grid lg:grid-cols-2 gap-12 items-center">
          <div>
            <h2 className="text-3xl sm:text-4xl font-bold text-white">
              Готовы увеличить эффективность клуба?
            </h2>
            <p className="mt-4 text-lg text-gray-300 leading-relaxed">
              Оставьте заявку — мы свяжемся в течение 30 минут, проведём демонстрацию и настроим
              систему за 1 день. 14 дней бесплатно.
            </p>
            <div className="mt-8 grid grid-cols-2 gap-4">
              {[
                'Бесплатная настройка',
                'Миграция данных',
                'Обучение команды',
                'Поддержка 24/7',
              ].map((item) => (
                <div key={item} className="flex items-center gap-2 text-sm text-gray-300">
                  <svg
                    className="h-4 w-4 text-primary shrink-0"
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path
                      fillRule="evenodd"
                      d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                      clipRule="evenodd"
                    />
                  </svg>
                  {item}
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-2xl bg-white p-8">
            {submitted ? (
              <div className="text-center py-8">
                <CheckCircle size={48} className="text-success mx-auto mb-4" />
                <h3 className="text-xl font-bold text-gray-900">Заявка отправлена!</h3>
                <p className="mt-2 text-sm text-gray-500">Мы свяжемся с вами в течение 30 минут</p>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-4">
                <h3 className="text-xl font-bold text-gray-900 mb-2">Получить бесплатный доступ</h3>

                {error && (
                  <div className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded-lg">{error}</div>
                )}

                {/* Honeypot — hidden from users, filled by bots */}
                <input
                  type="text"
                  name="website"
                  autoComplete="off"
                  tabIndex={-1}
                  className="absolute -left-[9999px] opacity-0 h-0 w-0"
                  aria-hidden="true"
                />

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
                  <input
                    type="text"
                    name="name"
                    required
                    placeholder="Ваше имя"
                    onFocus={handleFocus}
                    className="w-full rounded-xl border border-gray-200 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Телефон</label>
                  <input
                    type="tel"
                    name="phone"
                    required
                    placeholder="+7 (___) ___-__-__"
                    onFocus={handleFocus}
                    className="w-full rounded-xl border border-gray-200 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                  <input
                    type="email"
                    name="email"
                    required
                    placeholder="email@example.com"
                    onFocus={handleFocus}
                    className="w-full rounded-xl border border-gray-200 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Название клуба
                  </label>
                  <input
                    type="text"
                    name="club"
                    placeholder="Название вашего клуба"
                    onFocus={handleFocus}
                    className="w-full rounded-xl border border-gray-200 px-4 py-3 text-sm text-gray-900 placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all"
                  />
                </div>
                <button
                  type="submit"
                  disabled={loading}
                  className="w-full flex items-center justify-center gap-2 rounded-xl bg-primary px-6 py-3.5 text-sm font-semibold text-white shadow-lg shadow-primary/25 hover:bg-primary-dark transition-colors disabled:opacity-50"
                >
                  <Send size={16} />
                  {loading ? 'Отправка...' : 'Получить бесплатный доступ'}
                </button>
                <p className="text-xs text-gray-400 text-center">
                  Нажимая кнопку, вы соглашаетесь с{' '}
                  <a href="#" className="underline">
                    политикой конфиденциальности
                  </a>
                </p>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
