"use client";

import * as React from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Bot,
  X,
  Send,
  Phone,
  Calendar,
  MessageCircle,
  Mail,
  Check,
  ChevronRight,
  Clock,
} from "lucide-react";
import { services, founders, company } from "@/lib/content";
import { cn } from "@/lib/utils";
import {
  TimeSlotPicker,
  type TimeSlot,
} from "@/components/ui-stratops/time-slot-picker";

type ChatMessage = {
  role: "user" | "assistant";
  content: string;
  slots?: boolean; // if true, render TimeSlotPicker inline
};

type ModalMode = "callback" | "capture" | null;

const QUICK_ACTIONS = [
  { label: "Request callback", icon: Phone, action: "callback" as const },
  { label: "Book meeting", icon: Calendar, action: "schedule" as const },
  { label: "Get in touch", icon: Mail, action: "capture" as const },
  { label: "WhatsApp", icon: MessageCircle, action: "whatsapp" as const },
];

const GREETING = `Welcome to ${company.shortName} Advisory Group. I am Thabo, Head of Sales and Marketing. I would love to understand your business needs — what challenge is your organisation currently facing?`;

export function AIChatWidget() {
  const [open, setOpen] = React.useState(false);
  const [messages, setMessages] = React.useState<ChatMessage[]>([
    { role: "assistant", content: GREETING },
  ]);
  const [input, setInput] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [modalMode, setModalMode] = React.useState<ModalMode>(null);
  const [pickedSlot, setPickedSlot] = React.useState<TimeSlot | null>(null);
  const [awaitingDetails, setAwaitingDetails] = React.useState(false);
  const scrollRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, loading]);

  const send = async (text?: string) => {
    const content = (text ?? input).trim();
    if (!content || loading) return;
    const newMessages: ChatMessage[] = [
      ...messages,
      { role: "user", content },
    ];
    setMessages(newMessages);
    setInput("");
    setLoading(true);

    try {
      const res = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message: content,
          history: messages.map((m) => ({ role: m.role, content: m.content })),
        }),
      });
      const data = await res.json();
      const reply = data.reply ?? "I apologise, I did not catch that. Could you rephrase?";
      setMessages((m) => [...m, { role: "assistant", content: reply }]);

      // Handle action
      if (data.action === "REQUEST_CALLBACK") {
        setTimeout(() => setModalMode("callback"), 800);
      } else if (data.action === "SCHEDULE_MEETING") {
        // Show inline time slot picker instead of modal
        setTimeout(() => {
          setMessages((m) => [
            ...m,
            {
              role: "assistant",
              content:
                "I'd love to set up a discovery session for you. Here are the available slots over the next few business days — pick whichever works best:",
              slots: true,
            },
          ]);
        }, 800);
      } else if (data.action === "CAPTURE_LEAD") {
        setTimeout(() => setModalMode("capture"), 800);
      } else if (data.action === "WHATSAPP_REDIRECT") {
        const wa = `https://wa.me/${founders[0].phone.replace(/\D/g, "")}?text=${encodeURIComponent(
          "Hello StratOps, I would like to schedule a discovery session.",
        )}`;
        window.open(wa, "_blank", "noopener,noreferrer");
      }
    } catch {
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          content:
            "I am having trouble connecting right now. You can email us at " +
            company.primaryEmail +
            " or leave your details and a founder will respond within one business day.",
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleSlotPick = (slot: TimeSlot) => {
    setPickedSlot(slot);
    setMessages((m) => [
      ...m,
      { role: "user", content: `I'd like to book ${slot.label} SAST.` },
    ]);
    setTimeout(() => {
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          content: `Excellent — ${slot.label} SAST is provisionally yours. To confirm, could you share your name and email so a founder can send the calendar invite?`,
        },
      ]);
      setAwaitingDetails(true);
    }, 600);
  };

  const handleDetailsSubmit = async () => {
    const text = input.trim();
    if (!text || loading) return;

    // The user is providing their name/email after picking a slot
    setMessages((m) => [...m, { role: "user", content: text }]);
    setInput("");

    // Try to extract email from the message
    const emailMatch = text.match(/[\w.+-]+@[\w-]+\.[\w.-]+/);
    const email = emailMatch?.[0] ?? "";
    const name = text.replace(email, "").replace(/[,;]/g, "").trim() || "Prospect";

    if (!pickedSlot) return;

    setLoading(true);
    try {
      await fetch("/api/leads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          email,
          phone: "",
          company: "",
          serviceInterest: "",
          message: `Meeting requested for ${pickedSlot.label} SAST via chat with Thabo.`,
          callbackRequested: false,
          meetingRequested: true,
          meetingDate: `${pickedSlot.date}T${pickedSlot.time}:00`,
          chatTranscript: messages
            .map((m) => `${m.role}: ${m.content}`)
            .join("\n"),
        }),
      });
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          content: `Thank you, ${name.split(" ")[0]}. Your discovery session is confirmed for ${pickedSlot.label} SAST. A founder will send you a calendar invite within the next few hours. Is there anything else you'd like to prepare for the session?`,
        },
      ]);
      setAwaitingDetails(false);
      setPickedSlot(null);
    } catch {
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          content: `Thank you, ${name.split(" ")[0]}. I've noted your request for ${pickedSlot.label} SAST. A founder will confirm shortly — or you can reach them directly on WhatsApp.`,
        },
      ]);
      setAwaitingDetails(false);
      setPickedSlot(null);
    } finally {
      setLoading(false);
    }
  };

  const handleQuickAction = (action: string) => {
    if (action === "whatsapp") {
      window.open(
        `https://wa.me/${founders[0].phone.replace(/\D/g, "")}?text=${encodeURIComponent(
          "Hello StratOps, I would like to enquire about your consulting services.",
        )}`,
        "_blank",
        "noopener,noreferrer",
      );
      return;
    }
    if (action === "schedule") {
      // Trigger inline scheduling
      setMessages((m) => [
        ...m,
        {
          role: "user",
          content: "I'd like to book a meeting.",
        },
        {
          role: "assistant",
          content:
            "Absolutely. Here are the available discovery session slots — pick one and I'll get it confirmed:",
          slots: true,
        },
      ]);
      return;
    }
    setModalMode(action as ModalMode);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (awaitingDetails && pickedSlot) {
      handleDetailsSubmit();
    } else {
      send();
    }
  };

  return (
    <>
      {/* Floating button */}
      <div className="fixed bottom-5 right-5 z-[55] flex flex-col items-end gap-3 sm:bottom-6 sm:right-6">
        <AnimatePresence>
          {open && (
            <motion.div
              initial={{ opacity: 0, y: 20, scale: 0.95 }}
              animate={{ opacity: 1, y: 0, scale: 1 }}
              exit={{ opacity: 0, y: 20, scale: 0.95 }}
              transition={{ type: "spring", stiffness: 320, damping: 28 }}
              className="flex h-[600px] w-[min(390px,calc(100vw-2.5rem))] flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-[0_24px_80px_-20px_rgba(0,0,0,0.7)]"
            >
              {/* Header */}
              <div className="flex items-center justify-between border-b border-border/60 bg-gradient-to-r from-brand-deep to-brand px-4 py-3">
                <div className="flex items-center gap-3">
                  <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-background/20 backdrop-blur-sm ring-1 ring-white/20">
                    <Bot className="h-5 w-5 text-foreground" />
                  </span>
                  <div className="leading-tight">
                    <p className="text-sm font-semibold text-foreground">
                      Thabo Mokoena
                    </p>
                    <p className="flex items-center gap-1.5 text-[11px] text-foreground/70">
                      <span className="relative flex h-2 w-2">
                        <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-60" />
                        <span className="relative inline-flex h-2 w-2 rounded-full bg-green-400" />
                      </span>
                      Head of Sales · Online
                    </p>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => setOpen(false)}
                  className="inline-flex h-8 w-8 items-center justify-center rounded-full text-foreground/70 transition-colors hover:bg-white/10 hover:text-foreground"
                  aria-label="Close chat"
                >
                  <X className="h-4 w-4" />
                </button>
              </div>

              {/* Messages */}
              <div
                ref={scrollRef}
                className="flex-1 space-y-3 overflow-y-auto bg-background/40 p-4"
              >
                {messages.map((msg, i) => (
                  <motion.div
                    key={i}
                    initial={{ opacity: 0, y: 8 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.3 }}
                    className={cn(
                      "flex flex-col",
                      msg.role === "user" ? "items-end" : "items-start",
                    )}
                  >
                    {msg.content && (
                      <div
                        className={cn(
                          "max-w-[88%] rounded-2xl px-3.5 py-2.5 text-sm leading-relaxed",
                          msg.role === "user"
                            ? "rounded-br-sm bg-brand text-background"
                            : "rounded-bl-sm bg-muted text-foreground",
                        )}
                      >
                        {msg.content}
                      </div>
                    )}
                    {msg.slots && (
                      <div className="max-w-[92%] w-full">
                        <TimeSlotPicker
                          onPick={handleSlotPick}
                          pickedSlot={pickedSlot}
                        />
                      </div>
                    )}
                  </motion.div>
                ))}
                {loading && (
                  <div className="flex justify-start">
                    <div className="flex items-center gap-1 rounded-2xl rounded-bl-sm bg-muted px-4 py-3">
                      {[0, 1, 2].map((d) => (
                        <motion.span
                          key={d}
                          className="h-1.5 w-1.5 rounded-full bg-brand"
                          animate={{ opacity: [0.3, 1, 0.3], y: [0, -3, 0] }}
                          transition={{
                            duration: 0.9,
                            repeat: Infinity,
                            delay: d * 0.15,
                          }}
                        />
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {/* Awaiting details hint */}
              {awaitingDetails && pickedSlot && (
                <div className="border-t border-border/60 bg-gold/5 px-4 py-2">
                  <div className="flex items-center gap-2 text-[11px] text-gold">
                    <Clock className="h-3 w-3" />
                    <span>
                      Slot held: <strong>{pickedSlot.label} SAST</strong> —
                      share your name &amp; email to confirm
                    </span>
                  </div>
                </div>
              )}

              {/* Quick actions */}
              <div className="flex gap-1.5 overflow-x-auto border-t border-border/60 bg-card/60 px-3 py-2">
                {QUICK_ACTIONS.map((qa) => (
                  <button
                    key={qa.action}
                    type="button"
                    onClick={() => handleQuickAction(qa.action)}
                    className="flex flex-shrink-0 items-center gap-1.5 rounded-full border border-border/60 bg-background/40 px-2.5 py-1.5 text-[11px] font-medium text-foreground/80 transition-colors hover:border-gold/50 hover:bg-gold/5 hover:text-gold"
                  >
                    <qa.icon className="h-3 w-3" />
                    {qa.label}
                  </button>
                ))}
              </div>

              {/* Input */}
              <form
                onSubmit={handleSubmit}
                className="flex items-center gap-2 border-t border-border/60 bg-card p-3"
              >
                <input
                  type="text"
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  placeholder={
                    awaitingDetails
                      ? "Your name and email…"
                      : "Ask Thabo anything…"
                  }
                  className="flex-1 rounded-full border border-border bg-background/60 px-4 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-brand/50 focus:outline-none focus:ring-2 focus:ring-brand/20"
                />
                <button
                  type="submit"
                  disabled={!input.trim() || loading}
                  className={cn(
                    "flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full transition-colors",
                    input.trim() && !loading
                      ? "bg-brand text-background hover:bg-brand-soft"
                      : "cursor-not-allowed bg-muted text-muted-foreground",
                  )}
                  aria-label="Send message"
                >
                  <Send className="h-4 w-4" />
                </button>
              </form>
            </motion.div>
          )}
        </AnimatePresence>

        <motion.button
          type="button"
          onClick={() => setOpen((o) => !o)}
          initial={{ scale: 0, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ delay: 1.5, type: "spring", stiffness: 260, damping: 18 }}
          whileHover={{ scale: 1.06 }}
          whileTap={{ scale: 0.94 }}
          className="relative flex h-14 w-14 items-center justify-center rounded-full bg-gradient-to-br from-brand to-brand-soft shadow-[0_10px_30px_-8px_var(--brand)]"
          aria-label={open ? "Close chat" : "Open chat with Thabo"}
        >
          {open ? (
            <X className="h-6 w-6 text-background" />
          ) : (
            <>
              <Bot className="h-6 w-6 text-background" />
              <span className="absolute -right-0.5 -top-0.5 flex h-3.5 w-3.5">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-brand opacity-60" />
                <span className="relative inline-flex h-3.5 w-3.5 rounded-full bg-brand ring-2 ring-card" />
              </span>
            </>
          )}
        </motion.button>
      </div>

      {/* Lead capture modal (for callback / get in touch) */}
      <LeadModal
        mode={modalMode}
        onClose={() => setModalMode(null)}
        onSubmit={async (data) => {
          try {
            await fetch("/api/leads", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                ...data,
                callbackRequested: modalMode === "callback",
                meetingRequested: false,
                chatTranscript: messages
                  .map((m) => `${m.role}: ${m.content}`)
                  .join("\n"),
              }),
            });
            setMessages((m) => [
              ...m,
              {
                role: "assistant",
                content: `Thank you, ${data.name.split(" ")[0]}. A founder will reach out to you directly within one business day.`,
              },
            ]);
          } catch {
            // Lead capture failed, but still show success
          }
        }}
      />
    </>
  );
}

function LeadModal({
  mode,
  onClose,
  onSubmit,
}: {
  mode: ModalMode;
  onClose: () => void;
  onSubmit: (data: {
    name: string;
    email: string;
    phone: string;
    company: string;
    serviceInterest: string;
    message: string;
  }) => void;
}) {
  const [form, setForm] = React.useState({
    name: "",
    email: "",
    phone: "",
    company: "",
    serviceInterest: "",
    message: "",
  });
  const [submitted, setSubmitted] = React.useState(false);

  const title =
    mode === "callback" ? "Request a callback" : "Get in touch";

  React.useEffect(() => {
    if (mode) {
      setForm({
        name: "",
        email: "",
        phone: "",
        company: "",
        serviceInterest: "",
        message: "",
      });
      setSubmitted(false);
    }
  }, [mode]);

  return (
    <AnimatePresence>
      {mode && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-[65] flex items-end justify-center p-0 sm:items-center sm:p-6"
          role="dialog"
          aria-modal="true"
          aria-label={title}
        >
          <div
            className="absolute inset-0 bg-background/70 backdrop-blur-sm"
            onClick={onClose}
          />
          <motion.div
            initial={{ y: 60, opacity: 0, scale: 0.96 }}
            animate={{ y: 0, opacity: 1, scale: 1 }}
            exit={{ y: 30, opacity: 0, scale: 0.96 }}
            transition={{ type: "spring", stiffness: 320, damping: 30 }}
            className="relative max-h-[88svh] w-full max-w-md overflow-y-auto rounded-t-3xl border border-border bg-card p-6 shadow-2xl sm:rounded-3xl"
          >
            <button
              type="button"
              onClick={onClose}
              className="absolute right-4 top-4 inline-flex h-9 w-9 items-center justify-center rounded-full border border-border/60 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
              aria-label="Close"
            >
              <X className="h-4 w-4" />
            </button>

            {submitted ? (
              <div className="flex flex-col items-center gap-4 py-10 text-center">
                <span className="flex h-16 w-16 items-center justify-center rounded-full bg-success/15 text-success">
                  <Check className="h-8 w-8" strokeWidth={2.4} />
                </span>
                <h3 className="font-display text-2xl font-semibold text-foreground">
                  Thank you
                </h3>
                <p className="max-w-xs text-sm leading-relaxed text-muted-foreground">
                  Your request has been logged. One of our founders will respond
                  within one business day.
                </p>
                <button
                  type="button"
                  onClick={onClose}
                  className="mt-2 rounded-full border border-border px-5 py-2.5 text-sm font-semibold text-foreground transition-colors hover:bg-muted"
                >
                  Close
                </button>
              </div>
            ) : (
              <>
                <div className="mb-5">
                  <p className="font-mono-num text-[10px] uppercase tracking-[0.24em] text-gold">
                    Thabo · StratOps
                  </p>
                  <h3 className="mt-1 font-display text-2xl font-semibold text-foreground">
                    {title}
                  </h3>
                  <p className="mt-1 text-sm text-muted-foreground">
                    Leave your details and a founder will respond within one
                    business day.
                  </p>
                </div>
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    onSubmit(form);
                    setSubmitted(true);
                  }}
                  className="flex flex-col gap-3"
                >
                  <LeadField
                    label="Full name"
                    required
                    value={form.name}
                    onChange={(v) => setForm({ ...form, name: v })}
                    placeholder="Your name"
                  />
                  <div className="grid grid-cols-2 gap-3">
                    <LeadField
                      label="Email"
                      type="email"
                      required
                      value={form.email}
                      onChange={(v) => setForm({ ...form, email: v })}
                      placeholder="name@company.co.za"
                    />
                    <LeadField
                      label="Phone"
                      type="tel"
                      value={form.phone}
                      onChange={(v) => setForm({ ...form, phone: v })}
                      placeholder="+27 ..."
                    />
                  </div>
                  <LeadField
                    label="Organisation"
                    value={form.company}
                    onChange={(v) => setForm({ ...form, company: v })}
                    placeholder="Company name"
                  />
                  <label className="flex flex-col gap-1.5">
                    <span className="text-sm font-medium text-foreground">
                      Service of interest
                    </span>
                    <select
                      value={form.serviceInterest}
                      onChange={(e) =>
                        setForm({ ...form, serviceInterest: e.target.value })
                      }
                      className="rounded-xl border border-border bg-background/60 px-3 py-2.5 text-sm text-foreground focus:border-brand/50 focus:outline-none focus:ring-2 focus:ring-brand/20"
                    >
                      <option value="">Select a service</option>
                      {services.map((s) => (
                        <option key={s.id} value={s.title}>
                          {s.title}
                        </option>
                      ))}
                      <option value="General Enquiry">General Enquiry</option>
                    </select>
                  </label>
                  <label className="flex flex-col gap-1.5">
                    <span className="text-sm font-medium text-foreground">
                      Message (optional)
                    </span>
                    <textarea
                      rows={3}
                      value={form.message}
                      onChange={(e) =>
                        setForm({ ...form, message: e.target.value })
                      }
                      placeholder="Brief context on your situation…"
                      className="resize-none rounded-xl border border-border bg-background/60 px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-brand/50 focus:outline-none focus:ring-2 focus:ring-brand/20"
                    />
                  </label>
                  <button
                    type="submit"
                    className="mt-2 inline-flex items-center justify-center gap-2 rounded-full bg-brand px-5 py-3 text-sm font-semibold text-background transition-colors hover:bg-brand-soft"
                  >
                    {mode === "callback" ? "Request callback" : "Send details"}
                    <ChevronRight className="h-4 w-4" />
                  </button>
                  <p className="text-center text-[11px] text-muted-foreground">
                    POPIA-aligned · Your data is only used to contact you
                  </p>
                </form>
              </>
            )}
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}

function LeadField({
  label,
  value,
  onChange,
  placeholder,
  type = "text",
  required,
}: {
  label: string;
  value: string;
  onChange: (v: string) => void;
  placeholder?: string;
  type?: string;
  required?: boolean;
}) {
  return (
    <label className="flex flex-col gap-1.5">
      <span className="flex items-center gap-1 text-sm font-medium text-foreground">
        {label}
        {required && <span className="text-brand">*</span>}
      </span>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        required={required}
        className="rounded-xl border border-border bg-background/60 px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-brand/50 focus:outline-none focus:ring-2 focus:ring-brand/20"
      />
    </label>
  );
}
