"use client";

import { FormEvent, KeyboardEvent, ReactNode, useState } from "react";
import { cn } from "@/app/lib/utils";
import { Button } from "./button";
import { ScrollArea } from "./scroll-area";
import { Send } from "lucide-react";

type ChatContainerProps = {
  className?: string;
  children: ReactNode;
};

export function ChatContainer({ className, children }: ChatContainerProps) {
  return (
    <div
      className={cn(
        "flex h-full min-h-0 flex-col rounded-lg border border-border bg-card",
        className,
      )}
    >
      {children}
    </div>
  );
}

type ChatMessagesProps = {
  className?: string;
  children: ReactNode;
};

export function ChatMessages({ className, children }: ChatMessagesProps) {
  return (
    <ScrollArea className={cn("flex-1 min-h-0", className)}>
      <div className="space-y-3 p-3">{children}</div>
    </ScrollArea>
  );
}

type ChatMessageProps = {
  role: "user" | "assistant" | "system";
  content?: string;
  className?: string;
  children?: ReactNode;
};

export function ChatMessage({
  role,
  content,
  className,
  children,
}: ChatMessageProps) {
  const isUser = role === "user";
  const isSystem = role === "system";

  return (
    <div
      className={cn(
        "flex w-full",
        isUser ? "justify-end" : "justify-start",
        isSystem && "justify-center",
      )}
    >
      <div
        className={cn(
          "max-w-[92%] rounded-xl px-3 py-2 text-sm shadow-sm",
          isUser &&
            "bg-primary text-primary-foreground rounded-br-xs border border-primary-border",
          role === "assistant" &&
            "bg-muted/70 text-foreground rounded-bl-xs border border-border",
          isSystem &&
            "max-w-full bg-transparent text-center text-xs text-muted-foreground border border-dashed border-border px-2 py-1 rounded",
          className,
        )}
      >
        {content ? <p className="whitespace-pre-wrap break-words">{content}</p> : null}
        {children}
      </div>
    </div>
  );
}

type ChatInputProps = {
  onSubmit: (message: string) => void | Promise<void>;
  placeholder?: string;
  disabled?: boolean;
};

export function ChatInput({
  onSubmit,
  placeholder = "Type a message...",
  disabled = false,
}: ChatInputProps) {
  const [value, setValue] = useState("");

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    if (disabled) return;
    const trimmed = value.trim();
    if (!trimmed) return;
    await onSubmit(trimmed);
    setValue("");
  };

  const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
    if (event.key === "Enter" && !event.shiftKey) {
      event.preventDefault();
      void handleSubmit(event);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="border-t border-border p-3">
      <div className="flex items-end gap-2">
        <textarea
          value={value}
          onChange={(event) => setValue(event.target.value)}
          onKeyDown={onKeyDown}
          rows={2}
          disabled={disabled}
          placeholder={placeholder}
          className="min-h-[62px] max-h-40 flex-1 resize-y rounded-md border border-input bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:opacity-50"
        />
        <Button type="submit" size="icon" disabled={disabled || !value.trim()}>
          <Send className="h-4 w-4" />
        </Button>
      </div>
      <p className="mt-1 text-[11px] text-muted-foreground">
        Enter to send, Shift+Enter for a newline.
      </p>
    </form>
  );
}

export function TypingIndicator() {
  return (
    <div className="flex items-center gap-1 px-2 py-1 text-xs text-muted-foreground">
      <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/70" />
      <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/70 [animation-delay:120ms]" />
      <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground/70 [animation-delay:240ms]" />
      AI is typing...
    </div>
  );
}
