import type { FormEvent } from "react";
import { useState } from "react";

interface UseMobileWorkspaceOptions {
  readonly initialExpanded?: boolean;
  readonly onCreateIssue: (title: string, body: string) => Promise<void>;
  readonly onSend: (message: string) => Promise<void>;
}

const errorMessage = (error: unknown) =>
  error instanceof Error ? error.message : "Message could not be sent";

export const useMobileWorkspace = ({
  initialExpanded = false,
  onCreateIssue,
  onSend,
}: UseMobileWorkspaceOptions) => {
  const [composerValue, setComposerValue] = useState("");
  const [issueBody, setIssueBody] = useState("");
  const [issueTitle, setIssueTitle] = useState("");
  const [expanded, setExpanded] = useState(initialExpanded);
  const [statusMessage, setStatusMessage] = useState<string>();

  const handleComposerChange = (value: string) => {
    setComposerValue(value);
    setStatusMessage(undefined);
  };

  const handleComposerSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const message = composerValue.trim();
    if (!message) {
      return;
    }
    setStatusMessage("Sending to Zopu…");
    const sendMessage = async () => {
      try {
        await onSend(message);
        setComposerValue("");
        setStatusMessage("Sent to Zopu");
      } catch (error) {
        setStatusMessage(errorMessage(error));
      }
    };
    void sendMessage();
  };

  const handleCreateIssueSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const title = issueTitle.trim();
    const body = issueBody.trim();
    if (!title || !body) {
      return;
    }
    setStatusMessage("Creating project work…");
    const createIssue = async () => {
      try {
        await onCreateIssue(title, body);
        setIssueTitle("");
        setIssueBody("");
        setStatusMessage("Project work created");
      } catch (error) {
        setStatusMessage(errorMessage(error));
      }
    };
    void createIssue();
  };

  return {
    composerValue,
    expanded,
    handleComposerChange,
    handleComposerSubmit,
    handleCreateIssueSubmit,
    issueBody,
    issueTitle,
    setExpanded,
    setIssueBody,
    setIssueTitle,
    statusMessage,
  };
};
