"use client";

import type { AssistantTurn } from "@domainops/shared-types";
import { App, Button, Drawer, Empty, Input, List, Space, Tag, Typography } from "antd";
import { MessageOutlined, SendOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { sendAssistantMessage } from "@/lib/api/assistant";
import { getPublicSettings } from "@/lib/api/settings";
import { ApiError } from "@/lib/api/client";
import { useSiteBranding } from "@/lib/branding/BrandingProvider";
import { onAssistantEnabledChanged } from "@/lib/utils/assistantSettings";

interface DisplayTurn extends AssistantTurn {
  actionTools?: string[];
}

/**
 * Rendered app-wide in the dashboard shell, but stays hidden entirely when
 * a super admin has turned it off (Settings > Extra) - see
 * PublicSettingsController, the only place the frontend can currently
 * learn this without adding a second authenticated round trip.
 */
export function AssistantWidget() {
  const { message } = App.useApp();
  const branding = useSiteBranding();
  const [isEnabled, setIsEnabled] = useState(true);
  const [isOpen, setIsOpen] = useState(false);
  const [turns, setTurns] = useState<DisplayTurn[]>([]);
  const [draft, setDraft] = useState("");
  const [isSending, setIsSending] = useState(false);

  useEffect(() => {
    void getPublicSettings().then((settings) => setIsEnabled(settings.assistant_enabled));
    // Settings > Extra lives in a completely separate part of the tree, so
    // a toggle there can't just update this component's state directly -
    // this is what makes the launcher disappear immediately instead of on
    // the next page load/mount.
    return onAssistantEnabledChanged((enabled) => {
      setIsEnabled(enabled);
      if (!enabled) setIsOpen(false);
    });
  }, []);

  async function handleSend() {
    const text = draft.trim();
    if (!text) return;

    const history = turns.map(({ role, content }) => ({ role, content }));
    setTurns((prev) => [...prev, { role: "user", content: text }]);
    setDraft("");
    setIsSending(true);

    try {
      const result = await sendAssistantMessage(text, history);
      setTurns((prev) => [
        ...prev,
        {
          role: "assistant",
          content: result.reply,
          actionTools: result.actions.map((a) => a.tool),
        },
      ]);
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "The assistant didn't respond.");
      setTurns((prev) => [...prev, { role: "assistant", content: "Sorry, something went wrong on my end." }]);
    } finally {
      setIsSending(false);
    }
  }

  if (!isEnabled) return null;

  return (
    <>
      <Button
        className="assistant-widget__launcher"
        type="primary"
        shape="circle"
        size="large"
        icon={<MessageOutlined />}
        style={{ position: "fixed", right: 24, bottom: 24, zIndex: 1000 }}
        onClick={() => setIsOpen(true)}
      />
      <Drawer
        title={`${branding.site_title} Assistant`}
        open={isOpen}
        onClose={() => setIsOpen(false)}
        size={420}
        className="assistant-widget__drawer"
      >
        <div className="flex flex-col h-full">
          <div className="flex-1 overflow-y-auto mb-3">
            {turns.length === 0 ? (
              <Empty
                description="Ask about domains, servers, or provision Cloudflare for a domain."
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            ) : (
              <List
                dataSource={turns}
                renderItem={(turn, index) => (
                  <List.Item key={index} className="!border-0 !px-0">
                    <div className={`w-full ${turn.role === "user" ? "text-right" : "text-left"}`}>
                      <div
                        className={`inline-block rounded-lg px-3 py-2 max-w-[90%] ${
                          turn.role === "user" ? "bg-blue-600 text-white" : "bg-gray-100 dark:bg-gray-800"
                        }`}
                      >
                        <Typography.Text className={turn.role === "user" ? "!text-white" : undefined}>
                          {turn.content}
                        </Typography.Text>
                      </div>
                      {turn.actionTools && turn.actionTools.length > 0 && (
                        <div className="mt-1">
                          <Space size={4} wrap>
                            {turn.actionTools.map((tool, i) => (
                              <Tag key={i} color="blue">
                                {tool}
                              </Tag>
                            ))}
                          </Space>
                        </div>
                      )}
                    </div>
                  </List.Item>
                )}
              />
            )}
          </div>
          <Space.Compact className="w-full">
            <Input
              placeholder="Ask the assistant..."
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              onPressEnter={handleSend}
              disabled={isSending}
              className="dms_layout_assistant_message_input"
            />
            <Button
              type="primary"
              icon={<SendOutlined />}
              loading={isSending}
              onClick={handleSend}
              className="dms_layout_assistant_send_btn"
            >
              Send
            </Button>
          </Space.Compact>
        </div>
      </Drawer>
    </>
  );
}
