// @File: src/components/ContactModals.tsx
// @Desc: Three reusable popup modals triggered from anywhere on the marketing
//        site — Contact Us, Get Prices, and Support. Each modal renders a
//        controlled form, submits via the backend SMTP relay, and shows an
//        inline success / error state so users never leave the current page.
import { useEffect, useState } from "react";
import { X, Mail, Phone, User, Building2, MessageSquare, Tag, Loader2, CheckCircle2 } from "lucide-react";
import {
  submitContactForm,
  submitGetPriceForm,
  submitSupportForm,
} from "@/lib/contact-api";

/* ------------------------------------------------------------------ */
/* Shared modal shell                                                  */
/* ------------------------------------------------------------------ */
interface ModalShellProps {
  open: boolean;
  onClose: () => void;
  title: string;
  subtitle?: string;
  children: React.ReactNode;
}

function ModalShell({ open, onClose, title, subtitle, children }: ModalShellProps) {
  // Close on Escape & lock body scroll while the modal is visible.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-[100] flex items-center justify-center px-4 py-6 sm:py-10"
      role="dialog"
      aria-modal="true"
      aria-labelledby="contact-modal-title"
    >
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-slate-900/70 backdrop-blur-sm animate-[fadeIn_0.2s_ease-out]"
        onClick={onClose}
      />

      {/* Dialog */}
      <div className="relative w-full max-w-xl bg-white rounded-3xl shadow-2xl border border-slate-200 overflow-hidden animate-[fadeInUp_0.35s_ease-out] max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="relative bg-gradient-to-br from-[#0b6e3e] to-[#063019] text-white px-6 sm:px-8 py-5">
          <button
            type="button"
            onClick={onClose}
            aria-label="Close"
            className="absolute top-4 right-4 w-9 h-9 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition"
          >
            <X className="w-5 h-5" />
          </button>
          <h3 id="contact-modal-title" className="text-xl sm:text-2xl font-bold pr-10">
            {title}
          </h3>
          {subtitle && (
            <p className="text-slate-200 text-sm sm:text-base mt-1.5 pr-10">{subtitle}</p>
          )}
        </div>

        {/* Body */}
        <div className="px-6 sm:px-8 py-6 overflow-y-auto">{children}</div>
      </div>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Field helpers                                                       */
/* ------------------------------------------------------------------ */
interface FieldProps {
  id: string;
  label: string;
  icon?: React.ReactNode;
  required?: boolean;
  type?: string;
  placeholder?: string;
  value: string;
  onChange: (v: string) => void;
  textarea?: boolean;
  rows?: number;
  autoComplete?: string;
}

function Field({
  id,
  label,
  icon,
  required,
  type = "text",
  placeholder,
  value,
  onChange,
  textarea,
  rows = 4,
  autoComplete,
}: FieldProps) {
  const base =
    "w-full rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-slate-900 placeholder:text-slate-400 outline-none transition focus:border-[#0b6e3e] focus:ring-2 focus:ring-[#0b6e3e]/20";
  return (
    <div>
      <label htmlFor={id} className="flex items-center gap-2 text-sm font-semibold text-slate-800 mb-1.5">
        {icon}
        {label}
        {required && <span className="text-red-500">*</span>}
      </label>
      {textarea ? (
        <textarea
          id={id}
          name={id}
          required={required}
          rows={rows}
          placeholder={placeholder}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={`${base} resize-y min-h-[96px]`}
        />
      ) : (
        <input
          id={id}
          name={id}
          type={type}
          required={required}
          placeholder={placeholder}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          autoComplete={autoComplete}
          className={base}
        />
      )}
    </div>
  );
}

interface SubmitState {
  loading: boolean;
  error: string | null;
  success: string | null;
}
const initialSubmitState: SubmitState = { loading: false, error: null, success: null };

function SuccessPanel({ message, onClose }: { message: string; onClose: () => void }) {
  return (
    <div className="text-center py-6">
      <div className="w-16 h-16 rounded-full bg-emerald-100 text-[#0b6e3e] mx-auto flex items-center justify-center mb-4">
        <CheckCircle2 className="w-9 h-9" />
      </div>
      <h4 className="text-lg font-bold text-slate-900 mb-2">Message sent</h4>
      <p className="text-slate-600 mb-6">{message}</p>
      <button
        type="button"
        onClick={onClose}
        className="px-6 py-2.5 rounded-md bg-[#0b6e3e] text-white font-bold hover:bg-[#0a8048] transition"
      >
        Close
      </button>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/* Contact Us modal                                                    */
/* ------------------------------------------------------------------ */
export function ContactUsModal({ open, onClose }: { open: boolean; onClose: () => void }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [subject, setSubject] = useState("");
  const [message, setMessage] = useState("");
  const [state, setState] = useState<SubmitState>(initialSubmitState);

  const reset = () => {
    setName("");
    setEmail("");
    setPhone("");
    setSubject("");
    setMessage("");
    setState(initialSubmitState);
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (state.loading) return;
    setState({ loading: true, error: null, success: null });
    try {
      const res = await submitContactForm({
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim() || undefined,
        subject: subject.trim() || undefined,
        message: message.trim(),
      });
      setState({ loading: false, error: null, success: res.message });
    } catch (err) {
      setState({
        loading: false,
        error: err instanceof Error ? err.message : "Something went wrong.",
        success: null,
      });
    }
  };

  return (
    <ModalShell
      open={open}
      onClose={handleClose}
      title="Contact Us"
      subtitle="We reply within one business day."
    >
      {state.success ? (
        <SuccessPanel message={state.success} onClose={handleClose} />
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid sm:grid-cols-2 gap-4">
            <Field
              id="contact-name"
              label="Full Name"
              icon={<User className="w-4 h-4 text-[#0b6e3e]" />}
              required
              placeholder="John Smith"
              value={name}
              onChange={setName}
              autoComplete="name"
            />
            <Field
              id="contact-email"
              label="Email"
              icon={<Mail className="w-4 h-4 text-[#0b6e3e]" />}
              required
              type="email"
              placeholder="you@example.com"
              value={email}
              onChange={setEmail}
              autoComplete="email"
            />
          </div>
          <div className="grid sm:grid-cols-2 gap-4">
            <Field
              id="contact-phone"
              label="Phone"
              icon={<Phone className="w-4 h-4 text-[#0b6e3e]" />}
              type="tel"
              placeholder="+966 ..."
              value={phone}
              onChange={setPhone}
              autoComplete="tel"
            />
            <Field
              id="contact-subject"
              label="Subject"
              icon={<Tag className="w-4 h-4 text-[#0b6e3e]" />}
              placeholder="How can we help?"
              value={subject}
              onChange={setSubject}
            />
          </div>
          <Field
            id="contact-message"
            label="Message"
            icon={<MessageSquare className="w-4 h-4 text-[#0b6e3e]" />}
            required
            textarea
            placeholder="Tell us a bit about your project or question..."
            value={message}
            onChange={setMessage}
          />

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

          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={handleClose}
              className="px-5 py-2.5 rounded-md border border-slate-200 text-slate-700 font-semibold hover:bg-slate-50 transition"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={state.loading}
              className="px-6 py-2.5 rounded-md bg-[#0b6e3e] text-white font-bold hover:bg-[#0a8048] transition disabled:opacity-70 disabled:cursor-not-allowed inline-flex items-center justify-center gap-2"
            >
              {state.loading && <Loader2 className="w-4 h-4 animate-spin" />}
              {state.loading ? "Sending..." : "Send Message"}
            </button>
          </div>
        </form>
      )}
    </ModalShell>
  );
}

/* ------------------------------------------------------------------ */
/* Get Prices modal                                                    */
/* ------------------------------------------------------------------ */
const SERVICE_OPTIONS = [
  "Cloud VPS",
  "Virtual Dedicated (VDS)",
  "Dedicated Server",
  "Shared Hosting",
  "Business Email",
  "SD-WAN",
  "Managed IT",
  "Domain Registration",
  "Other",
];

export function GetPriceModal({
  open,
  onClose,
  prefillMessage,
  prefillService,
}: {
  open: boolean;
  onClose: () => void;
  prefillMessage?: string;
  prefillService?: string;
}) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [company, setCompany] = useState("");
  const [service, setService] = useState(prefillService || SERVICE_OPTIONS[0]);
  const [message, setMessage] = useState(prefillMessage || "");
  const [state, setState] = useState<SubmitState>(initialSubmitState);

  // When the modal opens with new prefill values, sync them into local state
  // so callers can open the modal multiple times with different contexts
  // (e.g., different compare-drawer selections).
  useEffect(() => {
    if (open) {
      if (prefillMessage !== undefined) setMessage(prefillMessage);
      if (prefillService !== undefined) setService(prefillService);
    }
  }, [open, prefillMessage, prefillService]);

  const reset = () => {
    setName("");
    setEmail("");
    setPhone("");
    setCompany("");
    setService(SERVICE_OPTIONS[0]);
    setMessage("");
    setState(initialSubmitState);
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (state.loading) return;
    setState({ loading: true, error: null, success: null });
    try {
      const res = await submitGetPriceForm({
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim() || undefined,
        company: company.trim() || undefined,
        service: service || undefined,
        message: message.trim() || undefined,
      });
      setState({ loading: false, error: null, success: res.message });
    } catch (err) {
      setState({
        loading: false,
        error: err instanceof Error ? err.message : "Something went wrong.",
        success: null,
      });
    }
  };

  return (
    <ModalShell
      open={open}
      onClose={handleClose}
      title="Get a Personalized Quote"
      subtitle="Tell us what you need — our sales team will reply with the best pricing."
    >
      {state.success ? (
        <SuccessPanel message={state.success} onClose={handleClose} />
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid sm:grid-cols-2 gap-4">
            <Field
              id="price-name"
              label="Full Name"
              icon={<User className="w-4 h-4 text-[#0b6e3e]" />}
              required
              placeholder="John Smith"
              value={name}
              onChange={setName}
              autoComplete="name"
            />
            <Field
              id="price-email"
              label="Business Email"
              icon={<Mail className="w-4 h-4 text-[#0b6e3e]" />}
              required
              type="email"
              placeholder="you@company.com"
              value={email}
              onChange={setEmail}
              autoComplete="email"
            />
          </div>
          <div className="grid sm:grid-cols-2 gap-4">
            <Field
              id="price-phone"
              label="Phone"
              icon={<Phone className="w-4 h-4 text-[#0b6e3e]" />}
              type="tel"
              placeholder="+966 ..."
              value={phone}
              onChange={setPhone}
              autoComplete="tel"
            />
            <Field
              id="price-company"
              label="Company"
              icon={<Building2 className="w-4 h-4 text-[#0b6e3e]" />}
              placeholder="Your company"
              value={company}
              onChange={setCompany}
              autoComplete="organization"
            />
          </div>

          <div>
            <label htmlFor="price-service" className="flex items-center gap-2 text-sm font-semibold text-slate-800 mb-1.5">
              <Tag className="w-4 h-4 text-[#0b6e3e]" />
              Service of Interest
              <span className="text-red-500">*</span>
            </label>
            <select
              id="price-service"
              name="price-service"
              required
              value={service}
              onChange={(e) => setService(e.target.value)}
              className="w-full rounded-xl border border-slate-200 bg-white px-4 py-2.5 text-slate-900 outline-none transition focus:border-[#0b6e3e] focus:ring-2 focus:ring-[#0b6e3e]/20"
            >
              {SERVICE_OPTIONS.map((opt) => (
                <option key={opt} value={opt}>
                  {opt}
                </option>
              ))}
            </select>
          </div>

          <Field
            id="price-message"
            label="Project Details"
            icon={<MessageSquare className="w-4 h-4 text-[#0b6e3e]" />}
            textarea
            placeholder="Tell us about your workload, expected traffic, or any special requirements..."
            value={message}
            onChange={setMessage}
          />

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

          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={handleClose}
              className="px-5 py-2.5 rounded-md border border-slate-200 text-slate-700 font-semibold hover:bg-slate-50 transition"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={state.loading}
              className="px-6 py-2.5 rounded-md bg-[#f5c400] text-slate-900 font-bold hover:bg-yellow-400 transition disabled:opacity-70 disabled:cursor-not-allowed inline-flex items-center justify-center gap-2"
            >
              {state.loading && <Loader2 className="w-4 h-4 animate-spin" />}
              {state.loading ? "Sending..." : "Request Quote"}
            </button>
          </div>
        </form>
      )}
    </ModalShell>
  );
}

/* ------------------------------------------------------------------ */
/* Support modal                                                       */
/* ------------------------------------------------------------------ */
export function SupportModal({ open, onClose }: { open: boolean; onClose: () => void }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [subject, setSubject] = useState("");
  const [message, setMessage] = useState("");
  const [state, setState] = useState<SubmitState>(initialSubmitState);

  const reset = () => {
    setName("");
    setEmail("");
    setPhone("");
    setSubject("");
    setMessage("");
    setState(initialSubmitState);
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (state.loading) return;
    setState({ loading: true, error: null, success: null });
    try {
      const res = await submitSupportForm({
        name: name.trim(),
        email: email.trim(),
        phone: phone.trim() || undefined,
        subject: subject.trim() || undefined,
        message: message.trim(),
      });
      setState({ loading: false, error: null, success: res.message });
    } catch (err) {
      setState({
        loading: false,
        error: err instanceof Error ? err.message : "Something went wrong.",
        success: null,
      });
    }
  };

  return (
    <ModalShell
      open={open}
      onClose={handleClose}
      title="Contact Support"
      subtitle="For account-specific issues, please also open a ticket from your client portal."
    >
      {state.success ? (
        <SuccessPanel message={state.success} onClose={handleClose} />
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid sm:grid-cols-2 gap-4">
            <Field
              id="support-name"
              label="Full Name"
              icon={<User className="w-4 h-4 text-[#0b6e3e]" />}
              required
              placeholder="John Smith"
              value={name}
              onChange={setName}
              autoComplete="name"
            />
            <Field
              id="support-email"
              label="Email"
              icon={<Mail className="w-4 h-4 text-[#0b6e3e]" />}
              required
              type="email"
              placeholder="you@example.com"
              value={email}
              onChange={setEmail}
              autoComplete="email"
            />
          </div>
          <div className="grid sm:grid-cols-2 gap-4">
            <Field
              id="support-phone"
              label="Phone"
              icon={<Phone className="w-4 h-4 text-[#0b6e3e]" />}
              type="tel"
              placeholder="+966 ..."
              value={phone}
              onChange={setPhone}
              autoComplete="tel"
            />
            <Field
              id="support-subject"
              label="Subject"
              icon={<Tag className="w-4 h-4 text-[#0b6e3e]" />}
              placeholder="Short summary"
              value={subject}
              onChange={setSubject}
            />
          </div>
          <Field
            id="support-message"
            label="How can we help?"
            icon={<MessageSquare className="w-4 h-4 text-[#0b6e3e]" />}
            required
            textarea
            placeholder="Describe the issue in as much detail as possible..."
            value={message}
            onChange={setMessage}
          />

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

          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={handleClose}
              className="px-5 py-2.5 rounded-md border border-slate-200 text-slate-700 font-semibold hover:bg-slate-50 transition"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={state.loading}
              className="px-6 py-2.5 rounded-md bg-[#0b6e3e] text-white font-bold hover:bg-[#0a8048] transition disabled:opacity-70 disabled:cursor-not-allowed inline-flex items-center justify-center gap-2"
            >
              {state.loading && <Loader2 className="w-4 h-4 animate-spin" />}
              {state.loading ? "Sending..." : "Send Request"}
            </button>
          </div>
        </form>
      )}
    </ModalShell>
  );
}