import { useParams } from "react-router-dom";
import { useEffect, useState } from "react";
import axios from "axios";

type Channel ={
    id: number,
    name: string
    description: string
}

type Message = {
    id: number,
    user_id: number,
    username: string,
    content: string,
    date: number
}

type Messages = Message[]

export default function Channel() {
    const { id } = useParams();
    const [channel, setChannel] = useState<Channel>();
    const [messages, setMessages] = useState<Messages>();

    useEffect(() => {
        axios.get(`/api/channels/${id}`).then((res) => {
            setChannel(res.data);
        });

        axios.get(`/api/channels/${id}/messages`).then((res) => {
            setMessages(res.data);
        });
    }, [id]);

    if (!channel || !messages) {
        return <div>Loading...</div>;
    }

    return (
        <div>
            <h1>Channel {channel.name}</h1>
            <ul>
                {messages.map((message) => (
                    <li key={message.id}>{`${message.username}: ${message.content}`}</li>
                ))}
            </ul>
        </div>
    );
}