import { useState, useCallback, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Bell, CheckCheck, ExternalLink } from 'lucide-react';
import { client } from '@/client/client.gen';
import { cn } from '@/lib/utils';

interface MentionNotification {
  message_id: string;
  mentioned_by: string;
  mentioned_by_name: string;
  content_preview: string;
  room_id: string;
  room_name: string;
  created_at: string;
}

interface RoomMentionPanelProps {
  onClose: () => void;
  onSelectNotification?: (notification: MentionNotification) => void;
}

export function RoomMentionPanel({ onClose, onSelectNotification }: RoomMentionPanelProps) {
  const [mentions, setMentions] = useState<MentionNotification[]>([]);
  const [isLoading, setIsLoading] = useState(false);

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

  const loadMentions = useCallback(async () => {
    setIsLoading(true);
    try {
      const resp = await client.get({
        url: '/api/me/mentions',
        params: { limit: 50 },
      });
      const data = (resp.data as any)?.data as MentionNotification[] | undefined;
      if (data) {
        setMentions(data);
      }
    } catch (err) {
      console.error('Failed to load mentions:', err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const handleMarkAllRead = useCallback(async () => {
    try {
      await client.post({
        url: '/api/me/mentions/read-all',
      });
      await loadMentions();
    } catch (err) {
      console.error('Failed to mark mentions as read:', err);
    }
  }, [loadMentions]);

  const handleSelectMention = useCallback((mention: MentionNotification) => {
    onSelectNotification?.(mention);
  }, [onSelectNotification]);

  return (
    <div className="flex h-full flex-col bg-background">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-border p-3">
        <div className="flex items-center gap-2">
          <Bell className="h-5 w-5 text-muted-foreground" />
          <h2 className="text-sm font-semibold text-foreground">@ Mentions</h2>
        </div>
        <div className="flex items-center gap-1">
          <Button
            variant="ghost"
            size="sm"
            className="h-7 px-2 text-xs"
            onClick={handleMarkAllRead}
          >
            <CheckCheck className="mr-1 h-3 w-3" />
            Mark all read
          </Button>
          <Button variant="ghost" size="icon" className="h-7 w-7" onClick={onClose}>
            ✕
          </Button>
        </div>
      </div>

      {/* Mentions List */}
      <ScrollArea className="flex-1">
        {isLoading ? (
          <div className="flex items-center justify-center py-8">
            <div className="text-sm text-muted-foreground">Loading...</div>
          </div>
        ) : mentions.length === 0 ? (
          <div className="py-12 text-center">
            <Bell className="mx-auto mb-3 h-12 w-12 text-muted-foreground/50" />
            <p className="text-sm text-muted-foreground">No mentions yet</p>
          </div>
        ) : (
          <div className="space-y-2 p-3">
            {mentions.map((mention) => (
              <button
                key={mention.message_id}
                onClick={() => handleSelectMention(mention)}
                className={cn(
                  'w-full rounded-lg border border-border/50 p-3 text-left transition-colors hover:bg-muted/40'
                )}
              >
                <div className="mb-1 flex items-center justify-between">
                  <span className="text-xs font-medium text-primary">
                    @{mention.mentioned_by_name}
                  </span>
                  <span className="text-[10px] text-muted-foreground">
                    {new Date(mention.created_at).toLocaleString()}
                  </span>
                </div>
                <div className="mb-1 text-xs text-muted-foreground">
                  In <span className="font-medium text-foreground">{mention.room_name}</span>
                </div>
                <div className="text-sm text-foreground break-words line-clamp-2">
                  {mention.content_preview}
                </div>
                <div className="mt-1 flex items-center justify-end">
                  <ExternalLink className="h-3 w-3 text-muted-foreground" />
                </div>
              </button>
            ))}
          </div>
        )}
      </ScrollArea>
    </div>
  );
}
