import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { InquiryDetailDialog } from '../inquiry-detail-dialog';
import type { InquiryReadDto } from '@/lib/inquiries-api';

// Mock the hook
const mockMarkReadMutate = vi.fn();
vi.mock('@/lib/hooks/use-inquiries', () => ({
  useMarkInquiryRead: () => ({
    mutate: mockMarkReadMutate,
    isPending: false,
  }),
}));

// Mock InquiryStatusBadge
vi.mock('@/components/inquiries/inquiry-row', () => ({
  InquiryStatusBadge: ({ isRead }: { isRead: boolean }) => (
    <span>{isRead ? 'Đã đọc' : 'Chưa đọc'}</span>
  ),
}));

// Mock Dialog
vi.mock('@/components/ui/dialog', () => ({
  Dialog: ({ children, open }: { children: React.ReactNode; open: boolean }) =>
    open ? <div data-testid="dialog">{children}</div> : null,
  DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  DialogHeader: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  DialogTitle: ({ children }: { children: React.ReactNode }) => <h2>{children}</h2>,
  DialogDescription: ({ children }: { children: React.ReactNode }) => <p>{children}</p>,
  DialogFooter: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

const mockInquiry: InquiryReadDto = {
  id: 'inq-1',
  listingId: 'listing-1',
  listingTitle: 'Căn hộ 3PN Quận 2',
  userId: 'user-1',
  userName: 'Nguyễn Minh C',
  userPhone: '0912345678',
  message: 'Tôi muốn xem nhà vào thứ 7 tuần sau',
  phone: null,
  isRead: false,
  createdAt: '2026-02-10T09:00:00Z',
};

describe('InquiryDetailDialog', () => {
  beforeEach(() => {
    mockMarkReadMutate.mockClear();
  });

  it('returns null when inquiry is null', () => {
    const { container } = render(
      <InquiryDetailDialog inquiry={null} open={true} onOpenChange={vi.fn()} />,
    );
    expect(container.firstChild).toBeNull();
  });

  it('renders dialog title', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText('Chi tiết liên hệ')).toBeInTheDocument();
  });

  it('renders listing title', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText('Căn hộ 3PN Quận 2')).toBeInTheDocument();
  });

  it('renders user name', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText('Nguyễn Minh C')).toBeInTheDocument();
  });

  it('renders phone number', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText(/0912[\s]?345[\s]?678/)).toBeInTheDocument();
  });

  it('renders inquiry message', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText('Tôi muốn xem nhà vào thứ 7 tuần sau')).toBeInTheDocument();
  });

  it('renders unread status', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText('Chưa đọc')).toBeInTheDocument();
  });

  it('renders mark as read button when unread', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText('Đánh dấu đã đọc')).toBeInTheDocument();
  });

  it('does not render mark as read button when already read', () => {
    const readInquiry = { ...mockInquiry, isRead: true };
    render(
      <InquiryDetailDialog inquiry={readInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.queryByText('Đánh dấu đã đọc')).not.toBeInTheDocument();
  });

  it('calls mutate when mark as read is clicked', async () => {
    const user = userEvent.setup();
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );

    await user.click(screen.getByText('Đánh dấu đã đọc'));
    expect(mockMarkReadMutate).toHaveBeenCalledWith('inq-1', expect.any(Object));
  });

  it('renders quick contact links', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    // Emoji prefixed text
    const content = document.body.textContent;
    expect(content).toContain('Gọi điện');
    expect(content).toContain('Zalo');
  });

  it('renders close button', () => {
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText('Đóng')).toBeInTheDocument();
  });

  it('calls onOpenChange when close is clicked', async () => {
    const user = userEvent.setup();
    const onOpenChange = vi.fn();
    render(
      <InquiryDetailDialog inquiry={mockInquiry} open={true} onOpenChange={onOpenChange} />,
    );

    await user.click(screen.getByText('Đóng'));
    expect(onOpenChange).toHaveBeenCalledWith(false);
  });

  it('uses inquiry.phone when available over userPhone', () => {
    const inquiryWithPhone = { ...mockInquiry, phone: '0987654321' };
    render(
      <InquiryDetailDialog inquiry={inquiryWithPhone} open={true} onOpenChange={vi.fn()} />,
    );
    expect(screen.getByText(/0987[\s]?654[\s]?321/)).toBeInTheDocument();
  });
});
