import { cn } from "@code/ui/lib/utils";
import { ArrowLeft, ArrowUp, ExternalLink, Sparkles } from "lucide-react";
import type { FormEvent } from "react";

import {
  Conversation,
  ConversationContent,
  ConversationScrollButton,
} from "../ai-elements/conversation";
import {
  Message,
  MessageContent,
  MessageResponse,
} from "../ai-elements/message";
import {
  PromptInput,
  PromptInputBody,
  PromptInputSubmit,
  PromptInputTextarea,
} from "../ai-elements/prompt-input";
import type { MobileWorkspaceView } from "./models";

export interface MobileWorkChatScreenProps {
  readonly composerValue: string;
  readonly data: MobileWorkspaceView;
  readonly onBack: () => void;
  readonly onComposerChange: (value: string) => void;
  readonly onComposerMessageSubmit?: (message: string) => Promise<void>;
  readonly onComposerSubmit: (event: FormEvent<HTMLFormElement>) => void;
  readonly statusMessage?: string;
}

export const MobileWorkChatScreen = ({
  composerValue,
  data,
  onBack,
  onComposerChange,
  onComposerMessageSubmit,
  onComposerSubmit,
  statusMessage,
}: MobileWorkChatScreenProps) => {
  const workUnit = data.selectedWorkUnit;

  return (
    <div className="mx-auto flex h-[100dvh] max-h-[858px] min-h-[700px] w-full max-w-[390px] flex-col overflow-hidden bg-white text-[#0b0b0a]">
      <header className="flex h-20 shrink-0 items-center border-b border-[#eff0ec] bg-white px-4">
        <button
          aria-label="Back to daily focus"
          className="flex size-10 items-center justify-center rounded-full bg-[#f2f3ef]"
          onClick={onBack}
          type="button"
        >
          <ArrowLeft className="size-5" />
        </button>
        <div className="min-w-0 flex-1 px-3 text-center">
          <p className="truncate text-[15px] font-semibold">
            {workUnit?.title ?? "Work chat"}
          </p>
          <p className="text-[10px] text-[#807b76]">
            {workUnit
              ? `${workUnit.code} · ${workUnit.statusLabel}`
              : "Loading work unit"}
          </p>
        </div>
        {workUnit?.reviewUrl ? (
          <a
            aria-label={`Open pull request ${workUnit.pullRequestNumber ?? ""}`}
            className="flex size-10 items-center justify-center rounded-full bg-[#c8ff00]"
            href={workUnit.reviewUrl}
            rel="noreferrer"
            target="_blank"
          >
            <ExternalLink className="size-5" />
          </a>
        ) : (
          <span className="size-10" />
        )}
      </header>
      <main className="min-h-0 flex-1 bg-[#fefefe]">
        <Conversation className="h-full">
          <ConversationContent className="min-h-full gap-5 px-4 pt-5 pb-6">
            {workUnit ? (
              <section className="rounded-[22px] bg-[#e8efff] p-4 text-[#14265f]">
                <div className="flex items-center text-[10px] font-semibold text-[#315dc0]">
                  {workUnit.statusLabel.toUpperCase()}
                  <span className="ml-auto">{workUnit.progress}%</span>
                </div>
                <p className="mt-2 text-[17px] leading-5 font-semibold">
                  {workUnit.nextAction}
                </p>
                <p className="mt-1 line-clamp-2 text-[12px] leading-4 opacity-70">
                  {workUnit.summary}
                </p>
                {workUnit.reviewUrl ? (
                  <a
                    className="mt-4 flex h-10 items-center justify-center gap-2 rounded-[14px] bg-black text-[12px] font-semibold text-white"
                    href={workUnit.reviewUrl}
                    rel="noreferrer"
                    target="_blank"
                  >
                    Review PR #{workUnit.pullRequestNumber}
                    <ExternalLink className="size-4" />
                  </a>
                ) : null}
              </section>
            ) : null}
            <Message className="max-w-full gap-0" from="assistant">
              <MessageContent className="w-full bg-transparent p-0 text-[#11110f] dark:text-[#11110f]">
                <div className="flex items-center gap-2">
                  <span className="flex size-7 items-center justify-center rounded-[9px] bg-[#c8ff00]">
                    <Sparkles className="size-4" />
                  </span>
                  <strong className="text-[14px]">Zopu</strong>
                  <span className="rounded-full bg-[#f1f1ef] px-2 py-1 text-[9px] text-[#aaa7a3]">
                    WORK PARTNER
                  </span>
                </div>
                <p className="mt-3 text-[15px] leading-5">
                  This chat is scoped to {workUnit?.title ?? "this work unit"}.
                  Add context, change direction, or ask what happens next.
                </p>
              </MessageContent>
            </Message>
            {data.assistant.messages.map((message) => (
              <Message
                className="max-w-full gap-0"
                from={message.role}
                key={message.id}
              >
                <MessageContent
                  className={cn(
                    "max-w-full gap-0 overflow-visible p-0",
                    message.role === "user"
                      ? "ml-auto w-fit max-w-[86%] rounded-[22px] bg-[#0c0c0b] px-4 py-3 text-[15px] leading-5 text-white group-[.is-user]:rounded-[22px] group-[.is-user]:bg-[#0c0c0b] group-[.is-user]:px-4 group-[.is-user]:py-3 group-[.is-user]:text-white"
                      : "w-full bg-transparent text-[#11110f] dark:text-[#11110f]"
                  )}
                >
                  {message.role === "assistant" ? (
                    <>
                      <div className="flex items-center gap-2">
                        <span className="flex size-7 items-center justify-center rounded-[9px] bg-[#c8ff00]">
                          <Sparkles className="size-4" />
                        </span>
                        <strong className="text-[14px]">Zopu</strong>
                      </div>
                      <MessageResponse
                        className="mt-3 text-[15px] leading-5 text-[#11110f] dark:text-[#11110f]"
                        isAnimating={data.assistant.isBusy}
                      >
                        {message.text}
                      </MessageResponse>
                    </>
                  ) : (
                    <span className="whitespace-pre-wrap">{message.text}</span>
                  )}
                </MessageContent>
              </Message>
            ))}
            {data.assistant.isBusy ? (
              <p className="text-[12px] text-[#807b76]">Zopu is working…</p>
            ) : null}
          </ConversationContent>
          <ConversationScrollButton
            aria-label="Scroll to latest message"
            className="bottom-2 size-9 rounded-full border border-[#dededb] bg-white text-black shadow-sm"
          />
        </Conversation>
      </main>
      <footer className="relative h-[106px] shrink-0 border-t border-[#eff0ec] bg-white px-3 pt-3">
        <PromptInput
          className="w-full [&_[data-slot=input-group]]:min-h-[58px] [&_[data-slot=input-group]]:rounded-full [&_[data-slot=input-group]]:border-0 [&_[data-slot=input-group]]:bg-[#f2f3ef] [&_[data-slot=input-group]]:px-3 [&_[data-slot=input-group]]:py-1.5 [&_[data-slot=input-group]]:shadow-none [&_[data-slot=input-group]]:dark:bg-[#f2f3ef]"
          onSubmit={async (message) => {
            if (onComposerMessageSubmit) {
              await onComposerMessageSubmit(message.text);
              return;
            }
            onComposerChange(message.text);
          }}
        >
          <PromptInputBody>
            <PromptInputTextarea
              aria-label="Ask about this work unit"
              className="max-h-20 min-h-10 flex-1 resize-none bg-transparent px-2 py-2.5 text-[14px] leading-5 shadow-none outline-none placeholder:text-[#aaa7a3] dark:bg-transparent"
              onChange={(event) => onComposerChange(event.currentTarget.value)}
              placeholder="Ask about this work unit..."
              value={composerValue}
            />
            <PromptInputSubmit
              aria-label="Send"
              className="size-11 shrink-0 rounded-full bg-black text-white hover:bg-black/85 disabled:bg-black disabled:text-white disabled:opacity-100"
              disabled={!composerValue.trim() || data.assistant.isBusy}
              size="icon-sm"
              status={data.assistant.isBusy ? "streaming" : "ready"}
            >
              <ArrowUp className="size-5" />
            </PromptInputSubmit>
          </PromptInputBody>
        </PromptInput>
        <p className="mt-1 text-center text-[9px] text-[#b5b2ae]">
          {statusMessage ?? "Messages stay with this work unit"}
        </p>
        <form className="sr-only" onSubmit={onComposerSubmit} />
      </footer>
    </div>
  );
};
