import React, { useState, useRef, useEffect, useCallback } from "react";
import axios from "axios";
import {
  X,
  PaperPlaneTilt,
  Sparkle,
  Robot,
  User,
  ClockCounterClockwise,
  Plus,
  Trash,
  ChatCircle,
} from "@phosphor-icons/react";
import useAuthStore from "../store/authStore";

const STORAGE_KEY = "sarkinmota_ai_conversations";

function loadConversations() {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]");
  } catch {
    return [];
  }
}
function saveConversations(convs) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(convs));
  } catch {}
}
function newId() {
  return Date.now().toString(36) + Math.random().toString(36).slice(2);
}
const nowTime = () =>
  new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
const fmtDate = (iso) => {
  const d = new Date(iso);
  const today = new Date();
  if (d.toDateString() === today.toDateString()) return "Today";
  const yesterday = new Date(today);
  yesterday.setDate(today.getDate() - 1);
  if (d.toDateString() === yesterday.toDateString()) return "Yesterday";
  return d.toLocaleDateString([], { day: "numeric", month: "short" });
};

function TypingDots() {
  return (
    <div className="flex items-center gap-1 px-4 py-3">
      {[0, 1, 2].map((i) => (
        <span
          key={i}
          className="w-2 h-2 rounded-full animate-bounce"
          style={{
            background: "#8D6E63",
            animationDelay: `${i * 0.15}s`,
            animationDuration: "0.8s",
          }}
        />
      ))}
    </div>
  );
}

function renderInline(text) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  return parts.map((part, i) =>
    part.startsWith("**") && part.endsWith("**") ? (
      <strong key={i}>{part.slice(2, -2)}</strong>
    ) : (
      part
    ),
  );
}

function FormattedMessage({ content }) {
  const lines = content.split("\n");
  return (
    <div className="space-y-1">
      {lines.map((line, i) => {
        if (line.startsWith("• ") || line.startsWith("- "))
          return (
            <p key={i} className="flex gap-2">
              <span className="flex-shrink-0 mt-0.5">•</span>
              <span>{renderInline(line.slice(2))}</span>
            </p>
          );
        if (line === "") return <div key={i} className="h-1" />;
        return <p key={i}>{renderInline(line)}</p>;
      })}
    </div>
  );
}

function MessageBubble({ msg }) {
  const isUser = msg.role === "user";
  return (
    <div
      className={`flex gap-3 ${isUser ? "flex-row-reverse" : "flex-row"} mb-4`}
    >
      <div
        className="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-white shadow-md"
        style={{
          background: isUser
            ? "linear-gradient(135deg,#5D4037,#A1887F)"
            : "linear-gradient(135deg, #6D4C41, #C6A862)",
        }}
      >
        {isUser ? (
          <User size={14} weight="bold" />
        ) : (
          <Robot size={14} weight="fill" />
        )}
      </div>
      <div
        className={`max-w-[78%] flex flex-col ${isUser ? "items-end" : "items-start"}`}
      >
        <div
          className={`px-4 py-3 rounded-2xl text-sm leading-relaxed shadow-sm ${
            isUser
              ? "text-white rounded-tr-sm"
              : "bg-white text-gray-800 border border-gray-100 rounded-tl-sm"
          }`}
          style={
            isUser
              ? { background: "linear-gradient(135deg, #5D4037, #8D6E63)" }
              : {}
          }
        >
          <FormattedMessage content={msg.content} />
        </div>
        <span className="text-[10px] text-gray-400 mt-1 px-1">{msg.time}</span>
      </div>
    </div>
  );
}

const SUGGESTIONS = [
  "Summarise this month's expenses",
  "How many active employees do we have?",
  "What are our outstanding invoices?",
  "Give me a financial overview",
];

export default function SarkinMotaAI({ open, onClose }) {
  const { user } = useAuthStore();
  const companyName = user?.company?.name || "Sarkin Mota Group";
  const firstName = user?.name?.split(" ")[0] || "there";

  const [view, setView] = useState("chat");
  const [conversations, setConvs] = useState(loadConversations);
  const [currentId, setCurrentId] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [confirmClearAll, setConfirmClearAll] = useState(false);
  const bottomRef = useRef(null);
  const inputRef = useRef(null);

  const greeting = `Hello ${firstName}! 👋\n\nI'm Sarkin Mota AI, your intelligent business assistant for ${companyName}.\n\nI have access to your live company data — ask me anything about your finances, employees, invoices, or operations.`;

  const startNewChat = useCallback(() => {
    const id = newId();
    const greetMsg = { role: "assistant", content: greeting, time: nowTime() };
    const conv = {
      id,
      title: "New conversation",
      createdAt: new Date().toISOString(),
      messages: [greetMsg],
    };
    const updated = [conv, ...conversations];
    setConvs(updated);
    saveConversations(updated);
    setCurrentId(id);
    setMessages([greetMsg]);
    setView("chat");
    setTimeout(() => inputRef.current?.focus(), 150);
  }, [conversations, greeting]);

  useEffect(() => {
    if (open) {
      if (conversations.length === 0 || !currentId) {
        startNewChat();
      } else {
        setView("chat");
        setTimeout(() => inputRef.current?.focus(), 150);
      }
    }
  }, [open]);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, loading]);

  const persistMessages = (id, msgs) => {
    setConvs((prev) => {
      const updated = prev.map((c) => {
        if (c.id !== id) return c;
        const userMsgs = msgs.filter((m) => m.role === "user");
        const title =
          userMsgs.length > 0
            ? userMsgs[0].content.slice(0, 45) +
              (userMsgs[0].content.length > 45 ? "…" : "")
            : c.title;
        return { ...c, title, messages: msgs };
      });
      saveConversations(updated);
      return updated;
    });
  };

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

      const userMsg = { role: "user", content: msg, time: nowTime() };
      const history = messages.map((m) => ({
        role: m.role,
        content: m.content,
      }));
      const nextMsgs = [...messages, userMsg];

      setMessages(nextMsgs);
      setInput("");
      setLoading(true);
      persistMessages(currentId, nextMsgs);

      try {
        const { data } = await axios.post("/api/ai/chat", {
          message: msg,
          history,
        });
        const aiMsg = {
          role: "assistant",
          content: data.reply,
          time: nowTime(),
        };
        const finalMsgs = [...nextMsgs, aiMsg];
        setMessages(finalMsgs);
        persistMessages(currentId, finalMsgs);
      } catch {
        const errMsg = {
          role: "assistant",
          content:
            "I encountered a connection issue. Please try again in a moment.",
          time: nowTime(),
        };
        const finalMsgs = [...nextMsgs, errMsg];
        setMessages(finalMsgs);
        persistMessages(currentId, finalMsgs);
      } finally {
        setLoading(false);
      }
    },
    [input, messages, loading, currentId],
  );

  const openConversation = (conv) => {
    setCurrentId(conv.id);
    setMessages(conv.messages);
    setView("chat");
    setTimeout(() => inputRef.current?.focus(), 150);
  };

  const deleteConversation = (id, e) => {
    e.stopPropagation();
    const updated = conversations.filter((c) => c.id !== id);
    setConvs(updated);
    saveConversations(updated);
    if (id === currentId) {
      if (updated.length > 0) {
        openConversation(updated[0]);
      } else {
        startNewChat();
      }
    }
  };

  const clearAllHistory = () => {
    setConvs([]);
    saveConversations([]);
    setConfirmClearAll(false);
    startNewChat();
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  if (!open) return null;

  return (
    <>
      <div
        className="fixed inset-0 bg-black/30 backdrop-blur-[2px] z-[998]"
        onClick={onClose}
      />

      <div
        className="fixed right-0 top-0 h-full w-full max-w-[420px] z-[999] flex flex-col shadow-2xl"
        style={{ background: "#FDFAF6" }}
      >
        {/* ── Header ───────────────────────────────────── */}
        <div
          className="flex-shrink-0 flex items-center justify-between px-5 py-4"
          style={{
            background:
              "linear-gradient(135deg,#3E2723 0%,#5D4037 60%,#C6A862 100%)",
          }}
        >
          <div className="flex items-center gap-3">
            <div
              className="w-10 h-10 rounded-2xl flex items-center justify-center shadow-lg"
              style={{ background: "rgba(255,255,255,0.15)" }}
            >
              <Sparkle size={22} weight="fill" className="text-white" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <p className="font-extrabold text-white text-base tracking-tight">
                  Sarkin Mota AI
                </p>
                <span
                  className="px-1.5 py-0.5 rounded-md text-[9px] font-bold tracking-wider uppercase"
                  style={{
                    background: "rgba(255,255,255,0.2)",
                    color: "#EFEBE9",
                  }}
                >
                  BETA
                </span>
              </div>
              <p
                className="text-[11px] font-medium"
                style={{ color: "#C6A862" }}
              >
                {companyName} · Live data
              </p>
            </div>
          </div>
          <div className="flex items-center gap-1">
            <button
              onClick={() =>
                setView((v) => (v === "history" ? "chat" : "history"))
              }
              title="Chat history"
              className={`p-2 rounded-xl transition-all ${view === "history" ? "bg-white/25 text-white" : "text-white/60 hover:text-white hover:bg-white/15"}`}
            >
              <ClockCounterClockwise size={17} weight="bold" />
            </button>
            <button
              onClick={startNewChat}
              title="New chat"
              className="p-2 rounded-xl text-white/60 hover:text-white hover:bg-white/15 transition-all"
            >
              <Plus size={17} weight="bold" />
            </button>
            <button
              onClick={onClose}
              className="p-2 rounded-xl text-white/60 hover:text-white hover:bg-white/15 transition-all"
            >
              <X size={18} weight="bold" />
            </button>
          </div>
        </div>

        {/* ── Status bar ───────────────────────────────── */}
        <div className="flex-shrink-0 flex items-center gap-2 px-5 py-2 bg-white border-b border-gray-100">
          <span className="w-2 h-2 rounded-full bg-green-400 animate-pulse" />
          <span className="text-xs text-gray-500 font-medium">
            Connected to live company data
          </span>
        </div>

        {/* ── HISTORY VIEW ─────────────────────────────── */}
        {view === "history" && (
          <div className="flex-1 flex flex-col overflow-hidden">
            <div className="flex items-center justify-between px-5 py-3 border-b border-gray-100 bg-white">
              <p className="text-sm font-bold text-gray-800">Chat History</p>
              {conversations.length > 0 &&
                (confirmClearAll ? (
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-gray-500">Clear all?</span>
                    <button
                      onClick={clearAllHistory}
                      className="text-xs font-bold text-red-600 hover:text-red-700 px-2 py-1 rounded-lg hover:bg-red-50 transition-all"
                    >
                      Yes
                    </button>
                    <button
                      onClick={() => setConfirmClearAll(false)}
                      className="text-xs font-bold text-gray-500 px-2 py-1 rounded-lg hover:bg-gray-100 transition-all"
                    >
                      No
                    </button>
                  </div>
                ) : (
                  <button
                    onClick={() => setConfirmClearAll(true)}
                    className="flex items-center gap-1.5 text-xs text-red-500 font-semibold hover:text-red-600 px-2 py-1 rounded-lg hover:bg-red-50 transition-all"
                  >
                    <Trash size={13} weight="bold" /> Clear all
                  </button>
                ))}
            </div>
            <div className="flex-1 overflow-y-auto py-2">
              {conversations.length === 0 ? (
                <div className="flex flex-col items-center justify-center h-full text-center py-16 px-6">
                  <ChatCircle
                    size={40}
                    weight="duotone"
                    className="text-gray-300 mb-3"
                  />
                  <p className="text-gray-500 font-semibold text-sm">
                    No previous conversations
                  </p>
                  <p className="text-gray-400 text-xs mt-1">
                    Your chat history will appear here
                  </p>
                </div>
              ) : (
                conversations.map((conv) => (
                  <div
                    key={conv.id}
                    onClick={() => openConversation(conv)}
                    className={`flex items-start gap-3 px-4 py-3 cursor-pointer hover:bg-primary-50 transition-all group border-b border-gray-50 ${conv.id === currentId ? "bg-primary-50" : ""}`}
                  >
                    <div
                      className="flex-shrink-0 w-8 h-8 rounded-xl flex items-center justify-center mt-0.5"
                      style={{
                        background:
                          conv.id === currentId
                            ? "linear-gradient(135deg,#5D4037,#C6A862)"
                            : "#EFEBE9",
                      }}
                    >
                      <Robot
                        size={14}
                        weight="fill"
                        className={
                          conv.id === currentId ? "text-white" : "text-gray-400"
                        }
                      />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-semibold text-gray-800 truncate">
                        {conv.title}
                      </p>
                      <p className="text-xs text-gray-400 mt-0.5">
                        {fmtDate(conv.createdAt)} · {conv.messages.length}{" "}
                        messages
                      </p>
                    </div>
                    <button
                      onClick={(e) => deleteConversation(conv.id, e)}
                      className="flex-shrink-0 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 text-gray-400 hover:text-red-500 hover:bg-red-50 transition-all"
                    >
                      <Trash size={13} weight="bold" />
                    </button>
                  </div>
                ))
              )}
            </div>
            <div className="flex-shrink-0 p-4 border-t border-gray-100 bg-white">
              <button
                onClick={startNewChat}
                className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-white text-sm font-bold transition-all hover:shadow-lg"
                style={{
                  background: "linear-gradient(135deg,#5D4037,#C6A862)",
                }}
              >
                <Plus size={16} weight="bold" /> New Conversation
              </button>
            </div>
          </div>
        )}

        {/* ── CHAT VIEW ────────────────────────────────── */}
        {view === "chat" && (
          <>
            <div className="flex-1 overflow-y-auto px-4 py-4">
              {messages.map((msg, i) => (
                <MessageBubble key={i} msg={msg} />
              ))}
              {loading && (
                <div className="flex gap-3 mb-4">
                  <div
                    className="flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-white shadow-md"
                    style={{
                      background: "linear-gradient(135deg, #6D4C41, #C6A862)",
                    }}
                  >
                    <Robot size={14} weight="fill" />
                  </div>
                  <div className="bg-white border border-gray-100 rounded-2xl rounded-tl-sm shadow-sm">
                    <TypingDots />
                  </div>
                </div>
              )}
              <div ref={bottomRef} />
            </div>

            {messages.length === 1 && (
              <div className="flex-shrink-0 px-4 pb-2">
                <p className="text-[11px] text-gray-400 font-semibold uppercase tracking-wider mb-2">
                  Quick prompts
                </p>
                <div className="grid grid-cols-2 gap-2">
                  {SUGGESTIONS.map((s, i) => (
                    <button
                      key={i}
                      onClick={() => sendMessage(s)}
                      className="text-left px-3 py-2 rounded-xl text-xs font-medium text-gray-700 bg-white border border-gray-200 hover:border-primary-300 hover:text-primary-700 hover:bg-primary-50 transition-all shadow-sm"
                    >
                      {s}
                    </button>
                  ))}
                </div>
              </div>
            )}

            <div className="flex-shrink-0 px-4 pb-4 pt-2 bg-white border-t border-gray-100">
              <div className="flex items-end gap-2 bg-gray-50 rounded-2xl border border-gray-200 focus-within:border-primary-400 focus-within:bg-white transition-all px-4 py-2 shadow-sm">
                <textarea
                  ref={inputRef}
                  rows={1}
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="Ask Sarkin Mota AI anything…"
                  disabled={loading}
                  className="flex-1 bg-transparent text-sm text-gray-800 placeholder-gray-400 resize-none outline-none max-h-32 py-1"
                  style={{ lineHeight: "1.5" }}
                  onInput={(e) => {
                    e.target.style.height = "auto";
                    e.target.style.height =
                      Math.min(e.target.scrollHeight, 128) + "px";
                  }}
                />
                <button
                  onClick={() => sendMessage()}
                  disabled={!input.trim() || loading}
                  className="flex-shrink-0 w-8 h-8 rounded-xl flex items-center justify-center text-white transition-all disabled:opacity-40 disabled:cursor-not-allowed mb-0.5"
                  style={{
                    background: "linear-gradient(135deg,#5D4037,#C6A862)",
                  }}
                >
                  <PaperPlaneTilt size={15} weight="fill" />
                </button>
              </div>
              <p className="text-center text-[10px] text-gray-400 mt-2">
                Sarkin Mota AI · Powered by GPT-4o · Data is live &
                company-scoped
              </p>
            </div>
          </>
        )}
      </div>
    </>
  );
}
