import { render, screen, fireEvent } from '@testing-library/react';
import { describe, it, expect } from 'vitest';
import { MessageRow } from '../message-row';
import type { Message } from '@alqove/api-client';

const baseMessage: Message = {
  id: 'm1',
  thread_id: 't1',
  author_user_id: 'u1',
  author_role: 'buyer',
  body: 'Where is my package?',
  attachments: [],
  created_at: '2026-05-06T10:00:00Z',
  deleted_at: null,
  deleted_by_user_id: null,
  deleted_by_admin: false,
};

describe('MessageRow', () => {
  it('renders the body and a buyer label when the viewer is the buyer', () => {
    render(<MessageRow message={baseMessage} viewerRole="buyer" viewerUserId="u1" />);
    expect(screen.getByText('Where is my package?')).toBeInTheDocument();
    expect(screen.getByText(/You/)).toBeInTheDocument();
  });

  it('shows a Store label when the post is from the seller', () => {
    render(
      <MessageRow
        message={{
          ...baseMessage,
          author_role: 'seller',
          author_user_id: 'u2',
          body: 'Tracking is updated.',
        }}
        viewerRole="buyer"
        viewerUserId="u1"
        counterpartyName="Revive Boutique"
      />,
    );
    expect(screen.getByText('Revive Boutique')).toBeInTheDocument();
    expect(screen.getByText('Tracking is updated.')).toBeInTheDocument();
  });

  it('shows "(deleted by author)" stub for a self-deleted message', () => {
    render(
      <MessageRow
        message={{
          ...baseMessage,
          body: null,
          deleted_at: '2026-05-06T10:05:00Z',
          deleted_by_admin: false,
        }}
        viewerRole="buyer"
        viewerUserId="u1"
      />,
    );
    expect(screen.getByText(/deleted by author/i)).toBeInTheDocument();
  });

  it('shows "(deleted by Alqove Support)" stub when deleted_by_admin is true', () => {
    render(
      <MessageRow
        message={{
          ...baseMessage,
          body: null,
          deleted_at: '2026-05-06T10:05:00Z',
          deleted_by_admin: true,
        }}
        viewerRole="buyer"
        viewerUserId="u1"
      />,
    );
    expect(screen.getByText(/deleted by Alqove Support/i)).toBeInTheDocument();
  });

  it('renders a thumbnail grid when attachments are present', () => {
    render(
      <MessageRow
        message={{
          ...baseMessage,
          attachments: [
            { url: '/a.jpg', thumb_url: '/a-thumb.jpg', content_type: 'image/jpeg', size_bytes: 1 },
            { url: '/b.jpg', thumb_url: '/b-thumb.jpg', content_type: 'image/jpeg', size_bytes: 2 },
          ],
        }}
        viewerUserId="u1"
      />,
    );
    expect(screen.getAllByRole('button', { name: /Open attachment/i })).toHaveLength(2);
  });

  it('renders system messages as italic muted text with no author label or bubble', () => {
    render(
      <MessageRow
        message={{
          ...baseMessage,
          author_user_id: null,
          author_role: 'system',
          body: 'Seller approved the return.',
        }}
        viewerUserId="u1"
      />,
    );
    const body = screen.getByText('Seller approved the return.');
    expect(body).toBeInTheDocument();
    expect(screen.queryByText('You')).not.toBeInTheDocument();
    expect(screen.queryByText('Buyer')).not.toBeInTheDocument();
    expect(screen.queryByText('Seller')).not.toBeInTheDocument();
    expect(screen.queryByText('Alqove Support')).not.toBeInTheDocument();
    const row = body.closest('[data-testid^="message-row-"]') as HTMLElement;
    expect(row.className).toMatch(/italic/);
    expect(row.className).toMatch(/text-slate-500/);
    expect(row.className).not.toMatch(/bg-slate-100/);
    expect(row).toHaveAttribute('role', 'status');
  });

  it('clicking a thumbnail opens the lightbox', () => {
    render(
      <MessageRow
        message={{
          ...baseMessage,
          attachments: [
            { url: '/a.jpg', thumb_url: '/a-thumb.jpg', content_type: 'image/jpeg', size_bytes: 1 },
          ],
        }}
        viewerUserId="u1"
      />,
    );
    fireEvent.click(screen.getByRole('button', { name: /Open attachment/i }));
    const fullImg = screen
      .getAllByRole('img')
      .find((el) => (el as HTMLImageElement).src.endsWith('/a.jpg'));
    expect(fullImg).toBeDefined();
  });
});
