import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { createPost } from "@/lib/server/api";
import type { CardItem, PostItem } from "@/lib/types";

export function Composer({
  myCards,
  onPosted,
}: {
  myCards: CardItem[];
  onPosted: (post: PostItem) => void;
}) {
  const [content, setContent] = useState("");
  const [cardId, setCardId] = useState<string>("none");
  const [busy, setBusy] = useState(false);

  async function submit() {
    if (!content.trim()) return;
    setBusy(true);
    try {
      const post = await createPost({
        data: {
          content: content.trim(),
          cardId: cardId === "none" ? null : cardId,
        },
      });
      setContent("");
      setCardId("none");
      onPosted(post);
      toast.success("Posted");
    } catch (err) {
      toast.error(err instanceof Error ? err.message : "Could not post");
    } finally {
      setBusy(false);
    }
  }

  return (
    <Card>
      <CardContent className="pt-5 space-y-3">
        <Textarea
          placeholder="Share a pull, call out a trade, or talk ball…"
          value={content}
          onChange={(e) => setContent(e.target.value)}
          maxLength={500}
          rows={3}
        />
        <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
          <Select value={cardId} onValueChange={setCardId}>
            <SelectTrigger className="w-full sm:w-[220px]">
              <SelectValue placeholder="Attach a card" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="none">No card</SelectItem>
              {myCards.map((c) => (
                <SelectItem key={c.id} value={c.id}>
                  {c.playerName} · {c.team}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <Button onClick={() => void submit()} disabled={busy || !content.trim()}>
            {busy ? "Posting…" : "Post"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
