import { Loader2, Paperclip, Send, X } from "lucide-react";
import React from "react";
import { FileIcon } from "~/components/file-icon"; // Adjust path
import { sendMessage } from "~/lib/api/client/channel"; // Adjust path
import { uploadFiles } from "~/lib/api/client/file"; // Adjust path
import type { Uuid } from "~/lib/api/types"; // Adjust path
import { cn, formatFileSize } from "~/lib/utils"; // Adjust path
import TextBox from "./custom-ui/text-box"; // Adjust path, assuming TextBox is in ./custom-ui/
import { Button } from "./ui/button"; // Adjust path
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip"; // Adjust path

export interface MessageBoxProps {
    channelId: string;
}

export default function MessageBox({ channelId }: MessageBoxProps) {
    const [text, setText] = React.useState("");
    const [attachments, setAttachments] = React.useState<File[]>([]);
    const [isLoading, setIsLoading] = React.useState(false);

    const fileInputRef = React.useRef<HTMLInputElement>(null);
    const textBoxRef = React.useRef<HTMLDivElement>(null);

    const handleSendMessage = async () => {
        const content = text.trim();
        if ((!content && attachments.length === 0) || isLoading) return;

        setIsLoading(true);
        try {
            let uploadedAttachments: Uuid[] = [];
            if (attachments.length > 0) {
                uploadedAttachments = await uploadFiles(attachments);
            }
            await sendMessage(channelId, text, uploadedAttachments);
            setText("");
            setAttachments([]);

            setTimeout(() => textBoxRef.current?.focus(), 0);
        } catch (error) {
            console.error("Failed to send message:", error);
        } finally {
            setIsLoading(false);
        }
    };

    const addAttachment = () => {
        if (attachments.length >= 10 || isLoading) return;
        fileInputRef.current?.click();
    };

    const onFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const files = Array.from(e.target.files || []);
        if (files.length === 0) return;

        setAttachments((prev) => {
            const newAttachments = [...prev, ...files];
            return newAttachments.slice(0, 10);
        });

        if (fileInputRef.current) {
            fileInputRef.current.value = "";
        }
        setTimeout(() => textBoxRef.current?.focus(), 0);
    };

    const removeAttachment = (indexToRemove: number) => {
        setAttachments((prev) => prev.filter((_, i) => i !== indexToRemove));
        setTimeout(() => textBoxRef.current?.focus(), 0);
    };

    const handleKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
        if (e.key === "Enter" && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    };

    React.useEffect(() => {
        setText("");
        setAttachments([]);
        setIsLoading(false);
        setTimeout(() => textBoxRef.current?.focus(), 0);
    }, [channelId]);

    const canSend = (text.trim().length > 0 || attachments.length > 0) && !isLoading;
    const attachmentsRemaining = 10 - attachments.length;

    return (
        <div className="border-t bg-background p-2">
            {attachments.length > 0 && (
                <div className="mb-2 max-h-44 space-y-2 overflow-y-auto rounded-md border bg-muted/20 p-2 scrollbar-thin scrollbar-thumb-muted-foreground/30 scrollbar-track-transparent">
                    {attachments.map((file, i) => (
                        <div
                            key={`${file.name}-${file.lastModified}-${i}`}
                            className="flex items-center gap-2.5 rounded-md border bg-card p-2 text-sm shadow-sm"
                        >
                            <FileIcon contentType={file.type} className="h-7 w-7 flex-shrink-0 text-muted-foreground" />
                            <div className="min-w-0 flex-1">
                                <p className="truncate font-medium text-card-foreground">{file.name}</p>
                                <p className="text-xs text-muted-foreground">{formatFileSize(file.size)}</p>
                            </div>
                            <TooltipProvider delayDuration={100}>
                                <Tooltip>
                                    <TooltipTrigger asChild>
                                        <Button
                                            variant="ghost"
                                            size="icon"
                                            className="h-7 w-7 flex-shrink-0 text-muted-foreground hover:text-destructive"
                                            onClick={() => removeAttachment(i)}
                                            disabled={isLoading}
                                            aria-label={`Remove ${file.name}`}
                                        >
                                            <X className="h-4 w-4" />
                                        </Button>
                                    </TooltipTrigger>
                                    <TooltipContent side="top">
                                        <p>Remove attachment</p>
                                    </TooltipContent>
                                </Tooltip>
                            </TooltipProvider>
                        </div>
                    ))}
                </div>
            )}

            <div
                className={cn(
                    "grid gap-x-2 rounded-xl border bg-card p-2.5 shadow-sm transition-all",
                    "focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/30",
                )}
                style={{
                    gridTemplateColumns: "auto 1fr auto",
                    gridTemplateRows: "auto 1fr",
                }}
            >
                <TooltipProvider delayDuration={100}>
                    <Tooltip>
                        <TooltipTrigger asChild>
                            <div className="self-start row-start-1 col-start-1 row-span-2 col-span-1">
                                <input
                                    type="file"
                                    multiple
                                    className="hidden"
                                    ref={fileInputRef}
                                    onChange={onFileChange}
                                    accept="image/*,application/pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt,.zip,.rar,audio/*,video/*"
                                    disabled={isLoading}
                                />
                                <Button
                                    type="button"
                                    size="icon"
                                    variant="ghost"
                                    onClick={addAttachment}
                                    disabled={attachments.length >= 10 || isLoading}
                                    aria-label="Add attachment"
                                >
                                    <Paperclip className="h-5 w-5" />
                                </Button>
                            </div>
                        </TooltipTrigger>
                        <TooltipContent side="top">
                            {attachments.length >= 10 ? (
                                <p>Maximum 10 attachments</p>
                            ) : (
                                <p>Add attachment ({attachmentsRemaining} remaining)</p>
                            )}
                        </TooltipContent>
                    </Tooltip>
                </TooltipProvider>

                <div className="self-center row-start-1 col-start-2 row-span-2 col-span-1">
                    <TextBox
                        ref={textBoxRef}
                        value={text}
                        onChange={setText}
                        placeholder="Message..."
                        aria-label="Message input"
                        onKeyDown={handleKeyDown}
                        wrapperClassName="max-h-40"
                        disabled={isLoading}
                    />
                </div>

                <div className="self-start row-start-1 col-start-3 row-span-2 col-span-1">
                    <Button
                        type="button"
                        size="icon"
                        onClick={handleSendMessage}
                        disabled={!canSend}
                        aria-label="Send message"
                    >
                        {isLoading ? <Loader2 className="h-5 w-5 animate-spin" /> : <Send className="h-5 w-5" />}
                    </Button>
                </div>
            </div>
        </div>
    );
}
