'use client';

import React, { useState } from 'react';

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

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

type MediaReference = components['schemas']['MediaResponse'];
type Message = components['schemas']['MessageResponse'];
type MarketplaceProject = components['schemas']['ProjectResponse'];

interface MarketplaceMediaLibraryProps {
  mediaReferences: MediaReference[];
  messagesByMedia: Record<
    string,
    { media: MediaReference; messages: Message[] }
  >;
  activeMediaId: string | null;
  onMediaSelect: (mediaId: string) => void;
  filterByMediaId?: string | null;
  onClearFilter?: () => void;
  isWaveformCollapsed?: boolean;
  project?: MarketplaceProject | null;
  isCreator?: boolean;
  fetchMediaReferences?: () => void;
}

const MarketplaceMediaLibrary: React.FC<MarketplaceMediaLibraryProps> = ({
  mediaReferences,
  messagesByMedia,
  activeMediaId,
  onMediaSelect,
  filterByMediaId = null,
  onClearFilter,
  isWaveformCollapsed = false,
  project,
  isCreator = false,
  fetchMediaReferences,
}) => {
  const { openModalWithData } = useModalContext();
  const [showCreatorDialog, setShowCreatorDialog] = useState(false);
  const [showReferenceInfoDialog, setShowReferenceInfoDialog] = useState(false);
  const getMediaColor = (referenceType: string) => {
    return (
      mediaTypeColors[referenceType as keyof typeof mediaTypeColors] ||
      '#726e6c'
    );
  };

  if (mediaReferences.length === 0) {
    return null;
  }

  // Group media by type for better organization
  const groupedMedia = mediaReferences.reduce(
    (acc, media) => {
      const type = media.reference_type || 'other';
      if (!acc[type]) {
        acc[type] = [];
      }
      acc[type].push(media);
      return acc;
    },
    {} as Record<string, MediaReference[]>
  );

  return (
    <div
      className={`flex-shrink-0 ${isWaveformCollapsed ? 'mt-2 mb-2' : 'mt-3 mb-3'}`}
    >
      <div className='mb-3 flex items-center justify-between'>
        <h3 className='text-sm font-medium text-foreground-secondary'>
          Media Library
        </h3>
        {filterByMediaId && onClearFilter && (
          <button
            onClick={onClearFilter}
            className='flex items-center gap-1 rounded px-2 py-1 text-xs text-foreground-tertiary transition-colors hover:text-foreground-primary'
            title='Show all messages'
          >
            <svg
              className='h-3 w-3'
              fill='none'
              stroke='currentColor'
              viewBox='0 0 24 24'
            >
              <path
                strokeLinecap='round'
                strokeLinejoin='round'
                strokeWidth={2}
                d='M6 18L18 6M6 6l12 12'
              />
            </svg>
            Clear filter
          </button>
        )}
      </div>

      <div className='space-y-2'>
        {/* Source, References, and Submissions Side by Side */}
        {(groupedMedia['source']?.length > 0 ||
          groupedMedia['reference']?.length > 0 ||
          groupedMedia['submission']?.length > 0) && (
          <div className='grid grid-cols-1 gap-4'>
            {/* Source Column */}
            {groupedMedia['source']?.length > 0 && (
              <div className='space-y-1.5'>
                {/* Type Label */}
                <div className='flex items-center gap-1.5'>
                  <span
                    className='text-[10px] font-medium tracking-wider uppercase'
                    style={{ color: getMediaColor('source') }}
                  >
                    source
                  </span>
                  <div className='h-px flex-1 bg-border-primary' />
                </div>

                {/* Media Cards Grid */}
                <div className='flex flex-wrap gap-1.5'>
                  {groupedMedia['source'].map((media) => {
                    const allMediaMessages =
                      messagesByMedia[media.id]?.messages || [];
                    // Filter out orphaned child messages (children whose parent doesn't exist)
                    const allMessageIds = new Set(
                      allMediaMessages.map((m) => m.id)
                    );
                    const validMediaMessages = allMediaMessages.filter(
                      (msg) => {
                        const parentId = (msg as any).parent_message_id;
                        // Include root messages (no parent) or messages whose parent exists
                        return !parentId || allMessageIds.has(parentId);
                      }
                    );
                    const isActive = activeMediaId === media.id;
                    const isFiltered = filterByMediaId === media.id;
                    const mediaColor = getMediaColor(
                      media.reference_type || 'source'
                    );

                    return (
                      <div key={media.id} className='relative'>
                        <button
                          onClick={() => onMediaSelect(media.id)}
                          className={`h-12 w-12 rounded border transition-all ${
                            isActive || isFiltered
                              ? 'cursor-pointer hover:border-cyan-500 hover:bg-cyan-500/5'
                              : 'cursor-pointer hover:border-foreground-secondary/50'
                          }`}
                          style={{
                            borderColor: mediaColor + '60',
                            backgroundColor:
                              isActive || isFiltered
                                ? mediaColor + '10'
                                : 'transparent',
                          }}
                          title={media.title.replace('Edit: ', '')}
                        >
                          <div className='flex h-full items-center justify-center p-1'>
                            <svg
                              className='h-4 w-4'
                              style={{
                                color: mediaColor,
                              }}
                              fill={
                                media.media_type === 'link'
                                  ? 'none'
                                  : 'currentColor'
                              }
                              stroke={
                                media.media_type === 'link'
                                  ? 'currentColor'
                                  : 'none'
                              }
                              viewBox='0 0 24 24'
                            >
                              {media.media_type === 'audio' ? (
                                <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' />
                              ) : media.media_type === 'link' ? (
                                <path
                                  strokeLinecap='round'
                                  strokeLinejoin='round'
                                  strokeWidth={1.5}
                                  d='M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14'
                                />
                              ) : (
                                <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>
                          </div>
                        </button>
                        {/* Comment count badge */}
                        {validMediaMessages.length > 0 && (
                          <div
                            className='absolute -top-1 -right-1 flex h-5 w-5 items-center justify-center rounded-full text-[10px] font-medium text-white'
                            style={{ backgroundColor: mediaColor }}
                            title={`${validMediaMessages.length} comment${validMediaMessages.length > 1 ? 's' : ''}`}
                          >
                            {validMediaMessages.length}
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Reference Column */}
            <div className='space-y-1.5'>
              {/* Type Label */}
              <div className='flex items-center gap-1.5'>
                <span
                  className='text-[10px] font-medium tracking-wider uppercase'
                  style={{ color: getMediaColor('reference') }}
                >
                  reference
                </span>
                <div className='h-px flex-1 bg-border-primary' />
              </div>

              {/* Reference Cards and Placeholders */}
              <div className='flex flex-wrap gap-1.5'>
                {/* Existing references */}
                {groupedMedia['reference']?.map((media) => {
                  const allMediaMessages =
                    messagesByMedia[media.id]?.messages || [];
                  // Filter out orphaned child messages (children whose parent doesn't exist)
                  const allMessageIds = new Set(
                    allMediaMessages.map((m) => m.id)
                  );
                  const validMediaMessages = allMediaMessages.filter((msg) => {
                    const parentId = (msg as any).parent_message_id;
                    // Include root messages (no parent) or messages whose parent exists
                    return !parentId || allMessageIds.has(parentId);
                  });
                  const isActive = activeMediaId === media.id;
                  const isFiltered = filterByMediaId === media.id;
                  const mediaColor = getMediaColor(
                    media.reference_type || 'reference'
                  );

                  return (
                    <div key={media.id} className='relative'>
                      <button
                        onClick={() => onMediaSelect(media.id)}
                        className={`h-12 w-12 rounded border transition-all ${
                          isActive || isFiltered
                            ? 'cursor-pointer hover:border-cyan-500 hover:bg-cyan-500/5'
                            : 'cursor-pointer hover:border-foreground-secondary/50'
                        }`}
                        style={{
                          borderColor:
                            isActive || isFiltered
                              ? mediaColor + '60'
                              : 'var(--color-border-secondary)',
                          backgroundColor:
                            isActive || isFiltered
                              ? mediaColor + '10'
                              : 'transparent',
                        }}
                        title={media.title.replace('Edit: ', '')}
                      >
                        <div className='flex h-full items-center justify-center p-1'>
                          <svg
                            className='h-4 w-4'
                            style={{
                              color:
                                isActive || isFiltered
                                  ? mediaColor
                                  : 'var(--foreground-tertiary)',
                            }}
                            fill={
                              media.media_type === 'link'
                                ? 'none'
                                : 'currentColor'
                            }
                            stroke={
                              media.media_type === 'link'
                                ? 'currentColor'
                                : 'none'
                            }
                            viewBox='0 0 24 24'
                          >
                            {media.media_type === 'audio' ? (
                              <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' />
                            ) : media.media_type === 'link' ? (
                              <path
                                strokeLinecap='round'
                                strokeLinejoin='round'
                                strokeWidth={1.5}
                                d='M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14'
                              />
                            ) : (
                              <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>
                        </div>
                      </button>
                      {/* Comment count badge */}
                      {validMediaMessages.length > 0 && (
                        <div
                          className='absolute -top-1 -right-1 flex h-3.5 w-3.5 items-center justify-center rounded-full text-[8px] font-medium text-white'
                          style={{ backgroundColor: mediaColor }}
                          title={`${validMediaMessages.length} comment${validMediaMessages.length > 1 ? 's' : ''}`}
                        >
                          {validMediaMessages.length}
                        </div>
                      )}
                    </div>
                  );
                })}

                {/* Upload placeholder - show 1 placeholder button */}
                {(() => {
                  const allowsUpload =
                    project?.status !== 'COMPLETED' &&
                    project?.status !== 'CANCELLED';

                  const canUploadReference = isCreator || project?.is_fulfiller;

                  const handleClick = () => {
                    if (!project || !allowsUpload) return;

                    // If user is not creator or fulfiller, show info dialog
                    if (!canUploadReference) {
                      setShowReferenceInfoDialog(true);
                      return;
                    }

                    if (isCreator) {
                      // Creator uploads references
                      openModalWithData(ModalTypes.MARKETPLACE_UPLOAD_MEDIA, {
                        projectId: project.id,
                        mode: 'full' as const,
                        title: 'Upload Reference',
                        isCreator: true,
                        referenceType: 'reference' as const,
                        onUploadComplete: () => {
                          fetchMediaReferences?.();
                        },
                      });
                    } else {
                      // Fulfiller can also upload references
                      const submissionCount = mediaReferences.filter(
                        (m) => m.reference_type === 'submission'
                      ).length;

                      openModalWithData(ModalTypes.MARKETPLACE_UPLOAD_MEDIA, {
                        projectId: project.id,
                        mode: 'full' as const,
                        title: 'Upload Reference',
                        isCreator: false,
                        referenceType: 'reference' as const,
                        existingSubmissionCount: submissionCount,
                        onUploadComplete: () => {
                          fetchMediaReferences?.();
                        },
                      });
                    }
                  };

                  return (
                    <div key='upload-placeholder' className='relative'>
                      <button
                        onClick={allowsUpload ? handleClick : undefined}
                        onKeyDown={(e) => {
                          if (
                            allowsUpload &&
                            (e.key === 'Enter' || e.key === ' ')
                          ) {
                            e.preventDefault();
                            handleClick();
                          }
                        }}
                        disabled={!allowsUpload}
                        className={`flex h-12 w-12 items-center justify-center rounded-lg border bg-transparent p-2 text-foreground-tertiary transition-colors ${
                          allowsUpload
                            ? 'cursor-pointer hover:bg-background-secondary hover:text-foreground-secondary'
                            : 'cursor-not-allowed opacity-50'
                        }`}
                        style={{ borderColor: 'var(--color-border-secondary)' }}
                        title={
                          allowsUpload
                            ? canUploadReference
                              ? 'Click to upload reference'
                              : 'Only project creators and accepted applicants can upload references'
                            : 'Project is not in a state that allows uploads'
                        }
                      >
                        {canUploadReference ? (
                          <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='M12 4v16m8-8H4'
                            />
                          </svg>
                        ) : (
                          <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='M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'
                            />
                          </svg>
                        )}
                      </button>
                    </div>
                  );
                })()}
              </div>
            </div>

            {/* Submission Column */}
            {project?.fulfiller_id && (
              <div className='space-y-1.5'>
                {/* Type Label */}
                <div className='flex items-center gap-1.5'>
                  <span
                    className='text-[10px] font-medium tracking-wider uppercase'
                    style={{ color: getMediaColor('submission') }}
                  >
                    submission
                  </span>
                  <div className='h-px flex-1 bg-border-primary' />
                </div>

                {/* Submissions - Show actual submissions + 1 upload placeholder */}
                <div className='flex flex-wrap gap-1.5'>
                  {/* Show all existing submissions */}
                  {groupedMedia['submission']?.map((submission) => {
                    // Determine status
                    let status: 'pending' | 'accepted' | 'rejected' = 'pending';
                    if (submission.is_accepted === true) {
                      status = 'accepted';
                    } else if (
                      submission.is_accepted === null ||
                      submission.is_accepted === undefined ||
                      !('is_accepted' in submission)
                    ) {
                      status = 'pending';
                    } else {
                      status = 'rejected';
                    }

                    const isActive = activeMediaId === submission.id;
                    const isFiltered = filterByMediaId === submission.id;
                    const mediaColor = getMediaColor('submission');
                    const allMediaMessages =
                      messagesByMedia[submission.id]?.messages || [];
                    // Filter out orphaned child messages (children whose parent doesn't exist)
                    const allMessageIds = new Set(
                      allMediaMessages.map((m) => m.id)
                    );
                    const validMediaMessages = allMediaMessages.filter(
                      (msg) => {
                        const parentId = (msg as any).parent_message_id;
                        // Include root messages (no parent) or messages whose parent exists
                        return !parentId || allMessageIds.has(parentId);
                      }
                    );

                    return (
                      <div key={submission.id} className='relative'>
                        <button
                          onClick={() => onMediaSelect(submission.id)}
                          className={`h-12 w-12 rounded border transition-all ${
                            isActive || isFiltered
                              ? 'cursor-pointer hover:border-cyan-500 hover:bg-cyan-500/5'
                              : 'cursor-pointer hover:border-foreground-secondary/50'
                          }`}
                          style={{
                            borderColor: mediaColor + '60',
                            backgroundColor: mediaColor + '10',
                          }}
                          title={submission.title.replace('Edit: ', '')}
                        >
                          <div className='flex h-full items-center justify-center p-1'>
                            {status === 'accepted' && (
                              <svg
                                className='h-4 w-4 text-green-400'
                                fill='none'
                                stroke='currentColor'
                                viewBox='0 0 24 24'
                              >
                                <path
                                  strokeLinecap='round'
                                  strokeLinejoin='round'
                                  strokeWidth={3}
                                  d='M5 13l4 4L19 7'
                                />
                              </svg>
                            )}
                            {status === 'rejected' && (
                              <svg
                                className='h-4 w-4 text-accent-brand'
                                fill='none'
                                stroke='currentColor'
                                viewBox='0 0 24 24'
                              >
                                <path
                                  strokeLinecap='round'
                                  strokeLinejoin='round'
                                  strokeWidth={2}
                                  d='M6 18L18 6M6 6l12 12'
                                />
                              </svg>
                            )}
                            {status === 'pending' && (
                              <div className='h-3 w-3 animate-pulse rounded-full bg-cyan-500' />
                            )}
                          </div>
                        </button>
                        {/* Comment count badge */}
                        {validMediaMessages.length > 0 && (
                          <div
                            className='absolute -top-1 -right-1 flex h-5 w-5 items-center justify-center rounded-full text-[10px] font-medium text-white'
                            style={{ backgroundColor: mediaColor }}
                            title={`${validMediaMessages.length} comment${validMediaMessages.length > 1 ? 's' : ''}`}
                          >
                            {validMediaMessages.length}
                          </div>
                        )}
                      </div>
                    );
                  })}

                  {/* Upload placeholder - show 1 placeholder button */}
                  {(() => {
                    // Check if project is in a state that allows submissions
                    const allowsSubmissions =
                      project.status === 'IN_PROGRESS' ||
                      project.status === 'REVISION_REQUESTED' ||
                      project.status === 'PENDING_REVIEW';

                    const handleClick = () => {
                      if (!project) return;

                      // If creator, show info dialog
                      if (isCreator) {
                        setShowCreatorDialog(true);
                        return;
                      }

                      // If fulfiller and submissions allowed, open upload modal
                      if (!allowsSubmissions) return;

                      // Count existing submissions
                      const submissionCount = mediaReferences.filter(
                        (m) => m.reference_type === 'submission'
                      ).length;

                      // Open upload modal
                      openModalWithData(ModalTypes.MARKETPLACE_UPLOAD_MEDIA, {
                        projectId: project.id,
                        mode: 'full' as const,
                        title: 'Upload Submission',
                        referenceType: 'submission' as const,
                        isCreator: false,
                        existingSubmissionCount: submissionCount,
                        onUploadComplete: () => {
                          fetchMediaReferences?.();
                        },
                      });
                    };

                    return (
                      <div key='upload-placeholder' className='relative'>
                        <button
                          onClick={handleClick}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter' || e.key === ' ') {
                              e.preventDefault();
                              handleClick();
                            }
                          }}
                          className={`flex h-12 w-12 items-center justify-center rounded-lg border bg-transparent p-2 text-foreground-tertiary transition-colors ${
                            isCreator || allowsSubmissions
                              ? 'cursor-pointer hover:bg-background-secondary hover:text-foreground-secondary'
                              : 'cursor-not-allowed opacity-50'
                          }`}
                          style={{
                            borderColor: 'var(--color-border-secondary)',
                          }}
                          title={
                            isCreator
                              ? 'Click to learn more'
                              : !allowsSubmissions
                                ? 'Project is not in a state that allows submissions'
                                : 'Click to upload submission'
                          }
                        >
                          {!isCreator && (
                            <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='M12 4v16m8-8H4'
                              />
                            </svg>
                          )}
                        </button>
                      </div>
                    );
                  })()}
                </div>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Creator info dialog */}
      <MarketplaceConfirmDialog
        isOpen={showCreatorDialog}
        onClose={() => setShowCreatorDialog(false)}
        title='Submissions'
        message='The fulfiller will upload their submissions here. You can review and accept or reject them once they are submitted.'
        confirmText='Got it'
        variant='primary'
        alertMode={true}
      />

      {/* Reference upload info dialog */}
      <MarketplaceConfirmDialog
        isOpen={showReferenceInfoDialog}
        onClose={() => setShowReferenceInfoDialog(false)}
        onConfirm={() => setShowReferenceInfoDialog(false)}
        title='Upload References'
        message='Only project creators and accepted applicants will be able to upload new references.'
        confirmText='Got it'
        variant='primary'
        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='M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'
            />
          </svg>
        }
      />
    </div>
  );
};

export default MarketplaceMediaLibrary;
