"use client";

import { useEffect, useRef, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { AiPageHeader } from "@/features/ai/components/ai-page-header";
import { aiDict } from "@/features/ai/dict";
import {
  canSendMoreChatMessages,
  MAX_MESSAGES_PER_CHAT,
} from "@/features/ai/constants/ai-conversation.constants";
import { useSendAiMessageMutation } from "@/features/ai/hooks/use-ai";
import type { AiMessage } from "@/features/ai/types";
import { useProfile } from "@/features/profile/hooks/use-profile";
import { toPersianDigits } from "@/lib/to-english-digits";

const EMPTY_MESSAGES: AiMessage[] = [];

type AiChatViewProps = {
  agentId: string;
  agentName: string;
  conversationId?: string;
  initialMessages?: AiMessage[];
  backHref?: string;
};

export function AiChatView({
  agentId,
  agentName,
  conversationId: initialConversationId,
  initialMessages = EMPTY_MESSAGES,
  backHref = "/panel/ai",
}: AiChatViewProps) {
  const router = useRouter();
  const { data: profile } = useProfile();
  const sendMessageMutation = useSendAiMessageMutation();
  const tokenBalance = profile?.subscription.aiTokenBalance;
  const isTokensDepleted = tokenBalance !== undefined && tokenBalance <= 0;
  const tokenBalanceSubtitle =
    tokenBalance !== undefined
      ? aiDict.tokenBalance.replace(
          "{count}",
          toPersianDigits(tokenBalance.toLocaleString()),
        )
      : undefined;
  const [conversationId, setConversationId] = useState(initialConversationId);
  const [messages, setMessages] = useState<AiMessage[]>(initialMessages);
  const isMessageLimitReached = !canSendMoreChatMessages(messages.length);
  const messageLimitText = aiDict.messageLimitReached.replace(
    "{max}",
    toPersianDigits(MAX_MESSAGES_PER_CHAT),
  );
  const cannotSendMessage = isTokensDepleted || isMessageLimitReached;
  const [draft, setDraft] = useState("");
  const [shareData, setShareData] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, sendMessageMutation.isPending]);

  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const content = draft.trim();
    if (!content || sendMessageMutation.isPending || cannotSendMessage) {
      return;
    }

    setDraft("");

    sendMessageMutation.mutate(
      {
        agentId,
        content,
        conversationId,
        ...(shareData ? { shareData: true } : {}),
      },
      {
        onSuccess: (data) => {
          setShareData(false);
          setConversationId(data.conversationId);
          setMessages((current) => [
            ...current,
            data.userMessage,
            data.agentMessage,
          ]);

          if (!initialConversationId && data.conversationId) {
            router.replace(`/panel/ai/conversations/${data.conversationId}`);
          }
        },
      },
    );
  };

  return (
    <div className="flex min-h-0 flex-1 flex-col">
      <div className="fixed inset-x-0 top-0 z-40 border-b border-border/60 bg-background/95 backdrop-blur-md md:start-64">
        <div className="mx-auto w-full max-w-3xl px-4 py-3 sm:px-6">
          <AiPageHeader
            title={agentName}
            subtitle={tokenBalanceSubtitle}
            backHref={backHref}
            showHistory
          />
        </div>
      </div>

      <div
        className={`mx-auto flex w-full max-w-3xl flex-1 flex-col gap-4 px-4 pb-4 sm:gap-5 sm:px-6 sm:pb-6 ${
          tokenBalanceSubtitle ? "pt-[5.75rem]" : "pt-[4.5rem]"
        }`}
      >
        <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-3xl bg-card shadow-soft-sm">
          <div className="flex min-h-[420px] flex-1 flex-col gap-3 overflow-y-auto p-4 sm:p-5">
          {messages.length === 0 && !sendMessageMutation.isPending && !cannotSendMessage ? (
            <p className="py-8 text-center text-sm text-muted-foreground">
              {aiDict.emptyChat}
            </p>
          ) : null}

          {messages.map((message) => {
            const isUser = message.role === "USER";

            return (
              <div
                key={message.id}
                className={`flex ${isUser ? "justify-start" : "justify-end"}`}
              >
                <div
                  className={`max-w-[85%] rounded-3xl px-4 py-3 text-sm leading-7 shadow-soft-sm ${
                    isUser
                      ? "bg-primary text-primary-foreground"
                      : "bg-muted text-foreground"
                  }`}
                >
                  {message.content}
                </div>
              </div>
            );
          })}

          {sendMessageMutation.isPending ? (
            <div className="flex justify-end">
              <div className="rounded-3xl bg-muted px-4 py-3 text-sm text-muted-foreground">
                {aiDict.sending}
              </div>
            </div>
          ) : null}

          <div ref={bottomRef} />
        </div>

        {isTokensDepleted ? (
          <div className="border-t border-border p-4">
            <p className="text-center text-sm leading-7 text-muted-foreground">
              {aiDict.tokensDepletedMessage}
            </p>
          </div>
        ) : isMessageLimitReached ? (
          <div className="border-t border-border p-4">
            <p className="text-center text-sm leading-7 text-muted-foreground">
              {messageLimitText}
            </p>
          </div>
        ) : (
          <form
            onSubmit={handleSubmit}
            className="flex flex-col gap-3 border-t border-border p-4"
          >
            <label className="flex items-start gap-3 rounded-2xl bg-input px-3 py-2.5 ring-1 ring-border">
              <input
                type="checkbox"
                checked={shareData}
                onChange={(event) => setShareData(event.target.checked)}
                className="mt-0.5 size-4 shrink-0 rounded border-border text-primary focus:ring-primary"
              />
              <span className="min-w-0 space-y-0.5">
                <span className="block text-sm font-medium text-foreground">
                  {aiDict.shareDataLabel}
                </span>
                <span className="block text-xs leading-5 text-muted-foreground">
                  {aiDict.shareDataHint}
                </span>
              </span>
            </label>

            <div className="flex items-end gap-2">
              <textarea
                value={draft}
                onChange={(event) => setDraft(event.target.value)}
                placeholder={aiDict.messagePlaceholder}
                rows={2}
                className="min-h-12 flex-1 resize-none rounded-2xl bg-input px-4 py-3 text-sm text-foreground shadow-soft-sm outline-none ring-1 ring-border transition-shadow placeholder:text-muted-foreground focus:ring-2 focus:ring-primary"
              />
              <button
                type="submit"
                disabled={!draft.trim() || sendMessageMutation.isPending}
                className="inline-flex h-12 shrink-0 items-center justify-center rounded-2xl bg-primary px-5 text-sm font-semibold text-primary-foreground shadow-soft-sm transition-all hover:brightness-105 disabled:cursor-not-allowed disabled:opacity-70"
              >
                {sendMessageMutation.isPending ? aiDict.sending : aiDict.send}
              </button>
            </div>
          </form>
        )}
        </div>
      </div>
    </div>
  );
}
