"use client"

import { useCallback, useEffect, useRef, useState } from "react"
import { Input } from "@/components/ui/input"
import { Send } from "lucide-react"
import { cn } from "@/lib/utils"
import { AGENT } from "@/lib/agent-brand"

type Chat = {
  id: string
  fullName: string
  email: string
  phone: string
  topic: string
}

type Message = {
  id: string
  sender: "visitor" | "admin"
  body: string
  createdAt: string
}

const CHAT_KEY = "agent_calendar_chat_id"

type CalendarMessageChatProps = {
  /** offline = blue gradient page; light = white booking card */
  theme?: "offline" | "light"
  compact?: boolean
}

export function CalendarMessageChat({
  theme = "offline",
  compact = false,
}: CalendarMessageChatProps) {
  const [phase, setPhase] = useState<"form" | "chat">("form")
  const [fullName, setFullName] = useState("")
  const [email, setEmail] = useState("")
  const [phone, setPhone] = useState("")
  const [topic, setTopic] = useState("")
  const [chat, setChat] = useState<Chat | null>(null)
  const [messages, setMessages] = useState<Message[]>([])
  const [draft, setDraft] = useState("")
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const bottomRef = useRef<HTMLDivElement>(null)

  const isOffline = theme === "offline"

  const loadChat = useCallback(async (id: string) => {
    const res = await fetch(`/api/offline-chat?id=${encodeURIComponent(id)}`, {
      cache: "no-store",
    })
    if (!res.ok) return false
    const data = await res.json()
    setChat(data.chat)
    setMessages(data.messages || [])
    setPhase("chat")
    return true
  }, [])

  useEffect(() => {
    const saved = sessionStorage.getItem(CHAT_KEY)
    if (saved) void loadChat(saved)
  }, [loadChat])

  useEffect(() => {
    if (phase !== "chat" || !chat) return
    const id = window.setInterval(() => {
      void loadChat(chat.id)
    }, 3000)
    return () => window.clearInterval(id)
  }, [phase, chat, loadChat])

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" })
  }, [messages.length])

  const startChat = async (e: React.FormEvent) => {
    e.preventDefault()
    setBusy(true)
    setError(null)
    try {
      const res = await fetch("/api/offline-chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "start",
          fullName,
          email,
          phone,
          topic,
        }),
      })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error || "Failed to send")
        return
      }
      sessionStorage.setItem(CHAT_KEY, data.chat.id)
      setChat(data.chat)
      setMessages(data.messages || [])
      setPhase("chat")
    } catch {
      setError("Could not send message. Try again.")
    } finally {
      setBusy(false)
    }
  }

  const sendMessage = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!chat || !draft.trim()) return
    const text = draft.trim()
    setDraft("")
    setBusy(true)
    try {
      const res = await fetch("/api/offline-chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "message",
          chatId: chat.id,
          sender: "visitor",
          body: text,
        }),
      })
      const data = await res.json()
      if (res.ok) setMessages(data.messages || [])
    } finally {
      setBusy(false)
    }
  }

  const fieldClass = isOffline
    ? "h-11 rounded-xl border-white/15 bg-white/10 text-white placeholder:text-white/35 focus-visible:ring-[#067ab4]"
    : "h-10 rounded-lg border-[#dadce0] bg-white text-[#202124] placeholder:text-[#80868b] focus-visible:ring-[#067ab4] text-sm"

  const shellClass = isOffline
    ? "overflow-hidden rounded-2xl bg-white/[0.07] shadow-[0_24px_80px_rgba(0,0,0,0.35)] ring-1 ring-white/15 backdrop-blur-md"
    : "overflow-hidden rounded-xl border border-[#dadce0] bg-white shadow-sm"

  if (phase === "form") {
    return (
      <div className={shellClass}>
        <div
          className={cn(
            "border-b px-5 py-4",
            isOffline ? "border-white/10" : "border-[#edeff2] bg-[#f8f9fa]"
          )}
        >
          <h2
            className={cn(
              "font-semibold tracking-tight",
              isOffline ? "text-xl text-white" : "text-[16px] text-[#202124]"
            )}
          >
            {compact ? `Message ${AGENT.firstName}` : "Leave us a message"}
          </h2>
          <p
            className={cn(
              "mt-1.5 text-sm leading-relaxed",
              isOffline ? "text-white/55" : "text-[#5f6368]"
            )}
          >
            {compact
              ? `Questions about scheduling? ${AGENT.firstName} will get back to you.`
              : "Share your details and we’ll reply when the calendar is back online."}
          </p>
        </div>

        <form onSubmit={startChat} className="space-y-3 px-5 py-4">
          {!compact ? (
            <>
              <div>
                <label
                  className={cn(
                    "mb-1.5 block text-xs font-medium",
                    isOffline ? "text-white/60" : "text-[#5f6368]"
                  )}
                >
                  Full name
                </label>
                <Input
                  required
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  className={fieldClass}
                  placeholder="Jane Doe"
                />
              </div>
              <div>
                <label
                  className={cn(
                    "mb-1.5 block text-xs font-medium",
                    isOffline ? "text-white/60" : "text-[#5f6368]"
                  )}
                >
                  Email
                </label>
                <Input
                  required
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className={fieldClass}
                  placeholder="you@company.com"
                />
              </div>
              <div>
                <label
                  className={cn(
                    "mb-1.5 block text-xs font-medium",
                    isOffline ? "text-white/60" : "text-[#5f6368]"
                  )}
                >
                  Phone <span className="opacity-60">(optional)</span>
                </label>
                <Input
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className={fieldClass}
                  placeholder="+1 555 000 0000"
                />
              </div>
            </>
          ) : (
            <div className="grid gap-3 sm:grid-cols-2">
              <div>
                <label className="mb-1.5 block text-xs font-medium text-[#5f6368]">Name</label>
                <Input
                  required
                  value={fullName}
                  onChange={(e) => setFullName(e.target.value)}
                  className={fieldClass}
                  placeholder="Your name"
                />
              </div>
              <div>
                <label className="mb-1.5 block text-xs font-medium text-[#5f6368]">Email</label>
                <Input
                  required
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  className={fieldClass}
                  placeholder="you@company.com"
                />
              </div>
            </div>
          )}
          <div>
            <label
              className={cn(
                "mb-1.5 block text-xs font-medium",
                isOffline ? "text-white/60" : "text-[#5f6368]"
              )}
            >
              Message
            </label>
            <Input
              required
              value={topic}
              onChange={(e) => setTopic(e.target.value)}
              className={fieldClass}
              placeholder={
                compact
                  ? "I need to reschedule my meeting…"
                  : "Please send me a new scheduling link…"
              }
            />
          </div>
          {error ? (
            <p className={cn("text-sm", isOffline ? "text-rose-300" : "text-red-600")}>{error}</p>
          ) : null}
          <button
            type="submit"
            disabled={busy}
            className={cn(
              "mt-1 flex h-11 w-full items-center justify-center rounded-xl text-sm font-semibold transition disabled:cursor-not-allowed disabled:opacity-60",
              isOffline
                ? "bg-white text-[#067ab4] hover:bg-white/95"
                : "bg-[#067ab4] text-white hover:bg-[#067ab4]"
            )}
          >
            {busy ? "Sending…" : "Send message"}
          </button>
        </form>
      </div>
    )
  }

  return (
    <div className={cn(shellClass, "flex flex-col")}>
      <div
        className={cn(
          "border-b px-5 py-4",
          isOffline ? "border-white/10" : "border-[#edeff2] bg-[#f8f9fa]"
        )}
      >
        <p
          className={cn(
            "text-[11px] font-semibold uppercase tracking-[0.16em]",
            isOffline ? "text-white/60" : "text-[#80868b]"
          )}
        >
          Message sent
        </p>
        <p
          className={cn(
            "mt-1 font-semibold",
            isOffline ? "text-base text-white" : "text-[15px] text-[#202124]"
          )}
        >
          {chat?.fullName}
        </p>
        <p className={cn("text-xs", isOffline ? "text-white/45" : "text-[#5f6368]")}>
          {chat?.email}
        </p>
        <p className={cn("mt-2 text-sm", isOffline ? "text-white/55" : "text-[#5f6368]")}>
          {AGENT.firstName} will reply here — keep this page open or come back later.
        </p>
      </div>

      <div
        className={cn(
          "flex max-h-[min(360px,45vh)] min-h-[200px] flex-col gap-2 overflow-y-auto px-4 py-4",
          !isOffline && "bg-[#fafafa]"
        )}
      >
        {messages.length === 0 ? (
          <p
            className={cn(
              "py-8 text-center text-sm",
              isOffline ? "text-white/40" : "text-[#80868b]"
            )}
          >
            Thanks — your message is with our team.
          </p>
        ) : null}
        {messages.map((m) => (
          <div
            key={m.id}
            className={cn(
              "max-w-[88%] rounded-2xl px-3.5 py-2.5 text-sm leading-snug",
              m.sender === "visitor"
                ? isOffline
                  ? "ml-auto bg-white/20 text-white ring-1 ring-white/20"
                  : "ml-auto bg-[#067ab4] text-white"
                : isOffline
                  ? "mr-auto bg-white/12 text-white/95 ring-1 ring-white/10"
                  : "mr-auto bg-white text-[#202124] ring-1 ring-[#dadce0]"
            )}
          >
            {m.sender === "admin" ? (
              <p
                className={cn(
                  "mb-1 text-[10px] font-medium uppercase tracking-wide",
                  isOffline ? "text-white/50" : "text-[#80868b]"
                )}
              >
                {AGENT.firstName}
              </p>
            ) : null}
            {m.body}
          </div>
        ))}
        <div ref={bottomRef} />
      </div>

      <form
        onSubmit={sendMessage}
        className={cn(
          "flex gap-2 border-t p-3",
          isOffline ? "border-white/10 bg-black/20" : "border-[#edeff2] bg-white"
        )}
      >
        <Input
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          placeholder="Add another message…"
          className={cn(fieldClass, "flex-1")}
        />
        <button
          type="submit"
          disabled={busy || !draft.trim()}
          className={cn(
            "flex h-10 w-10 shrink-0 items-center justify-center rounded-xl transition disabled:cursor-not-allowed disabled:opacity-60",
            isOffline
              ? "bg-white text-[#067ab4] hover:bg-white/95"
              : "bg-[#067ab4] text-white hover:bg-[#067ab4]"
          )}
          aria-label="Send"
        >
          <Send className="h-4 w-4" />
        </button>
      </form>
    </div>
  )
}
