"use client";

import { useEffect, useRef, useState } from "react";

import { Bot, FileText, Mail, Search, Send, Sparkles, User, Users } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { clients } from "@/data/clients";

interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  isTyping?: boolean;
}

const QUICK_ACTIONS = [
  { label: "Draft Email", icon: Mail, prompt: "Draft a short professional email to schedule a discovery call." },
  { label: "Search Clients", icon: Search, prompt: "List active clients from the CRM for me." },
  { label: "Summarize Notes", icon: FileText, prompt: "How should we structure CRM notes after a discovery call?" },
  { label: "Tips", icon: Sparkles, prompt: "What are best practices for client onboarding?" },
];

function buildClientsResponse(): string {
  const subset = clients.filter((c) => c.status === "Active").slice(0, 5);
  if (subset.length === 0) {
    return "There are no active clients in mock data yet. Add records in src/data/clients.ts or register users via signup.";
  }
  const lines = subset.map((c, i) => `${i + 1}. **${c.name}** (${c.id}) — ${c.type}, ${c.status}`);
  return `Here are some active clients from your mock CRM:\n\n${lines.join("\n")}\n\n(Wire this assistant to your API when you're ready.)`;
}

const MOCK_RESPONSES: Record<string, string> = {
  default:
    "I'm a mock assistant. Replace the response logic with your LLM endpoint. I can help you draft texts, recap CRM conventions, or reason about onboarding.",
  email:
    "Subject: Scheduling a quick discovery call\n\nHi [Name],\n\nI'd like to find 30 minutes next week for a discovery call—please reply with a few times that work for you.\n\nBest regards,\n[Your name]",
  notes:
    "After a discovery call: log date, attendee names, objectives, objections, agreed next steps, and follow-up date in your CRM note field.",
  tips: "**Onboarding best practices**\n• Send a concise welcome summary within 24h.\n• Confirm data you need upfront.\n• Use a checklist so nothing is forgotten.\n• Book the next milestone before closing the meeting.",
};

function getResponse(input: string): string {
  const lower = input.toLowerCase();
  if (lower.includes("email") || lower.includes("draft")) return MOCK_RESPONSES.email;
  if (lower.includes("client") || lower.includes("crm") || lower.includes("active")) return buildClientsResponse();
  if (lower.includes("note") || lower.includes("summar")) return MOCK_RESPONSES.notes;
  if (lower.includes("practice") || lower.includes("onboard")) return MOCK_RESPONSES.tips;
  return MOCK_RESPONSES.default;
}

export default function AiAssistantPage() {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: "welcome",
      role: "assistant",
      content:
        "Hi! I'm your internal assistant placeholder. Prompts stay on the frontend—swap in your API when you connect a model.",
    },
  ]);
  const [input, setInput] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

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

  const sendMessage = (text: string) => {
    if (!text.trim() || isTyping) return;

    const userMsg: Message = { id: `u-${Date.now()}`, role: "user", content: text };
    const typingMsg: Message = { id: "typing", role: "assistant", content: "", isTyping: true };

    setMessages((prev) => [...prev, userMsg, typingMsg]);
    setInput("");
    setIsTyping(true);

    const response = getResponse(text);
    let charIndex = 0;

    const interval = setInterval(() => {
      charIndex += 6;
      const partial = response.slice(0, charIndex);
      const isDone = charIndex >= response.length;

      setMessages((prev) =>
        prev.map((m) =>
          m.id === "typing"
            ? { ...m, content: partial, isTyping: !isDone, id: isDone ? `a-${Date.now()}` : "typing" }
            : m,
        ),
      );

      if (isDone) {
        clearInterval(interval);
        setIsTyping(false);
      }
    }, 20);
  };

  const recentClients = clients.filter((c) => c.status === "Active").slice(0, 5);

  return (
    <div className="flex flex-col gap-4 md:gap-6">
      <div>
        <h1 className="font-semibold text-xl">AI Assistant</h1>
        <p className="text-muted-foreground text-sm">Mock UI only — swap in your model / API.</p>
      </div>

      <div className="flex gap-4" style={{ height: "calc(100vh - 220px)", minHeight: 500 }}>
        <div className="flex min-w-0 flex-1 flex-col">
          <Card className="flex h-full flex-col overflow-hidden">
            <div className="flex flex-wrap gap-2 border-b p-3">
              {QUICK_ACTIONS.map((action) => {
                const Icon = action.icon;
                return (
                  <Button
                    key={action.label}
                    variant="outline"
                    size="sm"
                    className="gap-1.5 text-xs"
                    onClick={() => sendMessage(action.prompt)}
                    disabled={isTyping}
                  >
                    <Icon className="size-3.5" />
                    {action.label}
                  </Button>
                );
              })}
            </div>

            <ScrollArea className="flex-1 p-4" ref={scrollRef}>
              <div className="space-y-4">
                {messages.map((msg) => (
                  <div
                    key={msg.id}
                    className={`flex items-start gap-3 ${msg.role === "user" ? "flex-row-reverse" : ""}`}
                  >
                    <div
                      className={`flex size-8 shrink-0 items-center justify-center rounded-full ${msg.role === "assistant" ? "bg-primary text-primary-foreground" : "bg-muted"}`}
                    >
                      {msg.role === "assistant" ? <Bot className="size-4" /> : <User className="size-4" />}
                    </div>
                    <div
                      className={`max-w-[80%] rounded-2xl px-4 py-2.5 ${msg.role === "assistant" ? "bg-muted" : "bg-primary text-primary-foreground"}`}
                    >
                      {msg.isTyping ? (
                        <div className="flex items-center gap-1">
                          <span
                            className="size-1.5 animate-bounce rounded-full bg-current"
                            style={{ animationDelay: "0ms" }}
                          />
                          <span
                            className="size-1.5 animate-bounce rounded-full bg-current"
                            style={{ animationDelay: "150ms" }}
                          />
                          <span
                            className="size-1.5 animate-bounce rounded-full bg-current"
                            style={{ animationDelay: "300ms" }}
                          />
                        </div>
                      ) : (
                        <p className="whitespace-pre-wrap text-sm leading-relaxed">{msg.content}</p>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </ScrollArea>

            <div className="border-t p-3">
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  sendMessage(input);
                }}
                className="flex gap-2"
              >
                <Input
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  placeholder="Ask anything…"
                  disabled={isTyping}
                />
                <Button type="submit" size="icon" disabled={!input.trim() || isTyping}>
                  <Send className="size-4" />
                </Button>
              </form>
            </div>
          </Card>
        </div>

        <div className="w-56 shrink-0 space-y-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-sm">
                <Users className="size-4" />
                Sample clients
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              {recentClients.map((c) => (
                <button
                  key={c.id}
                  type="button"
                  className="flex w-full items-center gap-2 rounded px-1 py-0.5 text-left hover:bg-muted/50"
                  onClick={() => sendMessage(`Tell me about client ${c.name}`)}
                >
                  <div className="flex size-5 shrink-0 items-center justify-center rounded bg-muted font-bold text-[10px]">
                    {c.name.charAt(0)}
                  </div>
                  <div className="min-w-0">
                    <p className="truncate font-medium text-xs">{c.name}</p>
                    <p className="text-[10px] text-muted-foreground">{c.type}</p>
                  </div>
                </button>
              ))}
            </CardContent>
          </Card>

          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm">Try asking</CardTitle>
            </CardHeader>
            <CardContent className="space-y-1">
              {[
                "Who are my active clients?",
                "Draft a thank-you note after onboarding",
                "How do I describe this boilerplate?",
              ].map((s) => (
                <button
                  key={s}
                  type="button"
                  className="w-full rounded px-2 py-1.5 text-left text-xs hover:bg-muted/50"
                  onClick={() => sendMessage(s)}
                >
                  <Sparkles className="mr-1.5 inline size-3 text-muted-foreground" />
                  {s}
                </button>
              ))}
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
