import React, { useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";
import { useTheme } from "styled-components";
import { Box, Button, Flex, Typography } from "@strapi/design-system";
import { getFetchClient } from "@strapi/strapi/admin";

const SUGGESTIONS = [
  { icon: "✦", label: "Summarize the document", instruction: "Summarize this text into a short paragraph in the same language." },
  { icon: "✦", label: "Continue writing", instruction: "Continue writing this text naturally in the same language and tone. Return the full HTML with your continuation appended." },
  { icon: "✦", label: "Rewrite the document", instruction: "Rewrite this text to be clearer and more engaging. Keep the same language, meaning and HTML structure." },
  { icon: "✧", label: "Fix grammar and spelling", instruction: "Fix all grammar, spelling and punctuation mistakes. Keep the wording as close to the original as possible." },
  { icon: "✧", label: "Review document", instruction: "Review this text: list strengths, weaknesses and concrete improvement suggestions as a short HTML list." },
  { icon: "✧", label: "Translate to German", instruction: "Translate the text to German. Keep the HTML structure." },
  { icon: "✧", label: "Translate to English", instruction: "Translate the text to English. Keep the HTML structure." },
];

const AIPanel = ({ isOpen, onClose, getEditor }) => {
  const theme = useTheme();
  const [status, setStatus] = useState(null);
  const [provider, setProvider] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");
  const [contextHtml, setContextHtml] = useState("");
  const [isSelection, setIsSelection] = useState(false);
  const [useContext, setUseContext] = useState(true);
  const [isRunning, setIsRunning] = useState(false);
  const threadRef = useRef(null);

  useEffect(() => {
    if (!isOpen) return;

    const editor = getEditor();
    if (editor) {
      const selectionContent = editor.model.getSelectedContent(editor.model.document.selection);
      const selectedHtml = editor.data.stringify(selectionContent);
      setIsSelection(Boolean(selectedHtml));
      setContextHtml(selectedHtml || editor.getData());
      setUseContext(true);
    }

    const { get } = getFetchClient();
    get("/ckstudio/ai/status")
      .then(({ data }) => {
        setStatus(data);
        if (data.providers?.length) setProvider((current) => current ?? data.providers[0].id);
      })
      .catch(() => setStatus({ enabled: false, providers: [] }));
  }, [isOpen]);

  useEffect(() => {
    threadRef.current?.scrollTo({ top: threadRef.current.scrollHeight, behavior: "smooth" });
  }, [messages, isRunning]);

  if (!isOpen) return null;

  const resolveContextHtml = (forceDocument) => {
    const editor = getEditor();
    if (!editor) return useContext ? contextHtml : "";
    if (!useContext && !forceDocument) return "";

    const selectionContent = editor.model.getSelectedContent(editor.model.document.selection);
    const selectedHtml = editor.data.stringify(selectionContent);
    if (useContext && isSelection && selectedHtml) return selectedHtml;
    return editor.getData();
  };

  const send = async (instruction, { forceDocument = false } = {}) => {
    if (!instruction.trim() || isRunning) return;

    if (forceDocument && !useContext) {
      setUseContext(true);
      setIsSelection(false);
    }

    const history = messages.map(({ role, content }) => ({ role, content }));
    setMessages((current) => [...current, { role: "user", content: instruction }]);
    setInput("");
    setIsRunning(true);

    try {
      const { post } = getFetchClient();
      const { data } = await post("/ckstudio/ai", {
        provider,
        instruction,
        html: resolveContextHtml(forceDocument),
        history,
      });
      setMessages((current) => [...current, { role: "assistant", content: data.text }]);
    } catch (requestError) {
      const message =
        requestError.response?.data?.error ?? requestError.message ?? "Request failed";
      setMessages((current) => [...current, { role: "assistant", content: "", error: message }]);
    } finally {
      setIsRunning(false);
    }
  };

  const applyToEditor = (html) => {
    const editor = getEditor();
    if (!editor || !html) return;

    if (isSelection) {
      editor.model.change(() => {
        const viewFragment = editor.data.processor.toView(html);
        const modelFragment = editor.data.toModel(viewFragment);
        editor.model.insertContent(modelFragment);
      });
    } else {
      editor.setData(html);
    }
  };

  const renderHeader = () => (
    <Flex justifyContent="space-between" alignItems="center" padding={4} style={{ borderBottom: "1px solid rgba(128,128,128,0.25)" }}>
      <Flex gap={2} alignItems="center">
        <Typography variant="delta" tag="h2">
          ✦ AI Chat
        </Typography>
        {status?.providers?.length > 1 && (
          <select
            value={provider ?? ""}
            onChange={(event) => setProvider(event.target.value)}
            aria-label="AI provider"
            style={{
              ...selectStyle,
              background: theme.colors.neutral100,
              color: theme.colors.neutral800,
              border: `1px solid ${theme.colors.neutral200}`,
              colorScheme: isDarkColor(theme.colors.neutral0) ? "dark" : "light",
            }}
          >
            {status.providers.map((entry) => (
              <option key={entry.id} value={entry.id}>
                {entry.label}
              </option>
            ))}
          </select>
        )}
      </Flex>
      <Flex gap={2}>
        <Button variant="tertiary" onClick={() => setMessages([])} disabled={!messages.length}>
          + New chat
        </Button>
        <Button variant="tertiary" onClick={onClose}>
          ✕
        </Button>
      </Flex>
    </Flex>
  );

  const renderSuggestions = () => (
    <Flex direction="column" alignItems="stretch" gap={2} paddingTop={2}>
      <Typography variant="omega">
        Hi! I can help you draft, rewrite, and improve your text. How can I help right now?
      </Typography>
      {SUGGESTIONS.map((suggestion) => (
        <button
          key={suggestion.label}
          type="button"
          onClick={() => send(suggestion.instruction, { forceDocument: true })}
          style={suggestionStyle}
        >
          <span style={{ color: "#7b79ff" }}>{suggestion.icon}</span> {suggestion.label}
        </button>
      ))}
    </Flex>
  );

  const renderMessage = (message, index) => {
    if (message.role === "user") {
      return (
        <Box key={index} padding={3} hasRadius background="primary100" style={{ alignSelf: "flex-end", maxWidth: "85%" }}>
          <Typography>{message.content}</Typography>
        </Box>
      );
    }

    if (message.error) {
      return (
        <Box key={index} padding={3} hasRadius background="danger100" style={{ maxWidth: "92%" }}>
          <Typography textColor="danger600">{message.error}</Typography>
        </Box>
      );
    }

    return (
      <Box key={index} padding={3} hasRadius background="neutral100" style={{ maxWidth: "92%" }}>
        <div dangerouslySetInnerHTML={{ __html: message.content }} />
        <Flex gap={2} paddingTop={2}>
          <Button size="S" onClick={() => applyToEditor(message.content)}>
            {isSelection ? "Replace selection" : "Replace document"}
          </Button>
        </Flex>
      </Box>
    );
  };

  return (
    <div style={overlayStyle}>
      <Box background="neutral0" shadow="popupShadow" style={drawerStyle} role="dialog" aria-label="AI assistant">
        {renderHeader()}

        {status && !status.enabled && (
          <Box padding={4}>
            <Box padding={3} hasRadius background="warning100">
              <Typography textColor="warning600">
                AI is not configured. Add a provider API key in Settings → CKStudio → AI settings
                (keys are stored encrypted in the database).
              </Typography>
            </Box>
          </Box>
        )}

        <div ref={threadRef} style={threadStyle}>
          <Flex direction="column" alignItems="stretch" gap={2}>
            {messages.length === 0 && status?.enabled && renderSuggestions()}
            {messages.map(renderMessage)}
            {isRunning && (
              <Box padding={3} hasRadius background="neutral100" style={{ maxWidth: "60%" }}>
                <Typography textColor="neutral500">✦ Thinking…</Typography>
              </Box>
            )}
          </Flex>
        </div>

        <Box padding={4} style={{ borderTop: "1px solid rgba(128,128,128,0.25)" }}>
          {useContext ? (
            <Flex paddingBottom={2}>
              <Flex gap={1} alignItems="center" paddingLeft={2} paddingRight={2} hasRadius background="neutral150">
                <Typography variant="pi">
                  {isSelection ? "Selection" : "Current document"}
                </Typography>
                <button type="button" onClick={() => setUseContext(false)} style={chipCloseStyle} aria-label="Remove context">
                  ✕
                </button>
              </Flex>
            </Flex>
          ) : (
            <Flex paddingBottom={2}>
              <button type="button" onClick={() => setUseContext(true)} style={suggestionStyle}>
                + Attach {isSelection ? "selection" : "document"} as context
              </button>
            </Flex>
          )}
          <Flex gap={2}>
            <input
              value={input}
              onChange={(event) => setInput(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Enter" && !event.shiftKey) {
                  event.preventDefault();
                  send(input);
                }
              }}
              placeholder="Ask AI anything…"
              disabled={!status?.enabled || isRunning}
              style={inputStyle}
              aria-label="Ask AI anything"
            />
            <Button onClick={() => send(input)} disabled={!status?.enabled || !input.trim() || isRunning}>
              ↵
            </Button>
          </Flex>
          <Box paddingTop={2}>
            <Typography variant="pi" textColor="neutral500">
              AI can make mistakes. Please double-check responses.
            </Typography>
          </Box>
        </Box>
      </Box>
    </div>
  );
};

const overlayStyle = {
  position: "fixed",
  inset: 0,
  background: "rgba(0, 0, 0, 0.25)",
  display: "flex",
  justifyContent: "flex-end",
  zIndex: 10000,
};

const drawerStyle = {
  width: 440,
  maxWidth: "95vw",
  height: "100%",
  display: "flex",
  flexDirection: "column",
};

const threadStyle = {
  flex: 1,
  overflowY: "auto",
  padding: 16,
};

const suggestionStyle = {
  textAlign: "left",
  padding: "10px 12px",
  borderRadius: 8,
  border: "1px solid rgba(128,128,128,0.3)",
  background: "transparent",
  color: "inherit",
  cursor: "pointer",
  fontSize: 13,
};

const inputStyle = {
  flex: 1,
  padding: "10px 12px",
  borderRadius: 8,
  border: "1px solid rgba(128,128,128,0.35)",
  background: "transparent",
  color: "inherit",
  fontSize: 13,
};

const selectStyle = {
  padding: "4px 8px",
  borderRadius: 6,
  fontSize: 12,
  cursor: "pointer",
};

function isDarkColor(hex) {
  if (typeof hex !== "string" || !/^#[0-9a-f]{6}$/i.test(hex)) return false;
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return (0.299 * r + 0.587 * g + 0.114 * b) / 255 < 0.5;
}

const chipCloseStyle = {
  border: "none",
  background: "transparent",
  cursor: "pointer",
  color: "inherit",
  padding: "2px 4px",
};

AIPanel.propTypes = {
  isOpen: PropTypes.bool.isRequired,
  onClose: PropTypes.func.isRequired,
  getEditor: PropTypes.func.isRequired,
};

export default AIPanel;
