"use client";

import { useState, useEffect } from "react";
import type { Lang } from "@/lib/config";
import { getCSRFToken, getCSRFTokenAsync } from "@/lib/csrf-client";

export default function SimpleContactForm({ lang, copy, routingInfo }: any) {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    company: "",
    topic: "",
    message: "",
    consent: false,
    language: lang,
  });

  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [error, setError] = useState("");

  // Fetch CSRF token on mount
  useEffect(() => {
    getCSRFTokenAsync();
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSubmitting(true);
    setError("");

    try {
      // Get CSRF token
      let csrfToken = getCSRFToken();
      if (!csrfToken) {
        csrfToken = await getCSRFTokenAsync();
      }

      const submitData = new FormData();
      Object.entries(formData).forEach(([key, value]) => {
        submitData.append(
          key === "language" ? "preferredLanguage" : key,
          value.toString(),
        );
      });
      submitData.append("consentGiven", formData.consent.toString());
      submitData.append("recaptchaToken", "DISABLED_FOR_TESTING");
      submitData.append("formStartedAt", Date.now().toString());
      submitData.append("timeOnPageMs", "30000");

      const response = await fetch("/api/contact/submit", {
        method: "POST",
        headers: csrfToken ? { "x-csrf-token": csrfToken } : {},
        credentials: "include",
        body: submitData,
      });

      const result = await response.json();

      if (response.ok) {
        setSuccess(true);
        setFormData({
          name: "",
          email: "",
          phone: "",
          company: "",
          topic: "",
          message: "",
          consent: false,
          language: lang,
        });
      } else {
        setError(result.error || "Submission failed");
      }
    } catch (err) {
      setError("Network error");
    } finally {
      setSubmitting(false);
    }
  };

  if (success) {
    return (
      <div className="text-center py-8">
        <h3 className="text-2xl font-bold text-emerald-600 mb-4">Success!</h3>
        <p>Your message has been sent.</p>
        <button
          onClick={() => setSuccess(false)}
          className="mt-4 px-6 py-3 bg-brand-green text-white rounded-lg"
        >
          Send Another Message
        </button>
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="p-4 bg-red-50 border border-red-200 rounded-lg text-sm text-red-700">
          {error}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-2">
            {copy.nameLabel} <span className="text-red-500">*</span>
          </label>
          <input
            type="text"
            name="name"
            required
            value={formData.name}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, name: e.target.value }))
            }
            className="w-full px-4 py-3 border border-neutral-300 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-2">
            {copy.emailLabel} <span className="text-red-500">*</span>
          </label>
          <input
            type="email"
            name="email"
            required
            value={formData.email}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, email: e.target.value }))
            }
            className="w-full px-4 py-3 border border-neutral-300 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-2">
            {copy.phoneLabel}
          </label>
          <input
            type="tel"
            name="phone"
            value={formData.phone}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, phone: e.target.value }))
            }
            placeholder={copy.phoneHint}
            className="w-full px-4 py-3 border border-neutral-300 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-neutral-700 mb-2">
            {copy.companyLabel}
          </label>
          <input
            type="text"
            name="company"
            value={formData.company}
            onChange={(e) =>
              setFormData((prev) => ({ ...prev, company: e.target.value }))
            }
            className="w-full px-4 py-3 border border-neutral-300 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
          />
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium text-neutral-700 mb-2">
          {copy.topicLabel} <span className="text-red-500">*</span>
        </label>
        <select
          name="topic"
          required
          value={formData.topic}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, topic: e.target.value }))
          }
          className="w-full px-4 py-3 border border-neutral-300 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20"
        >
          <option value="">{copy.topicPlaceholder}</option>
          {copy.topicOptions.map((opt: any) => (
            <option key={opt.value} value={opt.value}>
              {opt.label}
            </option>
          ))}
        </select>
      </div>

      <div>
        <label className="block text-sm font-medium text-neutral-700 mb-2">
          {copy.messageLabel} <span className="text-red-500">*</span>
        </label>
        <textarea
          name="message"
          required
          rows={6}
          value={formData.message}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, message: e.target.value }))
          }
          placeholder={copy.messagePlaceholder}
          className="w-full px-4 py-3 border border-neutral-300 rounded-lg focus:border-brand-green focus:ring-2 focus:ring-brand-green/20 resize-none"
        />
        <div className="mt-2 text-sm text-neutral-500">
          {formData.message.length}/10000
        </div>
      </div>

      <div>
        <fieldset className="space-y-3">
          <legend className="text-sm font-medium text-neutral-700">
            {copy.languageLabel}
          </legend>
          <div className="flex gap-3">
            {copy.languageOptions.map((opt: any) => (
              <label
                key={opt.value}
                className="flex items-center gap-2 border border-neutral-300 px-4 py-2 rounded-full cursor-pointer"
              >
                <input
                  type="radio"
                  name="language"
                  value={opt.value}
                  checked={formData.language === opt.value}
                  onChange={(e) =>
                    setFormData((prev) => ({
                      ...prev,
                      language: e.target.value as any,
                    }))
                  }
                />
                <span>{opt.label}</span>
              </label>
            ))}
          </div>
        </fieldset>
      </div>

      <div className="flex items-start gap-3">
        <input
          type="checkbox"
          name="consent"
          required
          checked={formData.consent}
          onChange={(e) =>
            setFormData((prev) => ({ ...prev, consent: e.target.checked }))
          }
          className="mt-1 h-5 w-5 text-brand-green border-neutral-300 rounded"
        />
        <label className="text-sm text-neutral-700">{copy.consentLabel}</label>
      </div>

      <button
        type="submit"
        disabled={submitting}
        className="w-full px-6 py-3 bg-brand-green text-white rounded-lg font-semibold hover:bg-green-600 disabled:opacity-70"
      >
        {submitting ? copy.submittingCta : copy.submitCta}
      </button>
    </form>
  );
}
