import { useCallback } from "react";
import { useParams, useNavigate } from "react-router";
import { Plus, MessageSquare, Code2, Bug, Lightbulb, Wand2 } from "lucide-react";
import { motion } from "motion/react";
import { client } from "@/client";
import { Button } from "@/components/ui/button";
import { useWorkspaceSessions } from "./chat/use-sessions";
import { ensureWorkspaceSession } from "./chat/use-session";

interface SuggestionCard {
  title: string;
  body: string;
  icon: React.ComponentType<{ className?: string }>;
}

const SUGGESTIONS: SuggestionCard[] = [
  {
    title: "Code Review",
    body: "Review my pull request for bugs and improvements",
    icon: Code2,
  },
  {
    title: "Debug Help",
    body: "Help me diagnose this failing test case",
    icon: Bug,
  },
  {
    title: "Explain Code",
    body: "Explain how this algorithm works step by step",
    icon: Lightbulb,
  },
  {
    title: "Refactor",
    body: "Suggest refactoring for better readability",
    icon: Wand2,
  },
];

/**
 * Landing / empty-state page shown when no conversation is selected.
 */
export default function WorkplanChatList() {
  const { projectName = "" } = useParams();
  const navigate = useNavigate();
  const { sessionsRef } = useWorkspaceSessions(projectName);

  const startConversation = useCallback(
    async (title: string, prefillBody?: string) => {
      try {
        const sessionId = await ensureWorkspaceSession(
          projectName,
          sessionsRef.current,
        );
        if (!sessionId) return;

        const r = await client.agentCreateConversation(sessionId, { title });
        navigate(`/${projectName}/workplan/chat/${r.data.id}`, {
          state: prefillBody ? { prefill: prefillBody } : undefined,
        });
      } catch {
        // Silently fail — user can retry via UI.
      }
    },
    [projectName, navigate, sessionsRef],
  );

  const handleNewChat = useCallback(() => {
    startConversation("New Chat");
  }, [startConversation]);

  const handleQuickStart = useCallback(
    (title: string, body: string) => {
      startConversation(title, body);
    },
    [startConversation],
  );

  return (
    <div className="flex h-full items-center justify-center px-8">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, ease: "easeOut" }}
        className="max-w-md text-center"
      >
        {/* Hero icon */}
        <div className="mx-auto grid size-20 place-items-center rounded-2xl bg-gradient-to-br from-primary/15 to-primary/[0.03] ring-1 ring-primary/10 shadow-sm">
          <MessageSquare
            className="size-9 text-primary/30"
            aria-hidden="true"
          />
        </div>

        <h1 className="mt-6 text-xl font-bold tracking-tight text-foreground">
          AI Assistant
        </h1>
        <p className="mt-2 text-sm leading-relaxed text-muted-foreground/70">
          Start a new conversation with the AI assistant. Ask questions, get
          code help, discuss ideas, and more.
        </p>

        <div className="mt-6 flex items-center justify-center gap-3">
          <motion.div whileHover={{ scale: 1.03 }} whileTap={{ scale: 0.97 }}>
            <Button
              className="cursor-pointer shadow-sm"
              onClick={handleNewChat}
              size="default"
              variant="default"
            >
              <Plus className="mr-2 size-4" aria-hidden="true" />
              New Chat
            </Button>
          </motion.div>
        </div>

        {/* Suggestion cards */}
        <div className="mt-10 grid grid-cols-2 gap-2.5 text-left">
          {SUGGESTIONS.map((suggestion, i) => {
            const Icon = suggestion.icon;
            return (
              <motion.button
                key={suggestion.title}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, delay: 0.1 + i * 0.06 }}
                whileHover={{
                  scale: 1.02,
                  transition: { duration: 0.15 },
                }}
                whileTap={{ scale: 0.98 }}
                type="button"
                className="group cursor-pointer rounded-xl border border-border/40 bg-card px-4 py-3.5 text-left transition-[background-color,border-color,box-shadow,transform] duration-200 hover:border-border/80 hover:bg-muted/30 hover:shadow-sm hover:ring-1 hover:ring-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                onClick={() =>
                  handleQuickStart(suggestion.title, suggestion.body)
                }
                aria-label={`${suggestion.title}: ${suggestion.body}`}
              >
                <div className="flex items-center gap-2">
                  <Icon className="size-3.5 text-muted-foreground/50 transition-colors group-hover:text-foreground/70" />
                  <p className="text-[13px] font-medium text-foreground">
                    {suggestion.title}
                  </p>
                </div>
                <p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground/50">
                  {suggestion.body}
                </p>
              </motion.button>
            );
          })}
        </div>
      </motion.div>
    </div>
  );
}
