import { useEffect, useRef, useState } from "react";
import {
  MessageCircle,
  X,
  Send,
  CheckCircle2,
  Loader2,
  Mail,
} from "lucide-react";

/**
 * PresalesChatWidget
 * -------------------
 * A floating live-chat / contact bubble shown on marketing landing pages.
 * Visitors can leave a pre-sales inquiry (name, email, phone, company,
 * topic, message) and it is persisted to the Atoms Cloud backend via
 * `POST /api/v1/entities/presales_messages`.
 *
 * This widget is public (no auth required). After a successful submission
 * the widget shows a success state and resets for the next visitor.
 */

export interface PresalesChatWidgetProps {
  /** Slug of the page the widget is embedded on, e.g. "bizmail360". */
  sourcePage: string;
  /** Optional title shown in the widget header. */
  title?: string;
  /** Optional subtitle shown under the title. */
  subtitle?: string;
  /** Optional preselected topic (pricing / demo / migration / support / other). */
  defaultTopic?: string;
  /** Accent background (e.g. header). Tailwind bg class. */
  accentClassName?: string;
  /** Accent text color class. */
  accentTextClassName?: string;
  /** Primary button color class. */
  buttonClassName?: string;
}

type SubmitState = "idle" | "submitting" | "success" | "error";

interface FormState {
  name: string;
  email: string;
  phone: string;
  company: string;
  topic: string;
  message: string;
}

const EMPTY_FORM: FormState = {
  name: "",
  email: "",
  phone: "",
  company: "",
  topic: "pricing",
  message: "",
};

function validateEmail(value: string): boolean {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
}

export default function PresalesChatWidget({
  sourcePage,
  title = "Talk to our team",
  subtitle = "We usually reply within a few minutes.",
  defaultTopic = "pricing",
  accentClassName = "bg-[#0e6305]",
  accentTextClassName = "text-white",
  buttonClassName = "bg-[#0e6305] hover:bg-[#0a5004] text-white",
}: PresalesChatWidgetProps) {
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState<FormState>({
    ...EMPTY_FORM,
    topic: defaultTopic,
  });
  const [state, setState] = useState<SubmitState>("idle");
  const [errorMsg, setErrorMsg] = useState<string>("");
  const panelRef = useRef<HTMLDivElement | null>(null);

  // Close panel with Escape
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setOpen(false);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  const handleChange =
    (field: keyof FormState) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
      setForm((prev) => ({ ...prev, [field]: e.target.value }));
    };

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

    // Basic client-side validation
    if (!form.name.trim()) {
      setErrorMsg("Please enter your name.");
      return;
    }
    if (!validateEmail(form.email)) {
      setErrorMsg("Please enter a valid email address.");
      return;
    }
    if (!form.message.trim()) {
      setErrorMsg("Please enter a short message so we can help.");
      return;
    }

    setState("submitting");
    try {
      const payload = {
        name: form.name.trim().slice(0, 120),
        email: form.email.trim().slice(0, 255),
        phone: form.phone.trim().slice(0, 40) || null,
        company: form.company.trim().slice(0, 200) || null,
        source_page: sourcePage.slice(0, 80),
        topic: (form.topic || "other").slice(0, 40),
        message: form.message.trim(),
        status: "new",
        user_agent: (typeof navigator !== "undefined"
          ? navigator.userAgent
          : ""
        ).slice(0, 500),
        referrer: (typeof document !== "undefined" ? document.referrer : "").slice(
          0,
          500,
        ),
      };

      const res = await fetch("/api/v1/entities/presales_messages", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const text = await res.text().catch(() => "");
        throw new Error(text || `Submission failed (${res.status})`);
      }

      setState("success");
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Submission failed.";
      setErrorMsg(msg);
      setState("error");
    }
  };

  const handleReset = () => {
    setForm({ ...EMPTY_FORM, topic: defaultTopic });
    setState("idle");
    setErrorMsg("");
  };

  return (
    <>
      {/* Floating bubble */}
      <button
        type="button"
        aria-label={open ? "Close chat" : "Open chat"}
        onClick={() => setOpen((v) => !v)}
        className={`fixed bottom-6 right-6 z-[60] w-14 h-14 rounded-full shadow-2xl ${accentClassName} ${accentTextClassName} flex items-center justify-center transition hover:scale-105 active:scale-95 focus:outline-none focus:ring-4 focus:ring-emerald-300/50`}
      >
        {open ? (
          <X className="w-6 h-6" />
        ) : (
          <MessageCircle className="w-6 h-6" />
        )}
        {!open && (
          <span className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-yellow-400 ring-2 ring-white animate-pulse" />
        )}
      </button>

      {/* Chat panel */}
      {open && (
        <div
          ref={panelRef}
          role="dialog"
          aria-label="Pre-sales chat"
          className="fixed bottom-24 right-4 sm:right-6 z-[60] w-[min(92vw,22rem)] max-h-[80vh] rounded-2xl shadow-2xl border border-slate-200 bg-white overflow-hidden flex flex-col"
        >
          {/* Header */}
          <div className={`${accentClassName} ${accentTextClassName} px-4 py-3 flex items-start gap-3`}>
            <div className="w-9 h-9 rounded-full bg-white/20 flex items-center justify-center shrink-0">
              <Mail className="w-4 h-4" />
            </div>
            <div className="flex-1 min-w-0">
              <div className="font-bold text-sm truncate">{title}</div>
              <div className="text-[11px] opacity-90 truncate">{subtitle}</div>
            </div>
            <button
              type="button"
              onClick={() => setOpen(false)}
              aria-label="Close"
              className="opacity-90 hover:opacity-100"
            >
              <X className="w-4 h-4" />
            </button>
          </div>

          {/* Body */}
          <div className="flex-1 overflow-y-auto px-4 py-4 bg-slate-50">
            {state === "success" ? (
              <div className="text-center py-6">
                <div className="w-14 h-14 mx-auto rounded-full bg-emerald-100 text-emerald-700 flex items-center justify-center mb-3">
                  <CheckCircle2 className="w-7 h-7" />
                </div>
                <h3 className="text-[#1e3828] font-bold text-base mb-1">
                  Thanks — we got your message!
                </h3>
                <p className="text-slate-600 text-sm mb-5">
                  Our team will reach out to <strong>{form.email}</strong> shortly.
                </p>
                <button
                  type="button"
                  onClick={handleReset}
                  className={`px-4 py-2 rounded-md text-sm font-semibold ${buttonClassName}`}
                >
                  Send another message
                </button>
              </div>
            ) : (
              <form onSubmit={handleSubmit} className="space-y-3">
                <div>
                  <label
                    htmlFor="chat-name"
                    className="block text-xs font-semibold text-slate-700 mb-1"
                  >
                    Name <span className="text-rose-500">*</span>
                  </label>
                  <input
                    id="chat-name"
                    type="text"
                    autoComplete="name"
                    value={form.name}
                    onChange={handleChange("name")}
                    required
                    className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
                    placeholder="Your full name"
                  />
                </div>

                <div>
                  <label
                    htmlFor="chat-email"
                    className="block text-xs font-semibold text-slate-700 mb-1"
                  >
                    Email <span className="text-rose-500">*</span>
                  </label>
                  <input
                    id="chat-email"
                    type="email"
                    autoComplete="email"
                    value={form.email}
                    onChange={handleChange("email")}
                    required
                    className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
                    placeholder="you@company.com"
                  />
                </div>

                <div className="grid grid-cols-2 gap-2">
                  <div>
                    <label
                      htmlFor="chat-phone"
                      className="block text-xs font-semibold text-slate-700 mb-1"
                    >
                      Phone
                    </label>
                    <input
                      id="chat-phone"
                      type="tel"
                      autoComplete="tel"
                      value={form.phone}
                      onChange={handleChange("phone")}
                      className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
                      placeholder="Optional"
                    />
                  </div>
                  <div>
                    <label
                      htmlFor="chat-company"
                      className="block text-xs font-semibold text-slate-700 mb-1"
                    >
                      Company
                    </label>
                    <input
                      id="chat-company"
                      type="text"
                      autoComplete="organization"
                      value={form.company}
                      onChange={handleChange("company")}
                      className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
                      placeholder="Optional"
                    />
                  </div>
                </div>

                <div>
                  <label
                    htmlFor="chat-topic"
                    className="block text-xs font-semibold text-slate-700 mb-1"
                  >
                    I&apos;m interested in
                  </label>
                  <select
                    id="chat-topic"
                    value={form.topic}
                    onChange={handleChange("topic")}
                    className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500"
                  >
                    <option value="pricing">Pricing & plans</option>
                    <option value="demo">Request a demo</option>
                    <option value="migration">Migration assistance</option>
                    <option value="support">Support question</option>
                    <option value="other">Something else</option>
                  </select>
                </div>

                <div>
                  <label
                    htmlFor="chat-message"
                    className="block text-xs font-semibold text-slate-700 mb-1"
                  >
                    Message <span className="text-rose-500">*</span>
                  </label>
                  <textarea
                    id="chat-message"
                    rows={3}
                    value={form.message}
                    onChange={handleChange("message")}
                    required
                    className="w-full rounded-md border border-slate-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 resize-none"
                    placeholder="Tell us how we can help…"
                  />
                </div>

                {errorMsg && (
                  <div className="text-xs text-rose-600 bg-rose-50 border border-rose-200 rounded-md px-3 py-2">
                    {errorMsg}
                  </div>
                )}

                <button
                  type="submit"
                  disabled={state === "submitting"}
                  className={`w-full inline-flex items-center justify-center gap-2 py-2.5 rounded-md text-sm font-bold transition ${buttonClassName} disabled:opacity-60 disabled:cursor-not-allowed`}
                >
                  {state === "submitting" ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" /> Sending…
                    </>
                  ) : (
                    <>
                      <Send className="w-4 h-4" /> Send message
                    </>
                  )}
                </button>

                <p className="text-[11px] text-slate-500 text-center">
                  By sending, you agree to be contacted by our sales team about
                  your inquiry.
                </p>
              </form>
            )}
          </div>
        </div>
      )}
    </>
  );
}