"use client";

import * as React from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Bot,
  X,
  Send,
  Calendar,
  MessageCircle,
  Users,
  Check,
  ChevronRight,
  Clock,
} from "lucide-react";
import { worksContent } from "@/lib/works-content";
import { cn } from "@/lib/utils";

type ChatMessage = {
  role: "user" | "assistant";
  content: string;
};

const GREETING = `Hi there! I'm Brandon, your virtual host at The Works. Hungry, thirsty, or looking to book a table? I'm here to help — what can I do for you?`;

const QUICK_ACTIONS = [
  { label: "Book a table", icon: Calendar, action: "book" as const },
  { label: "See menu", icon: Bot, action: "menu" as const },
  { label: "Opening hours", icon: Clock, action: "hours" as const },
  { label: "WhatsApp", icon: MessageCircle, action: "whatsapp" as const },
];

export function WorksChatWidget() {
  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 [showBooking, setShowBooking] = React.useState(false);
  const [booking, setBooking] = React.useState({
    name: "",
    phone: "",
    date: "",
    time: "",
    guests: "2",
  });
  const [bookingDone, setBookingDone] = React.useState(false);
  const scrollRef = React.useRef<HTMLDivElement>(null);

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

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

    try {
      const res = await fetch("/api/works-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 ?? "Sorry, I didn't catch that. Could you rephrase?";
      setMessages((m) => [...m, { role: "assistant", content: reply }]);

      if (data.action === "BOOK_TABLE") {
        setTimeout(() => setShowBooking(true), 800);
      } else if (data.action === "WHATSAPP_REDIRECT") {
        const wa = `https://wa.me/${worksContent.phoneE164}?text=${encodeURIComponent(
          "Hi The Works, I'd like to enquire about a booking.",
        )}`;
        window.open(wa, "_blank", "noopener,noreferrer");
      }
    } catch {
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          content: `I'm having trouble right now. Give us a call on ${worksContent.phone} and we'll sort you out.`,
        },
      ]);
    } finally {
      setLoading(false);
    }
  };

  const handleQuickAction = (action: string) => {
    if (action === "whatsapp") {
      window.open(
        `https://wa.me/${worksContent.phoneE164}?text=${encodeURIComponent(
          "Hi The Works, I'd like to enquire about a booking.",
        )}`,
        "_blank",
        "noopener,noreferrer",
      );
      return;
    }
    if (action === "menu") {
      send("What's on your menu?");
      return;
    }
    if (action === "hours") {
      send("What are your opening hours?");
      return;
    }
    if (action === "book") {
      setShowBooking(true);
    }
  };

  const submitBooking = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      await fetch("/api/works-leads", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...booking,
          bookingType: "Table booking",
          message: `Table for ${booking.guests} on ${booking.date} at ${booking.time}`,
          chatTranscript: messages.map((m) => `${m.role}: ${m.content}`).join("\n"),
        }),
      });
      setBookingDone(true);
      setMessages((m) => [
        ...m,
        {
          role: "assistant",
          content: `Great news, ${booking.name.split(" ")[0]}! Your table for ${booking.guests} on ${booking.date} at ${booking.time} is confirmed. We can't wait to host you. Anything else I can help with?`,
        },
      ]);
    } catch {
      setBookingDone(true);
    }
  };

  const today = new Date().toISOString().split("T")[0];
  const times = ["12:00", "13:00", "14:00", "18:00", "19:00", "20:00", "21:00"];

  return (
    <>
      <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 — amber theme */}
              <div className="flex items-center justify-between border-b border-border/60 bg-gradient-to-r from-amber-700 to-amber-500 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-white" />
                  </span>
                  <div className="leading-tight">
                    <p className="text-sm font-semibold text-white">Brandon</p>
                    <p className="flex items-center gap-1.5 text-[11px] text-white/80">
                      <span className="relative flex h-2 w-2">
                        <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-300 opacity-60" />
                        <span className="relative inline-flex h-2 w-2 rounded-full bg-green-300" />
                      </span>
                      Virtual Host · Online
                    </p>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => setOpen(false)}
                  className="inline-flex h-8 w-8 items-center justify-center rounded-full text-white/80 transition-colors hover:bg-white/15 hover:text-white"
                  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",
                      msg.role === "user" ? "justify-end" : "justify-start",
                    )}
                  >
                    <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-amber-600 text-white"
                          : "rounded-bl-sm bg-muted text-foreground",
                      )}
                    >
                      {msg.content}
                    </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-amber-600"
                          animate={{ opacity: [0.3, 1, 0.3], y: [0, -3, 0] }}
                          transition={{
                            duration: 0.9,
                            repeat: Infinity,
                            delay: d * 0.15,
                          }}
                        />
                      ))}
                    </div>
                  </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-amber-500/50 hover:bg-amber-500/5 hover:text-amber-600"
                  >
                    <qa.icon className="h-3 w-3" />
                    {qa.label}
                  </button>
                ))}
              </div>

              {/* Input */}
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  send();
                }}
                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="Ask Brandon 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-amber-500/50 focus:outline-none focus:ring-2 focus:ring-amber-500/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-amber-600 text-white hover:bg-amber-500"
                      : "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-amber-600 to-amber-500 shadow-[0_10px_30px_-8px_rgba(217,119,6,0.6)]"
          aria-label={open ? "Close chat" : "Open chat with Brandon"}
        >
          {open ? (
            <X className="h-6 w-6 text-white" />
          ) : (
            <>
              <Bot className="h-6 w-6 text-white" />
              <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-amber-400 opacity-60" />
                <span className="relative inline-flex h-3.5 w-3.5 rounded-full bg-amber-400 ring-2 ring-card" />
              </span>
            </>
          )}
        </motion.button>
      </div>

      {/* Booking modal */}
      <AnimatePresence>
        {showBooking && (
          <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="Book a table"
          >
            <div
              className="absolute inset-0 bg-background/70 backdrop-blur-sm"
              onClick={() => {
                setShowBooking(false);
                setBookingDone(false);
              }}
            />
            <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={() => {
                  setShowBooking(false);
                  setBookingDone(false);
                }}
                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>

              {bookingDone ? (
                <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-green-500/15 text-green-600">
                    <Check className="h-8 w-8" strokeWidth={2.4} />
                  </span>
                  <h3 className="font-display text-2xl font-semibold text-foreground">
                    Table booked!
                  </h3>
                  <p className="max-w-xs text-sm leading-relaxed text-muted-foreground">
                    See you on {booking.date} at {booking.time}, {booking.name.split(" ")[0]}.
                    We&apos;ll send a confirmation shortly.
                  </p>
                  <button
                    type="button"
                    onClick={() => {
                      setShowBooking(false);
                      setBookingDone(false);
                    }}
                    className="mt-2 rounded-full border border-border px-5 py-2.5 text-sm font-semibold text-foreground transition-colors hover:bg-muted"
                  >
                    Done
                  </button>
                </div>
              ) : (
                <>
                  <div className="mb-5">
                    <p className="font-mono-num text-[10px] uppercase tracking-[0.24em] text-amber-600">
                      Brandon · The Works
                    </p>
                    <h3 className="mt-1 font-display text-2xl font-semibold text-foreground">
                      Book a table
                    </h3>
                  </div>
                  <form onSubmit={submitBooking} className="flex flex-col gap-3">
                    <BookingField
                      label="Your name"
                      required
                      value={booking.name}
                      onChange={(v) => setBooking({ ...booking, name: v })}
                      placeholder="e.g. Sipho Dlamini"
                    />
                    <BookingField
                      label="Phone"
                      type="tel"
                      required
                      value={booking.phone}
                      onChange={(v) => setBooking({ ...booking, phone: v })}
                      placeholder="+27 ..."
                    />
                    <div className="grid grid-cols-2 gap-3">
                      <label className="flex flex-col gap-1.5">
                        <span className="text-sm font-medium text-foreground">Date</span>
                        <input
                          type="date"
                          min={today}
                          required
                          value={booking.date}
                          onChange={(e) => setBooking({ ...booking, date: e.target.value })}
                          className="rounded-xl border border-border bg-background/60 px-3 py-2.5 text-sm text-foreground focus:border-amber-500/50 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                        />
                      </label>
                      <label className="flex flex-col gap-1.5">
                        <span className="text-sm font-medium text-foreground">Time</span>
                        <select
                          required
                          value={booking.time}
                          onChange={(e) => setBooking({ ...booking, time: e.target.value })}
                          className="rounded-xl border border-border bg-background/60 px-3 py-2.5 text-sm text-foreground focus:border-amber-500/50 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                        >
                          <option value="">Select</option>
                          {times.map((t) => (
                            <option key={t} value={t}>{t}</option>
                          ))}
                        </select>
                      </label>
                    </div>
                    <label className="flex flex-col gap-1.5">
                      <span className="flex items-center gap-1.5 text-sm font-medium text-foreground">
                        <Users className="h-3.5 w-3.5 text-amber-600" />
                        Guests
                      </span>
                      <select
                        value={booking.guests}
                        onChange={(e) => setBooking({ ...booking, guests: e.target.value })}
                        className="rounded-xl border border-border bg-background/60 px-3 py-2.5 text-sm text-foreground focus:border-amber-500/50 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                      >
                        {["1", "2", "3", "4", "5", "6", "7", "8", "8+"].map((n) => (
                          <option key={n} value={n}>{n} {n === "1" ? "guest" : "guests"}</option>
                        ))}
                      </select>
                    </label>
                    <button
                      type="submit"
                      className="mt-2 inline-flex items-center justify-center gap-2 rounded-full bg-amber-600 px-5 py-3 text-sm font-semibold text-white transition-colors hover:bg-amber-500"
                    >
                      Confirm booking
                      <ChevronRight className="h-4 w-4" />
                    </button>
                  </form>
                </>
              )}
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}

function BookingField({
  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-amber-600">*</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-amber-500/50 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
      />
    </label>
  );
}
