'use client';

import Image from 'next/image';
import React, { useState } from 'react';

import type { components } from '@/lib/gen';
import { getRelativeTime } from '@/utils/utils';

import { timeRangeColorSets } from '../constants';
import MarketplaceConfirmDialog from '../shared/MarketplaceConfirmDialog';

type Message = components['schemas']['MessageResponse'];

interface MarketplaceChatMessageProps {
  message: Message;
  uniqueTimeRanges: Array<{
    start: number;
    end: number;
    firstMessageId: string;
    firstCreatedAt: string;
  }>;
  _isCurrentUser: boolean;
  mediaId?: string;
  mediaTitle?: string;
  mediaColor?: string;
  mediaExists?: boolean; // Whether the media reference still exists
  mediaType?: string; // 'audio', 'image', 'video', 'link', etc.
  mediaUrl?: string; // URL for link types
  onDelete?: () => void | Promise<void>;
  onEdit?: (
    messageId: string,
    newContent: string | null
  ) => void | Promise<void>; // null = cancel
  isEditing?: boolean;
  onUserClick?: () => void;
  onTimeRangeClick?: (
    timeRange: { start: number; end: number },
    mediaId?: string
  ) => void;
  onRemoveTimeRange?: (messageId: string) => void | Promise<void>;
  onMediaClick?: (mediaId?: string) => void;
  // Submission review props
  isSubmission?: boolean;
  submissionStatus?: 'pending' | 'accepted' | 'rejected';
  isCreator?: boolean;
  onAcceptSubmission?: () => void;
  onRejectSubmission?: () => void;
  onReply?: () => void;
  // Media view grouping: if provided, only show track button when message references different track
  groupedMediaId?: string;
}

const MarketplaceChatMessage: React.FC<MarketplaceChatMessageProps> = ({
  message,
  uniqueTimeRanges,
  _isCurrentUser,
  mediaId,
  mediaTitle,
  mediaColor,
  mediaExists = true,
  mediaType,
  mediaUrl,
  onDelete,
  onEdit,
  isEditing = false,
  onUserClick,
  onTimeRangeClick,
  onMediaClick,
  isSubmission,
  submissionStatus,
  isCreator,
  onAcceptSubmission,
  onRejectSubmission,
  onReply,
  onRemoveTimeRange,
  groupedMediaId,
}) => {
  const [showDeletedMediaDialog, setShowDeletedMediaDialog] = useState(false);
  const [editContent, setEditContent] = useState(message.content);

  // Format relative time in Reddit-style format (e.g., "1 min ago", "2h ago")
  const formatTimeAgo = (dateString: string) => {
    const relativeTime = getRelativeTime(dateString);
    // Replace "m" with "min" for minutes to match Reddit format
    // Handle both standalone "m" and "m" followed by comma/space/end
    return relativeTime.replace(/(\d+)m(?=\s|,|$)/g, '$1 min');
  };

  // Get consistent tonal color set for a time range message based on its ID
  const getTimeRangeColorSet = (messageId: string) => {
    const getHashValue = (seed: string) => {
      const x = Math.sin(
        seed.split('').reduce((acc, char) => {
          return acc + char.charCodeAt(0);
        }, 0) * 10000
      );
      return x - Math.floor(x);
    };

    const hashValue = getHashValue(messageId);
    return timeRangeColorSets[
      Math.floor(hashValue * timeRangeColorSets.length) %
        timeRangeColorSets.length
    ];
  };

  return (
    <div id={`message-${message.id}`} className='group flex gap-2 py-1'>
      <button
        onClick={onUserClick}
        className='flex-shrink-0 cursor-pointer self-start transition-opacity hover:opacity-80'
      >
        <div
          className={`flex h-6 w-6 items-center justify-center rounded-full text-xs font-medium ${
            message.sender_role === 'creator'
              ? 'bg-pink-500 text-white'
              : 'bg-green-500 text-white'
          }`}
        >
          {message.sender_avatar_url ? (
            <Image
              src={message.sender_avatar_url}
              alt={message.sender_display_name || message.sender_role}
              width={24}
              height={24}
              className='h-6 w-6 rounded-full object-cover'
            />
          ) : message.sender_role === 'creator' ? (
            'C'
          ) : (
            'F'
          )}
        </div>
      </button>

      <div className='min-w-0 flex-1'>
        <div className='mb-0.5 flex items-center gap-2'>
          <button
            onClick={onUserClick}
            className='cursor-pointer text-xs font-medium text-foreground-primary transition-colors hover:text-accent-brand'
          >
            {message.sender_display_name ||
              message.sender_handle ||
              (message.sender_role === 'creator' ? 'Creator' : 'Fulfiller')}
          </button>
          <span className='text-xs text-foreground-tertiary'>
            <span className='mr-1.5 ml-1'>•</span>
            {formatTimeAgo(message.created_at)}
          </span>
          {mediaTitle &&
            mediaColor &&
            // In media view: only show track button if message references different track
            // In chat view: always show track button (groupedMediaId is undefined)
            (!groupedMediaId ||
              (groupedMediaId && mediaId !== groupedMediaId)) && (
              <button
                onClick={() => {
                  // Check if media still exists
                  if (!mediaExists) {
                    setShowDeletedMediaDialog(true);
                    return;
                  }

                  // For link types, open URL in new window
                  if (mediaType === 'link' && mediaUrl) {
                    window.open(mediaUrl, '_blank', 'noopener,noreferrer');
                    return;
                  }

                  // For all other types, use existing behavior (filter/play)
                  if (onMediaClick) {
                    onMediaClick(mediaId);
                  }
                }}
                className={`rounded-full border border-border-primary bg-background-secondary px-2 py-1 text-xs font-medium text-foreground-secondary transition-all ${
                  mediaExists
                    ? 'cursor-pointer hover:scale-105 hover:bg-background-primary hover:shadow-sm'
                    : 'cursor-not-allowed opacity-50'
                }`}
                title={
                  mediaType === 'link'
                    ? 'Open link in new window'
                    : mediaExists
                      ? 'Click to play this track from the beginning'
                      : 'This track has been deleted'
                }
              >
                <span className='flex items-center gap-1'>
                  {mediaTitle}
                  {/* Show picture icon for image types */}
                  {mediaType === 'image' && (
                    <svg
                      className='h-3 w-3'
                      fill='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path d='M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z' />
                    </svg>
                  )}
                  {/* Show music note icon for audio types */}
                  {mediaType === 'audio' && (
                    <svg
                      className='h-3 w-3'
                      fill='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path d='M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z' />
                    </svg>
                  )}
                  {/* Show external link icon for link types */}
                  {mediaType === 'link' && (
                    <svg
                      className='h-3 w-3'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2}
                        d='M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14'
                      />
                    </svg>
                  )}
                  {/* Show submission status icon */}
                  {submissionStatus === 'accepted' && (
                    <svg
                      className='h-3 w-3'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                      style={{ color: '#4ade80' }}
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2.5}
                        d='M5 13l4 4L19 7'
                      />
                    </svg>
                  )}
                  {submissionStatus === 'rejected' && (
                    <svg
                      className='h-3 w-3'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                      style={{ color: '#f87171' }}
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2.5}
                        d='M6 18L18 6M6 6l12 12'
                      />
                    </svg>
                  )}
                  {submissionStatus === 'pending' && (
                    <svg
                      className='h-3 w-3 animate-pulse'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                      style={{ color: '#facc15' }}
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2.5}
                        d='M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'
                      />
                    </svg>
                  )}
                </span>
              </button>
            )}
          {message.time_range && (
            <div className='group/time-range relative inline-flex'>
              <button
                onClick={() => {
                  // Check if media still exists
                  if (!mediaExists) {
                    setShowDeletedMediaDialog(true);
                    return;
                  }

                  if (onTimeRangeClick && message.time_range) {
                    onTimeRangeClick(
                      {
                        start: message.time_range.start as number,
                        end: message.time_range.end as number,
                      },
                      mediaId
                    );
                  }
                }}
                className={`rounded-full px-2 py-1 text-xs font-medium transition-all ${
                  mediaExists
                    ? 'cursor-pointer hover:scale-105 hover:shadow-sm'
                    : 'cursor-not-allowed opacity-50'
                }`}
                style={(() => {
                  if (!mediaExists) {
                    // Gray out deleted media
                    return {
                      backgroundColor: '#71717a20',
                      color: '#71717a',
                      border: '1px solid #71717a40',
                    };
                  }

                  // Find the matching time range in uniqueTimeRanges to get the same color as the waveform
                  const matchingTimeRange = uniqueTimeRanges.find(
                    (tr) =>
                      Math.abs(
                        tr.start - (message.time_range!.start as number)
                      ) < 0.1 &&
                      Math.abs(tr.end - (message.time_range!.end as number)) <
                        0.1
                  );
                  const colorSet = matchingTimeRange
                    ? timeRangeColorSets[
                        uniqueTimeRanges.indexOf(matchingTimeRange) %
                          timeRangeColorSets.length
                      ]
                    : getTimeRangeColorSet(message.id);
                  return {
                    backgroundColor: colorSet.base + '20',
                    color: colorSet.base,
                    border: `1px solid ${colorSet.base + '40'}`,
                  };
                })()}
                title={
                  mediaExists
                    ? 'Click to play this time range'
                    : 'This track has been deleted'
                }
              >
                {(() => {
                  const start = message.time_range.start as number;
                  const end = message.time_range.end as number;
                  // If start and end are the same (or very close), show just one timestamp
                  if (Math.abs(start - end) < 0.01) {
                    return `${start.toFixed(1)}s`;
                  }
                  return `${start.toFixed(1)}s - ${end.toFixed(1)}s`;
                })()}
              </button>
              {/* Trash can icon - only show on hover and if user can edit */}
              {onRemoveTimeRange && (
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    onRemoveTimeRange(message.id);
                  }}
                  className='absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-white opacity-0 transition-opacity group-hover/time-range:opacity-100 hover:bg-red-600'
                  title='Remove time range'
                >
                  <svg
                    className='h-2.5 w-2.5'
                    fill='none'
                    stroke='currentColor'
                    viewBox='0 0 24 24'
                  >
                    <path
                      strokeLinecap='round'
                      strokeLinejoin='round'
                      strokeWidth={2.5}
                      d='M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16'
                    />
                  </svg>
                </button>
              )}
            </div>
          )}
        </div>
        {isEditing ? (
          <div className='mt-1 space-y-2'>
            <textarea
              value={editContent}
              onChange={(e) => setEditContent(e.target.value)}
              className='w-full resize-none rounded-lg border border-border-primary bg-background-primary px-2 py-1 text-sm text-foreground-primary focus:border-accent-brand focus:outline-none'
              rows={1}
              autoFocus
              aria-label='Edit message content'
              aria-invalid={!editContent.trim()}
              aria-describedby={!editContent.trim() ? 'edit-error' : undefined}
            />
            {!editContent.trim() && (
              <p id='edit-error' className='sr-only' role='alert'>
                Message content cannot be empty
              </p>
            )}
            <div className='flex gap-2'>
              <button
                onClick={() => {
                  if (onEdit && editContent.trim()) {
                    onEdit(message.id, editContent.trim());
                  }
                }}
                disabled={!editContent.trim()}
                className='rounded-md bg-accent-brand px-2 py-1 text-xs font-medium text-white transition-colors hover:bg-accent-brand/90 disabled:opacity-50'
              >
                Save
              </button>
              <button
                onClick={() => {
                  setEditContent(message.content);
                  if (onEdit) {
                    onEdit(message.id, null); // null signals cancel
                  }
                }}
                className='rounded-md border border-border-primary bg-background-secondary px-2 py-1 text-xs font-medium text-foreground-secondary transition-colors hover:bg-background-primary'
              >
                Cancel
              </button>
            </div>
          </div>
        ) : (
          <p className='text-sm leading-relaxed text-foreground-primary'>
            {message.content}
          </p>
        )}

        {/* Action buttons below message (Reply, Edit, Delete) */}
        <div className='mt-1 flex items-center gap-3 text-xs text-foreground-tertiary opacity-0 transition-opacity group-hover:opacity-100'>
          {onReply && (
            <button
              onClick={onReply}
              className='flex items-center gap-1 transition-colors hover:text-foreground-primary'
            >
              <svg
                className='h-3.5 w-3.5'
                fill='none'
                stroke='currentColor'
                viewBox='0 0 24 24'
              >
                <path
                  strokeLinecap='round'
                  strokeLinejoin='round'
                  strokeWidth={2}
                  d='M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z'
                />
              </svg>
              Reply
            </button>
          )}
          {!isEditing && onEdit && (
            <button
              onClick={() => onEdit(message.id, message.content)}
              className='flex items-center gap-1 transition-colors hover:text-foreground-primary'
            >
              <svg
                className='h-3.5 w-3.5'
                fill='none'
                stroke='currentColor'
                viewBox='0 0 24 24'
              >
                <path
                  strokeLinecap='round'
                  strokeLinejoin='round'
                  strokeWidth={2}
                  d='M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z'
                />
              </svg>
              Edit
            </button>
          )}
          {!isEditing && onDelete && (
            <button
              onClick={async () => {
                try {
                  await onDelete();
                } catch {
                  // Silently handle delete errors
                }
              }}
              className='flex items-center gap-1 transition-colors hover:text-foreground-primary'
            >
              <svg
                className='h-3.5 w-3.5'
                fill='none'
                stroke='currentColor'
                viewBox='0 0 24 24'
              >
                <path
                  strokeLinecap='round'
                  strokeLinejoin='round'
                  strokeWidth={2}
                  d='M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16'
                />
              </svg>
              Delete
            </button>
          )}
        </div>

        {/* Submission Review Buttons/Status */}
        {isSubmission && submissionStatus && (
          <div className='mt-2 flex items-center gap-2'>
            {/* Creator sees action buttons when pending, status badges otherwise */}
            {isCreator ? (
              <>
                {submissionStatus === 'pending' && (
                  <>
                    <button
                      onClick={onAcceptSubmission}
                      className='rounded-md border border-green-500/30 bg-green-500/10 px-2 py-1 text-xs font-medium text-green-400 transition-colors hover:bg-green-500/20'
                      title='Accept submission'
                    >
                      Accept
                    </button>
                    <button
                      onClick={onRejectSubmission}
                      className='rounded-md border border-border-primary bg-background-secondary/50 px-2 py-1 text-xs font-medium text-foreground-secondary transition-colors hover:bg-background-secondary'
                    >
                      Request Revision
                    </button>
                  </>
                )}
                {submissionStatus === 'accepted' && (
                  <div className='flex items-center gap-1.5 rounded-md border border-green-500/30 bg-green-500/10 px-2 py-1 text-xs font-medium text-green-400'>
                    <svg
                      className='h-3 w-3'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2}
                        d='M5 13l4 4L19 7'
                      />
                    </svg>
                    Accepted
                  </div>
                )}
                {/* Rejected status - No badge needed since X icon shows in track badge */}
              </>
            ) : (
              <>
                {/* Fulfiller sees status badges only */}
                {submissionStatus === 'pending' && (
                  <div className='flex items-center gap-1.5 rounded-md border border-yellow-500/30 bg-yellow-500/10 px-2 py-1 text-xs font-medium text-yellow-400'>
                    <svg
                      className='h-3 w-3 animate-pulse'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2}
                        d='M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'
                      />
                    </svg>
                    Pending Review
                  </div>
                )}
                {submissionStatus === 'accepted' && (
                  <div className='flex items-center gap-1.5 rounded-md border border-green-500/30 bg-green-500/10 px-2 py-1 text-xs font-medium text-green-400'>
                    <svg
                      className='h-3 w-3'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2}
                        d='M5 13l4 4L19 7'
                      />
                    </svg>
                    Accepted
                  </div>
                )}
                {/* Rejected status - No badge needed since X icon shows in track badge */}
              </>
            )}
          </div>
        )}
      </div>

      {/* Deleted Media Dialog */}
      <MarketplaceConfirmDialog
        isOpen={showDeletedMediaDialog}
        onClose={() => setShowDeletedMediaDialog(false)}
        onConfirm={() => setShowDeletedMediaDialog(false)}
        title='Track Deleted'
        message='This track has been deleted and is no longer available.'
        confirmText='Got it'
        variant='warning'
        alertMode={true}
        icon={
          <svg
            className='h-6 w-6'
            fill='none'
            stroke='currentColor'
            viewBox='0 0 24 24'
          >
            <path
              strokeLinecap='round'
              strokeLinejoin='round'
              strokeWidth={2}
              d='M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z'
            />
          </svg>
        }
      />
    </div>
  );
};

export default MarketplaceChatMessage;
