'use client';

import React from 'react';

import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { useModalContext } from '@/context/ModalContext';
import type { components } from '@/lib/gen';

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

interface MarketplaceMessageInputProps {
  value: string;
  onChange: (value: string) => void;
  onSend: () => void;
  onUpload?: () => void;
  onSearchClick?: () => void;
  showSearch?: boolean;
  placeholder?: string;
  disabled?: boolean;
  isSending?: boolean;
  // Upload modal props
  projectId: number;
  isCreator: boolean;
  mediaReferences: Array<{ reference_type: string }>;
  onUploadComplete?: () => void;
  // Optional ref callback for focusing
  inputRef?: (input: HTMLInputElement | null) => void;
  // Optional onFocus handler
  onFocus?: () => void;
  // Reply functionality
  replyingToMessage?: Message | null;
  onCancelReply?: () => void;
}

const MarketplaceMessageInput: React.FC<MarketplaceMessageInputProps> = ({
  value,
  onChange,
  onSend,
  onUpload,
  onSearchClick,
  showSearch = true,
  placeholder = 'Type a message...',
  disabled = false,
  isSending = false,
  projectId,
  isCreator,
  mediaReferences,
  onUploadComplete,
  inputRef,
  onFocus,
  replyingToMessage,
  onCancelReply,
}) => {
  const { openModalWithData } = useModalContext();

  const handleUploadClick = () => {
    if (onUpload) {
      onUpload();
      return;
    }

    // Default upload behavior
    const submissionCount = Array.isArray(mediaReferences)
      ? mediaReferences.filter((m) => m.reference_type === 'submission').length
      : 0;

    openModalWithData(ModalTypes.MARKETPLACE_UPLOAD_MEDIA, {
      projectId: String(projectId),
      mode: 'full' as const,
      title: isCreator ? 'Upload Reference' : 'Upload Submission',
      referenceType: isCreator
        ? ('reference' as const)
        : ('submission' as const),
      isCreator,
      existingSubmissionCount: submissionCount,
      // If replying to a message, pass parent task ID and current input as description
      initialParentTaskId: replyingToMessage?.id || null,
      initialDescription: value || undefined,
      onUploadComplete: () => {
        // Clear reply state after upload completes
        if (replyingToMessage && onCancelReply) {
          onCancelReply();
        }
        // Clear input value if replying
        if (replyingToMessage) {
          onChange('');
        }
        onUploadComplete?.();
      },
    });
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (value.trim() && !disabled && !isSending) {
        onSend();
      }
    }
  };

  return (
    <div className='flex gap-2'>
      {/* Search toggle button */}
      {showSearch && onSearchClick && (
        <button
          onClick={onSearchClick}
          className='rounded-lg border border-border-primary bg-background-secondary p-2 text-foreground-secondary transition-colors hover:bg-background-primary hover:text-foreground-primary'
          title='Search messages'
        >
          <svg
            className='h-4 w-4'
            fill='none'
            stroke='currentColor'
            viewBox='0 0 24 24'
          >
            <path
              strokeLinecap='round'
              strokeLinejoin='round'
              strokeWidth={2}
              d='M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z'
            />
          </svg>
        </button>
      )}
      <div className='relative flex-1'>
        <input
          ref={inputRef || undefined}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          className='w-full rounded-lg border border-border-primary bg-transparent px-4 py-2 text-sm text-foreground-primary placeholder-foreground-secondary focus:border-accent-brand focus:outline-none'
          onKeyDown={handleKeyDown}
          onFocus={onFocus}
          disabled={disabled || isSending}
        />
      </div>
      <button
        onClick={handleUploadClick}
        disabled={disabled || isSending}
        className='rounded-lg border border-border-primary bg-transparent p-2 text-foreground-secondary transition-colors hover:bg-background-secondary hover:text-foreground-primary disabled:cursor-not-allowed disabled:opacity-50'
        title='Upload media'
      >
        <svg
          className='h-5 w-5'
          fill='none'
          stroke='currentColor'
          viewBox='0 0 24 24'
        >
          <path
            strokeLinecap='round'
            strokeLinejoin='round'
            strokeWidth={2}
            d='M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12'
          />
        </svg>
      </button>
      <button
        onClick={onSend}
        disabled={!value.trim() || disabled || isSending}
        className='rounded-lg bg-accent-brand px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
      >
        {isSending ? (
          <svg className='h-4 w-4 animate-spin' fill='none' viewBox='0 0 24 24'>
            <circle
              className='opacity-25'
              cx='12'
              cy='12'
              r='10'
              stroke='currentColor'
              strokeWidth='4'
            />
            <path
              className='opacity-75'
              fill='currentColor'
              d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
            />
          </svg>
        ) : (
          'Send'
        )}
      </button>
    </div>
  );
};

export default MarketplaceMessageInput;
