"use client";

import React from "react";

import Image from "next/image";

import { useMutation } from "@tanstack/react-query";

import axios, { AxiosError } from "axios";

import { toast } from "sonner";

import clsx from "clsx";

import { Send } from "lucide-react";

import { cn } from "@/lib/utils";

import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Spinner from "../spinner";

export interface Message {
  content: string;
  sender: {
    name: string;
    avatar: string;
    isOnline: boolean;
    isCurrentUser?: boolean;
  };
  timestamp: string;
}

interface ChatCardProps {
  chatName?: string;
  initialMessages?: Message[];
  currentUser?: {
    name: string;
    avatar: string;
  };
  className?: string;
}

export function ChatCard({
  chatName,
  initialMessages = [],
  currentUser = {
    name: "You",
    avatar:
      "https://ferf1mheo22r9ira.public.blob.vercel-storage.com/avatar-03-n0x8HFv8EUetf9z6ht0wScJKoTHqf8.png",
  },
  className,
}: ChatCardProps) {
  const [messages, setMessages] = React.useState<Message[]>(initialMessages);
  const [inputValue, setInputValue] = React.useState("");

  const mutation = useMutation({
    mutationFn: async (userInput: string) => {
      const url = encodeURI(
        `https://ai-endpoint-one.dev3vds1.link/chatbot/beactio/${userInput}`
      );
      const json = await axios.get(url);

      return json.data;
    },
    onSuccess: (data: { response: string; system_prompt: string }) => {
      const newMessage: Message = {
        content: data.response,
        sender: {
          name: "beactio.ai",
          avatar: "/logo.png",
          isOnline: true,
        },
        timestamp: new Date().toLocaleTimeString([], {
          hour: "numeric",
          minute: "2-digit",
          hour12: true,
        }),
      };
      setMessages((old) => [...old, newMessage]);
    },
    onError: (error) => {
      if (error instanceof AxiosError) {
        if (error.response) {
          const errResponse = error.response.data;
          toast.error("There is something wrong");
          console.log({ errResponse });
        } else if (error.request) {
          toast.error("No response from the server", {
            description: "Failed to fetch the data, server returns null.",
          });
        } else {
          toast.error("Failed to set up the request", {
            description: "There is something wrong when setting up the request",
          });
        }
      }
    },
  });

  const handleSendMessage = () => {
    if (!inputValue.trim()) return;

    const newMessage: Message = {
      content: inputValue,
      sender: {
        name: currentUser.name,
        avatar: currentUser.avatar,
        isOnline: true,
        isCurrentUser: true,
      },
      timestamp: new Date().toLocaleTimeString([], {
        hour: "numeric",
        minute: "2-digit",
        hour12: true,
      }),
    };

    setMessages((prev) => [...prev, newMessage]);
    setInputValue("");

    mutation.mutate(inputValue);
  };

  return (
    <div
      className={cn(
        "w-[360px] mx-auto rounded-2xl overflow-hidden",
        "bg-white text-zinc-900 border border-zinc-200",
        className
      )}
    >
      <div className="flex flex-col h-[480px]">
        {/* Header */}
        <div
          className={cn(
            "px-4 py-3 flex items-center justify-between border-b border-zinc-200"
          )}
        >
          <div className="flex items-center gap-3">
            <div className="relative">
              <div className="relative w-10 h-10 rounded-full flex items-center justify-center overflow-hidden">
                <Image
                  src="/logo.png"
                  className="object-cover"
                  fill={true}
                  alt="logo"
                />
              </div>
              <div
                className={cn(
                  "absolute -bottom-0.5 -right-0.5 w-3 h-3 rounded-full bg-emerald-500 ring-2 ring-white"
                )}
              />
            </div>
            <div>
              <h3 className={cn("font-medium text-zinc-900")}>{chatName}</h3>
            </div>
          </div>
        </div>

        {/* Messages */}
        <div className="flex-1 overflow-y-auto p-4 space-y-4">
          {messages.map((message, idx) => (
            <div key={idx} className={"flex items-start gap-3"}>
              {!message.sender.isCurrentUser && (
                <Image
                  src={message.sender.avatar}
                  alt={message.sender.name}
                  width={36}
                  height={36}
                  className="rounded-full"
                />
              )}

              <div
                className={clsx(
                  message.sender.isCurrentUser ? "ml-auto" : "mr-auto"
                )}
              >
                <div className="text-sm flex items-center gap-2 mb-1">
                  <span className={cn("font-medium text-zinc-900")}>
                    {message.sender.name}
                  </span>
                </div>
                <div
                  className={clsx(
                    "py-2 px-3 rounded-md",
                    message.sender.isCurrentUser
                      ? "bg-accent-foreground"
                      : "bg-accent"
                  )}
                >
                  <p
                    className={cn(
                      "text-sm break-words",
                      message.sender.isCurrentUser
                        ? "text-primary"
                        : "text-zinc-700"
                    )}
                  >
                    {message.content}
                  </p>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Input */}
        <div className={cn("p-4 bg-white")}>
          <div className="flex items-center gap-2">
            <div className="relative flex-1">
              <Input
                disabled={mutation.isPending}
                type="text"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter" && !e.shiftKey) {
                    e.preventDefault();
                    handleSendMessage();
                  }
                }}
                placeholder="Write a message..."
              />
            </div>
            <Button
              disabled={mutation.isPending}
              onClick={handleSendMessage}
              size={"icon"}
            >
              {mutation.isPending ? (
                <Spinner className="w-5 h-5" />
              ) : (
                <Send className="w-5 h-5" />
              )}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
