import { useState, useCallback, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Pin, X, ChevronUp, ChevronDown, ExternalLink } from 'lucide-react';
import { client } from '@/client/client.gen';

interface PinInfo {
  message: string;
  pinned_at: string;
}

interface RoomPinBarProps {
  roomId: string;
  onSelectMessage?: (messageId: string) => void;
}

export function RoomPinBar({ roomId, onSelectMessage }: RoomPinBarProps) {
  const [pins, setPins] = useState<PinInfo[]>([]);
  const [isExpanded, setIsExpanded] = useState(false);

  const loadPins = useCallback(async () => {
    try {
      const resp = await client.get({
        url: `/api/rooms/${roomId}/pins`,
      });
      const data = (resp.data as any)?.data as PinInfo[] | undefined;
      if (data) {
        setPins(data);
      }
    } catch (err) {
      console.error('Failed to load pins:', err);
    }
  }, [roomId]);

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

  const handleUnpin = useCallback(async (messageId: string) => {
    try {
      await client.delete({
        url: `/api/rooms/${roomId}/messages/${messageId}/pin`,
      });
      setPins((prev) => prev.filter((p) => p.message !== messageId));
    } catch (err) {
      console.error('Failed to unpin message:', err);
    }
  }, [roomId]);

  if (pins.length === 0) {
    return null;
  }

  if (!isExpanded) {
    return (
      <div className="border-b border-border/50 bg-muted/30">
        <button
          type="button"
          onClick={() => setIsExpanded(true)}
          className="flex w-full items-center gap-2 px-4 py-2 text-left hover:bg-muted/50"
        >
          <Pin className="h-4 w-4 text-muted-foreground" />
          <span className="text-xs text-muted-foreground">
            {pins.length} pinned message{pins.length !== 1 ? 's' : ''}
          </span>
          <span className="flex-1 truncate text-sm text-foreground">
            {pins[0]?.message}
          </span>
          <ChevronUp className="h-4 w-4 text-muted-foreground" />
        </button>
      </div>
    );
  }

  return (
    <div className="border-b border-border/50 bg-muted/30">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-2">
        <div className="flex items-center gap-2">
          <Pin className="h-4 w-4 text-muted-foreground" />
          <span className="text-xs font-medium text-muted-foreground">
            Pinned Messages ({pins.length})
          </span>
        </div>
        <Button
          variant="ghost"
          size="sm"
          className="h-6 px-2 text-xs"
          onClick={() => setIsExpanded(false)}
        >
          <ChevronDown className="mr-1 h-3 w-3" />
          Collapse
        </Button>
      </div>

      {/* Pinned messages list */}
      <div className="max-h-48 overflow-y-auto">
        {pins.map((pin, index) => (
          <div
            key={index}
            className="group flex items-start gap-2 border-t border-border/30 px-4 py-2 hover:bg-muted/50"
          >
            <Pin className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-2">
                <span className="text-[10px] text-muted-foreground">
                  {new Date(pin.pinned_at).toLocaleDateString()}
                </span>
              </div>
              <p className="mt-0.5 line-clamp-2 text-sm text-foreground">
                {pin.message}
              </p>
              <div className="mt-1 flex items-center gap-1">
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-5 px-1.5 text-[10px]"
                  onClick={() => onSelectMessage?.(pin.message)}
                >
                  <ExternalLink className="mr-1 h-3 w-3" />
                  Jump
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-5 px-1.5 text-[10px] text-destructive hover:text-destructive"
                  onClick={() => handleUnpin(pin.message)}
                >
                  <X className="mr-1 h-3 w-3" />
                  Unpin
                </Button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// Pin button for message actions
interface PinButtonProps {
  roomId: string;
  messageId: string;
  isPinned: boolean;
  onPinChange?: (isPinned: boolean) => void;
}

export function PinButton({ roomId, messageId, isPinned, onPinChange }: PinButtonProps) {
  const [isLoading, setIsLoading] = useState(false);

  const handleToggle = useCallback(async () => {
    setIsLoading(true);
    try {
      if (isPinned) {
        await client.delete({
          url: `/api/rooms/${roomId}/messages/${messageId}/pin`,
        });
        onPinChange?.(false);
      } else {
        await client.post({
          url: `/api/rooms/${roomId}/messages/${messageId}/pin`,
        });
        onPinChange?.(true);
      }
    } catch (err) {
      console.error('Failed to toggle pin:', err);
    } finally {
      setIsLoading(false);
    }
  }, [roomId, messageId, isPinned, onPinChange]);

  return (
    <button
      type="button"
      title={isPinned ? 'Unpin' : 'Pin'}
      onClick={handleToggle}
      disabled={isLoading}
      className="group/btn relative flex items-center justify-center rounded-md p-1.5 transition-colors text-muted-foreground hover:bg-accent hover:text-foreground"
    >
      <Pin className="h-3.5 w-3.5" />
      <span className="absolute -top-7 left-1/2 -translate-x-1/2 whitespace-nowrap rounded bg-foreground px-2 py-0.5 text-xs text-background opacity-0 shadow-sm transition-opacity group-hover/btn:opacity-100 pointer-events-none">
        {isPinned ? 'Unpin' : 'Pin'}
      </span>
    </button>
  );
}
