import { useState } from "react";
import type { Channel } from "@/types/Channel";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { createChannel } from "@/api";

interface Props {
  channels: Channel[];
  activeId: string | null;
  onSelect: (id: string) => void;
  onChannelCreated: () => void;
}

export function ChannelSidebar({ channels, activeId, onSelect, onChannelCreated }: Props) {
  const [newName, setNewName] = useState("");
  const [creating, setCreating] = useState(false);

  async function handleCreate() {
    if (!newName.trim()) return;
    setCreating(true);
    await createChannel({ name: newName.trim(), description: "" });
    setNewName("");
    setCreating(false);
    onChannelCreated();
  }

  return (
    <div className="flex flex-col h-full w-60 border-r bg-sidebar text-sidebar-foreground">
      <div className="p-4 font-semibold text-lg">Colony</div>
      <Separator />
      <ScrollArea className="flex-1">
        <div className="p-2 space-y-1">
          {channels.map((ch) => (
            <button
              type="button"
              key={ch.id}
              onClick={() => onSelect(ch.id)}
              className={`w-full text-left px-3 py-1.5 rounded-md text-sm transition-colors ${
                ch.id === activeId
                  ? "bg-sidebar-accent text-sidebar-accent-foreground font-medium"
                  : "hover:bg-sidebar-accent/50"
              }`}
            >
              # {ch.name}
            </button>
          ))}
        </div>
      </ScrollArea>
      <Separator />
      <div className="p-2 flex gap-1">
        <Input
          placeholder="new channel"
          value={newName}
          onChange={(e) => setNewName(e.target.value)}
          onKeyDown={(e) => e.key === "Enter" && handleCreate()}
          className="text-sm h-8"
        />
        <Button size="sm" onClick={handleCreate} disabled={creating} className="h-8">
          +
        </Button>
      </div>
    </div>
  );
}
