"use client";

import { useEffect, useState } from "react";
import { getPinnedMessages, unpinMessage, Message } from "@/lib/api";
import { Pin, X } from "lucide-react";

interface PinnedMessagesProps {
  channelId: string;
}

export function PinnedMessages({ channelId }: PinnedMessagesProps) {
  const [pins, setPins] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);

  const loadPins = () => {
    setLoading(true);
    getPinnedMessages(channelId)
      .then(setPins)
      .catch(console.error)
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    loadPins();
  }, [channelId]);

  const handleUnpin = (msgId: string) => {
    unpinMessage(msgId)
      .then(() => {
        setPins((prev) => prev.filter((m) => m.id !== msgId));
      })
      .catch(console.error);
  };

  return (
    <div className="border-b border-gray-200 p-3">
      <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2 flex items-center gap-1.5">
        <Pin size={14} />
        Pinned ({pins.length})
      </h4>
      {loading ? (
        <div className="text-xs text-gray-400 animate-pulse">Loading pins...</div>
      ) : pins.length === 0 ? (
        <p className="text-xs text-gray-400">No pinned messages.</p>
      ) : (
        <div className="space-y-2 max-h-48 overflow-y-auto">
          {pins.map((msg) => (
            <div
              key={msg.id}
              className="group p-2 rounded-md bg-gray-50 border border-gray-100"
            >
              <div className="flex items-start justify-between gap-2">
                <div className="flex-1 min-w-0">
                  <p className="text-xs text-gray-700 break-words line-clamp-2">
                    {msg.text || msg.content || ""}
                  </p>
                  <p className="text-xs text-gray-400 mt-0.5">
                    {msg.user?.name || msg.user?.email || "Unknown"}
                  </p>
                </div>
                <button
                  onClick={() => handleUnpin(msg.id)}
                  className="opacity-0 group-hover:opacity-100 text-gray-400 hover:text-slack-red p-0.5 rounded transition-all flex-shrink-0"
                >
                  <X size={12} />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}