import * as React from "react";
import { Bot, RotateCcw, X } from "lucide-react";
import { cn } from "@/lib/utils";
import { Sheet, SheetContent } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ChatInputArea } from "@/components/ui/chat-input-area";
import { Spinner } from "@/components/ui/spinner";

/**
 * AiAssistantDrawer — WealthX DS (L5 Drawer)
 *
 * Right-side panel that provides an AI conversation interface for a specific
 * opportunity/deal. Used in the Pipeline board via the "Launch Assistant" button
 * on OpportunityCard.
 *
 * Layout:
 *   • Header  — bot icon + title + reload + close
 *   • Content — empty state (task suggestions) or chat message list
 *   • Footer  — textarea input + send button
 *
 * Pure display component: all message state and API calls are managed by the
 * consuming page. The drawer only handles local `inputValue` state.
 *
 * Data source: `ai-chat.ts` / `conversation.ts` hooks in the backoffice
 */

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export interface AiChatMessage {
  id: string;
  role: "user" | "assistant";
  content: string;
  /** True while the assistant response is still streaming in. */
  isStreaming?: boolean;
  /** True if the message failed to send or receive. */
  isErrored?: boolean;
}

export interface AiTaskSuggestion {
  id: string;
  /** Short label shown as the suggestion title. */
  title: string;
  /** Supporting description shown below the title. */
  description: string;
}

export interface AiAssistantDrawerProps {
  open: boolean;
  onClose: () => void;
  /** Opportunity or contact name shown in the header subtitle. */
  opportunityName?: string;
  /**
   * Suggested tasks shown in the empty state.
   * Typically the opportunity's incomplete tasks.
   * Clicking a suggestion pre-fills the input.
   */
  taskSuggestions?: AiTaskSuggestion[];
  /** Chat message history. Empty array = show empty/welcome state. */
  messages?: AiChatMessage[];
  /** True while the assistant is generating a response. */
  isStreaming?: boolean;
  /** True while initial data is loading (shows full-panel spinner). */
  isLoading?: boolean;
  /** Called when the user submits a message. Input is cleared after this fires. */
  onSendMessage?: (text: string) => void;
  /** Called when the user selects files via the attachment button. */
  onAttachFile?: (files: FileList) => void;
  /** Called when the user selects images via the image upload button. */
  onAttachImage?: (files: FileList) => void;
  /** Called when the user clicks the reload/reset button. */
  onReset?: () => void;
  className?: string;
}

// ---------------------------------------------------------------------------
// Typing indicator (three bouncing dots)
// ---------------------------------------------------------------------------

function AiTypingIndicator() {
  return (
    <span className="flex items-center gap-1 py-1" aria-label="AI is thinking">
      {[0, 150, 300].map((delay) => (
        <span
          key={delay}
          className="size-1.5 rounded-full bg-current animate-bounce"
          style={{ animationDelay: `${delay}ms` }}
          aria-hidden="true"
        />
      ))}
    </span>
  );
}

// ---------------------------------------------------------------------------
// Chat message bubble
// ---------------------------------------------------------------------------

function AiChatBubble({ message }: { message: AiChatMessage }) {
  const isUser = message.role === "user";
  const isEmpty = !message.content.trim();

  return (
    <div
      className={cn("flex w-full", isUser ? "justify-end" : "justify-start")}
    >
      <div
        className={cn(
          "max-w-[85%] px-3 py-2 text-sm",
          isUser
            ? "bg-primary text-primary-foreground"
            : "bg-muted text-foreground",
          message.isErrored && "bg-destructive/10 text-destructive",
        )}
      >
        {/* Content or streaming indicators */}
        {isEmpty && message.isStreaming ? (
          <AiTypingIndicator />
        ) : (
          <span className="whitespace-pre-wrap break-words leading-relaxed">
            {message.content}
          </span>
        )}
        {message.isErrored && (
          <p className="mt-1 text-xs opacity-70">
            Failed to send. Please try again.
          </p>
        )}
      </div>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Task suggestion card
// ---------------------------------------------------------------------------

function AiTaskCard({
  suggestion,
  onSelect,
}: {
  suggestion: AiTaskSuggestion;
  onSelect: (text: string) => void;
}) {
  return (
    <Button
      type="button"
      variant="ghost"
      onClick={() => onSelect(suggestion.title)}
      className="h-auto w-full flex-col items-start gap-1 border border-border bg-background p-3 text-left hover:bg-muted/50"
    >
      <span className="text-sm font-medium text-foreground">
        {suggestion.title}
      </span>
      <span className="text-xs text-muted-foreground">
        {suggestion.description}
      </span>
    </Button>
  );
}

// ---------------------------------------------------------------------------
// AiAssistantDrawer
// ---------------------------------------------------------------------------

const DEFAULT_SUGGESTIONS: AiTaskSuggestion[] = [
  {
    id: "s1",
    title: "Update pricing strategy",
    description: "Review and adjust pricing based on market trends",
  },
  {
    id: "s2",
    title: "Enhance marketing outreach",
    description: "Develop new campaigns to increase customer engagement",
  },
  {
    id: "s3",
    title: "Optimise social media strategy",
    description: "Analyse performance and adjust content for better visibility",
  },
  {
    id: "s4",
    title: "Implement customer feedback loops",
    description: "Create mechanisms to collect and act on customer insights",
  },
];

export function AiAssistantDrawer({
  open,
  onClose,
  opportunityName,
  taskSuggestions,
  messages = [],
  isStreaming = false,
  isLoading = false,
  onSendMessage,
  onAttachFile,
  onAttachImage,
  onReset,
  className,
}: AiAssistantDrawerProps) {
  const [inputValue, setInputValue] = React.useState("");
  const messagesEndRef = React.useRef<HTMLDivElement>(null);

  const suggestions = taskSuggestions ?? DEFAULT_SUGGESTIONS;
  const hasMessages = messages.length > 0;

  // Auto-scroll to latest message
  React.useEffect(() => {
    if (!messagesEndRef.current) return;
    messagesEndRef.current.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
    });
  }, [messages.length]);

  const handleSend = React.useCallback(
    (text: string) => {
      onSendMessage?.(text);
      setInputValue("");
    },
    [onSendMessage],
  );

  const handleSuggestionSelect = (text: string) => {
    setInputValue(text);
  };

  return (
    <Sheet open={open} onOpenChange={(o) => !o && onClose()}>
      <SheetContent
        side="right"
        showCloseButton={false}
        className={cn("w-[480px] max-w-full gap-0 p-0", className)}
        data-slot="ai-assistant-drawer"
      >
        {/* Header */}
        <div className="flex items-center justify-between border-b border-border px-4 py-3">
          <div className="flex items-center gap-3">
            <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary">
              <Bot className="size-4 text-primary-foreground" />
            </span>
            <div className="flex flex-col">
              <span className="text-sm font-semibold text-foreground">
                AI Assistant
              </span>
              {opportunityName && (
                <span className="text-xs text-muted-foreground">
                  {opportunityName}
                </span>
              )}
            </div>
          </div>
          <div className="flex items-center gap-1">
            {onReset && (
              <Button
                variant="ghost"
                size="icon"
                className="size-8"
                onClick={onReset}
                title="Reset conversation"
                disabled={isLoading}
              >
                <RotateCcw className="size-4" />
                <span className="sr-only">Reset conversation</span>
              </Button>
            )}
            <Button
              variant="ghost"
              size="icon"
              className="size-8"
              onClick={onClose}
              title="Close"
            >
              <X className="size-4" />
              <span className="sr-only">Close</span>
            </Button>
          </div>
        </div>

        {/* Content */}
        <div className="flex flex-1 flex-col overflow-y-auto">
          {isLoading ? (
            /* Loading state */
            <div className="flex flex-1 items-center justify-center py-20">
              <div className="flex flex-col items-center gap-3">
                <Spinner size="lg" className="text-muted-foreground" />
                <p className="text-sm text-muted-foreground">Initialising…</p>
              </div>
            </div>
          ) : !hasMessages ? (
            /* Empty / welcome state */
            <div className="flex flex-col gap-6 p-4">
              {/* Hero card */}
              <div className="flex flex-col gap-3 border border-border bg-muted/30 p-4">
                <Badge variant="outline" className="w-fit gap-1.5">
                  <span
                    className="size-1.5 rounded-full bg-primary"
                    aria-hidden="true"
                  />
                  AI Chat for Brokers
                </Badge>
                <p className="text-sm text-muted-foreground">
                  A safe and secure way to chat about insights that run your
                  business and utilise AI. All chats stay within your
                  environment, all closed off and compliant.
                </p>
                <div className="flex gap-2">
                  {(
                    [
                      { emoji: "🤖", label: "Smart" },
                      { emoji: "⚡", label: "Fast" },
                      { emoji: "🔒", label: "Secure" },
                    ] as const
                  ).map(({ emoji, label }) => (
                    <span
                      key={label}
                      className="border border-border px-2.5 py-1 text-xs text-foreground"
                    >
                      {emoji} {label}
                    </span>
                  ))}
                </div>
              </div>

              {/* Task suggestions */}
              {suggestions.length > 0 && (
                <div className="flex flex-col gap-2">
                  <p className="text-xs font-medium text-muted-foreground">
                    Suggested tasks
                  </p>
                  <div className="grid grid-cols-2 gap-2">
                    {suggestions.map((s) => (
                      <AiTaskCard
                        key={s.id}
                        suggestion={s}
                        onSelect={handleSuggestionSelect}
                      />
                    ))}
                  </div>
                </div>
              )}
            </div>
          ) : (
            /* Message list */
            <div className="flex flex-col gap-3 p-4">
              {messages.map((msg) => (
                <AiChatBubble key={msg.id} message={msg} />
              ))}
              {/* Streaming indicator when last message is user's */}
              {isStreaming &&
                messages[messages.length - 1]?.role === "user" && (
                  <div className="flex justify-start">
                    <div className="bg-muted px-3 py-2 text-muted-foreground">
                      <AiTypingIndicator />
                    </div>
                  </div>
                )}
              <div ref={messagesEndRef} />
            </div>
          )}
        </div>

        {/* Footer — input bar */}
        <div className="border-t border-border p-3">
          <ChatInputArea
            value={inputValue}
            onChange={setInputValue}
            onSend={handleSend}
            onAttachFile={onAttachFile}
            onAttachImage={onAttachImage}
            disabled={isLoading || isStreaming}
            placeholder="Ask me anything…"
          />
        </div>
      </SheetContent>
    </Sheet>
  );
}
