import React, { useEffect, useRef, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { toast } from '@/components/toast/Toast';
import { useModalContext } from '@/context/ModalContext';
import type { components } from '@/lib/gen';

import MarketplaceConfirmDialog from '../shared/MarketplaceConfirmDialog';

// Use generated API types
type Message = components['schemas']['MessageResponse'];

interface MarketplaceUploadMediaModalProps {
  projectId?: string;
  onUploadComplete?: (
    mediaReferences: Array<{
      id: string;
      type: 'audio' | 'image';
      url: string;
      name: string;
    }>
  ) => void;
  mode?: 'full' | 'audio-only';
  title?: string;
  referenceType?: 'submission' | 'reference';
  isCreator?: boolean;
  existingSubmissionCount?: number;
  initialParentTaskId?: string | null;
  initialDescription?: string;
}

type MediaType = 'audio' | 'image';
type ReferenceType = 'submission' | 'reference';

type MediaResponse = components['schemas']['MediaResponse'];

interface MediaReference {
  id: string;
  type: MediaType;
  url: string;
  name: string;
}

const MarketplaceUploadMediaModal: React.FC<
  MarketplaceUploadMediaModalProps
> = ({
  projectId,
  onUploadComplete,
  mode = 'full',
  title: modalTitle = 'Upload Media',
  referenceType: initialReferenceType,
  isCreator,
  existingSubmissionCount,
  initialParentTaskId,
  initialDescription,
}) => {
  const { closeModal, getModalData } = useModalContext();
  const { apiClient } = useStores();

  // Get modal data from context
  const modalData = getModalData(ModalTypes.MARKETPLACE_UPLOAD_MEDIA);
  const actualMode = modalData?.mode || mode;
  const actualTitle = modalData?.title || modalTitle;
  const actualOnUploadComplete =
    modalData?.onUploadComplete || onUploadComplete;
  const actualProjectId = modalData?.projectId || projectId;
  const actualIsCreator = modalData?.isCreator ?? isCreator ?? true;
  const actualSubmissionCount =
    modalData?.existingSubmissionCount ?? existingSubmissionCount ?? 0;
  const actualInitialParentTaskId =
    modalData?.initialParentTaskId ?? initialParentTaskId;
  const actualInitialDescription =
    modalData?.initialDescription ?? initialDescription;

  // Determine default reference type: fulfillers default to 'submission', creators default to 'reference'
  // Creators cannot upload submissions, so force 'reference' for creators
  const defaultReferenceType = actualIsCreator ? 'reference' : 'submission';
  let actualReferenceType =
    modalData?.referenceType || initialReferenceType || defaultReferenceType;
  // Force 'reference' if creator tries to use 'submission'
  if (actualIsCreator && actualReferenceType === 'submission') {
    actualReferenceType = 'reference';
  }

  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const [referenceType, setReferenceType] =
    useState<ReferenceType>(actualReferenceType);

  // Upload mode: 'file' for file uploads, 'link' for URL links (only for references)
  const [uploadMode, setUploadMode] = useState<'file' | 'link'>('file');
  const [linkUrl, setLinkUrl] = useState<string>('');

  // Auto-generate title only for submissions
  const getDefaultTitle = () => {
    if (referenceType === 'submission') {
      return `Submission ${actualSubmissionCount + 1}`;
    }
    // References require user to provide a title
    return '';
  };

  const defaultTitle = getDefaultTitle();

  const [title, setTitle] = useState(defaultTitle);
  const [description, setDescription] = useState(
    actualInitialDescription || ''
  );
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Task selection for submissions
  const [projectTasks, setProjectTasks] = useState<
    Array<{
      id: string;
      content: string;
      time_range?: { start: number; end: number };
    }>
  >([]);
  const [selectedParentTaskId, setSelectedParentTaskId] = useState<
    string | null
  >(actualInitialParentTaskId || null);
  const [isLoadingTasks, setIsLoadingTasks] = useState(false);

  // Preview time ranges for submissions
  const [previewTimeRanges, setPreviewTimeRanges] = useState<
    Array<{ start: number; end: number; label?: string }>
  >([]);
  const [audioPreviewUrl, setAudioPreviewUrl] = useState<string | null>(null);
  const [audioDuration, setAudioDuration] = useState<number>(0);
  const [startTimeInput, setStartTimeInput] = useState<string>('');
  const [endTimeInput, setEndTimeInput] = useState<string>('');
  const [showTimeRangeWarning, setShowTimeRangeWarning] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const audioRef = useRef<HTMLAudioElement>(null);

  const isAudioOnly = actualMode === 'audio-only';

  // Clean up audio preview URL when component unmounts or file changes
  useEffect(() => {
    return () => {
      if (audioPreviewUrl) {
        URL.revokeObjectURL(audioPreviewUrl);
      }
    };
  }, [audioPreviewUrl]);

  // Update title when reference type changes and reset upload mode
  // Also ensure creators can't switch to submission type
  React.useEffect(() => {
    // Force reference type for creators
    if (actualIsCreator && referenceType === 'submission') {
      setReferenceType('reference');
      return;
    }

    // Only auto-update title for submissions if it's empty or matches default patterns
    // References require user to provide a title
    setTitle((currentTitle) => {
      if (referenceType === 'submission') {
        if (
          !currentTitle ||
          currentTitle === 'Submission' ||
          currentTitle.match(/^(Submission|Reference) \d+$/)
        ) {
          return `Submission ${actualSubmissionCount + 1}`;
        }
      } else if (referenceType === 'reference') {
        // Clear title if switching from submission to reference
        if (
          currentTitle.match(/^(Submission|Reference) \d+$/) ||
          currentTitle === 'Submission'
        ) {
          return '';
        }
      }
      // Return current title if it doesn't match default patterns
      return currentTitle;
    });

    if (referenceType === 'submission') {
      // Submissions always use file mode
      setUploadMode('file');
      setLinkUrl('');
    }
  }, [referenceType, actualSubmissionCount, actualIsCreator]);

  // Fetch project tasks (creator messages) when uploading submissions
  useEffect(() => {
    if (referenceType === 'submission' && actualProjectId && !actualIsCreator) {
      setIsLoadingTasks(true);
      const fetchTasks = async () => {
        try {
          const response = await apiClient.GET(
            '/api/marketplace/projects/{project_id}/messages/',
            {
              params: { path: { project_id: actualProjectId } },
            }
          );

          if (response.data) {
            // Filter to only creator messages (tasks) that don't have a parent
            const tasks = (response.data as Message[])
              .filter(
                (msg: Message) =>
                  msg.sender_role === 'creator' && !msg.parent_message_id
              )
              .map((msg: Message) => {
                // Convert time_range to the expected format, handling null/undefined
                let timeRange: { start: number; end: number } | undefined;
                if (
                  msg.time_range &&
                  typeof msg.time_range === 'object' &&
                  'start' in msg.time_range &&
                  'end' in msg.time_range &&
                  typeof msg.time_range.start === 'number' &&
                  typeof msg.time_range.end === 'number'
                ) {
                  timeRange = {
                    start: msg.time_range.start,
                    end: msg.time_range.end,
                  };
                }
                return {
                  id: msg.id,
                  content: msg.content,
                  time_range: timeRange,
                };
              });
            setProjectTasks(tasks);
          }
        } catch (err) {
          console.error('Failed to fetch project tasks:', err);
          setProjectTasks([]);
        } finally {
          setIsLoadingTasks(false);
        }
      };

      fetchTasks();
    } else {
      setProjectTasks([]);
      setSelectedParentTaskId(actualInitialParentTaskId || null);
    }
  }, [
    referenceType,
    actualProjectId,
    actualIsCreator,
    apiClient,
    actualInitialParentTaskId,
  ]);

  // Update selectedParentTaskId when tasks are loaded and initialParentTaskId is provided
  // Always set it if provided, even if it's not in the dropdown (e.g., replying to a non-creator message)
  useEffect(() => {
    if (actualInitialParentTaskId) {
      setSelectedParentTaskId(actualInitialParentTaskId);
    }
  }, [projectTasks, actualInitialParentTaskId]);

  const onClose = () => {
    closeModal(ModalTypes.MARKETPLACE_UPLOAD_MEDIA);
  };

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files) return;

    let filesArray = Array.from(files);

    // Filter out video files (including MP4 videos)
    filesArray = filesArray.filter((file) => {
      // Reject video files
      if (file.type.startsWith('video/')) {
        return false;
      }
      // Reject MP4 files that are videos (M4A audio files have type 'audio/mp4' or 'audio/m4a')
      if (
        file.type === 'video/mp4' ||
        file.name.toLowerCase().endsWith('.mp4')
      ) {
        // Allow audio MP4 files (M4A) but reject video MP4 files
        // M4A files typically have type 'audio/mp4' or 'audio/m4a', not 'video/mp4'
        if (file.type.startsWith('audio/')) {
          return true; // It's an audio MP4 (M4A), allow it
        }
        return false; // It's a video MP4, reject it
      }
      return true;
    });

    // In audio-only mode, filter to only audio files
    if (isAudioOnly) {
      filesArray = filesArray.filter((file) => file.type.startsWith('audio/'));
    }

    // Show error if any video files were filtered out
    const rejectedFiles = Array.from(files).filter((file) => {
      if (file.type.startsWith('video/')) return true;
      if (
        file.type === 'video/mp4' ||
        (file.name.toLowerCase().endsWith('.mp4') &&
          !file.type.startsWith('audio/'))
      ) {
        return true;
      }
      return false;
    });

    if (rejectedFiles.length > 0) {
      setUploadError(
        'Video files are not supported. Please upload audio or image files only.'
      );
    }

    setSelectedFiles(filesArray);

    // Create preview URL for audio file if it's a submission
    if (
      referenceType === 'submission' &&
      filesArray.length > 0 &&
      filesArray[0].type.startsWith('audio/')
    ) {
      // Clean up previous URL if it exists
      if (audioPreviewUrl) {
        URL.revokeObjectURL(audioPreviewUrl);
      }
      const previewUrl = URL.createObjectURL(filesArray[0]);
      setAudioPreviewUrl(previewUrl);
      setPreviewTimeRanges([]); // Reset time ranges when new file is selected
      setStartTimeInput(''); // Reset input fields
      setEndTimeInput('');
    } else {
      setAudioPreviewUrl(null);
      setPreviewTimeRanges([]);
      setStartTimeInput('');
      setEndTimeInput('');
    }
  };

  const removeFile = (index: number) => {
    setSelectedFiles((prev) => prev.filter((_, i) => i !== index));
  };

  // Extract upload logic so it can be called from both handleUpload and warning dialog
  const performUpload = async (
    timeRangesToUse: Array<{ start: number; end: number; label?: string }>
  ) => {
    setIsUploading(true);

    try {
      let uploadPromises: Promise<MediaReference>[] = [];

      // Helper to convert MediaResponse to MediaReference
      const convertToMediaReference = (
        response: MediaResponse | undefined
      ): MediaReference => {
        if (!response) {
          return {
            id: '',
            type: 'audio',
            url: '',
            name: '',
          };
        }
        return {
          id: response.id,
          type: (response.media_type as MediaType) || 'audio',
          url: response.url,
          name: response.title,
        };
      };

      // Handle file uploads or link uploads
      if (uploadMode === 'link' && linkUrl.trim()) {
        // Handle link upload (only for references)
        if (!actualProjectId) {
          throw new Error('Link uploads require a project ID');
        }

        const response = await apiClient.POST(
          '/api/marketplace/projects/{project_id}/media/',
          {
            params: { path: { project_id: actualProjectId } },
            body: {
              media_type: 'link',
              reference_type: referenceType,
              title: title || linkUrl,
              url: linkUrl.trim(),
              description: description || `Link reference`,
            },
          }
        );

        if (response.error) {
          throw new Error(`Failed to upload link reference`);
        }

        if (!response.response || response.response.status >= 400) {
          throw new Error(`Failed to upload link reference`);
        }

        uploadPromises.push(
          Promise.resolve(convertToMediaReference(response.data))
        );
      } else if (selectedFiles.length > 0) {
        // Handle file uploads
        const filePromises = selectedFiles.map(async (file) => {
          const mediaType: MediaType = file.type.startsWith('audio/')
            ? 'audio'
            : 'image';

          // Convert file to base64 for upload
          const fileBase64 = await new Promise<string>((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => {
              const result = reader.result as string;
              resolve(result);
            };
            reader.onerror = reject;
            reader.readAsDataURL(file);
          });

          // If no projectId (audio-only mode), just return the media reference
          if (!actualProjectId) {
            return {
              id: `temp_${Date.now()}_${Math.random()}`,
              type: mediaType,
              url: URL.createObjectURL(file),
              name: file.name,
            };
          }

          // Use the appropriate API endpoint based on reference type
          if (referenceType === 'submission') {
            const response = await apiClient.POST(
              '/api/marketplace/projects/{project_id}/submissions/',
              {
                params: { path: { project_id: actualProjectId } },
                body: {
                  media_type: mediaType,
                  reference_type: referenceType,
                  title: title || file.name,
                  file: fileBase64, // Send base64 file data
                  description: description || `Uploaded ${mediaType} file`,
                },
              }
            );

            if (response.error) {
              throw new Error(`Failed to upload submission ${file.name}`);
            }

            if (!response.response || response.response.status >= 400) {
              throw new Error(`Failed to upload submission ${file.name}`);
            }

            return convertToMediaReference(response.data);
          } else {
            const response = await apiClient.POST(
              '/api/marketplace/projects/{project_id}/media/',
              {
                params: { path: { project_id: actualProjectId } },
                body: {
                  media_type: mediaType,
                  reference_type: referenceType,
                  title: title || file.name,
                  file: fileBase64, // Send base64 file data
                  description: description || `Uploaded ${mediaType} file`,
                },
              }
            );

            if (response.error) {
              throw new Error(`Failed to upload reference ${file.name}`);
            }

            if (!response.response || response.response.status >= 400) {
              throw new Error(`Failed to upload reference ${file.name}`);
            }

            return convertToMediaReference(response.data);
          }
        });

        uploadPromises.push(...filePromises);
      }

      const uploadedMedia = await Promise.all(uploadPromises);

      // Create messages with the uploaded media references (only if projectId exists)
      if (actualProjectId && uploadedMedia.length > 0) {
        const mediaId = uploadedMedia[0].id;

        // If it's a submission with preview time ranges, create a message for each time range
        if (referenceType === 'submission' && timeRangesToUse.length > 0) {
          const trimmedDescription = description?.trim() || '';
          const hasComment = trimmedDescription.length > 0;

          const messagePromises = timeRangesToUse.map(async (timeRange) => {
            // Use user's comment/description if provided, otherwise use time range label or preview text
            let messageContent: string;
            if (hasComment) {
              messageContent = trimmedDescription;
            } else if (timeRange.label) {
              messageContent = timeRange.label;
            } else {
              messageContent = `Preview: ${timeRange.start.toFixed(1)}s - ${timeRange.end.toFixed(1)}s`;
            }

            const messageBody: any = {
              content: messageContent,
              media_reference_id: mediaId,
              time_range: {
                start: timeRange.start,
                end: timeRange.end,
              },
            };

            // Add parent_message_id if provided (for replies)
            if (selectedParentTaskId) {
              messageBody.parent_message_id = selectedParentTaskId;
            }

            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            const messageResponse = await (apiClient.POST as any)(
              `/api/marketplace/projects/${actualProjectId}/messages/`,
              {
                body: messageBody,
              }
            );

            if (messageResponse.error) {
              console.error(
                'Failed to create time range message:',
                messageResponse.error
              );
            }
            return messageResponse;
          });

          // Wait for all messages to be created
          await Promise.all(messagePromises);
        } else {
          // Create a regular message without time range
          // Use comment/description if provided, otherwise use default message
          const trimmedDescription = description?.trim() || '';
          const hasComment = trimmedDescription.length > 0;

          const messageContent = hasComment
            ? trimmedDescription
            : referenceType === 'submission'
              ? `Uploaded submission for review`
              : `Added ${uploadedMedia.length} reference${uploadedMedia.length > 1 ? 's' : ''}`;

          const messageBody: any = {
            content: messageContent,
            media_reference_id: mediaId,
          };

          // Add parent_message_id if provided (for replies to messages)
          if (selectedParentTaskId) {
            messageBody.parent_message_id = selectedParentTaskId;
          }

          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const messageResponse = await (apiClient.POST as any)(
            `/api/marketplace/projects/${actualProjectId}/messages/`,
            {
              body: messageBody,
            }
          );

          if (messageResponse.error) {
            console.error('Failed to create message:', messageResponse.error);
          }
        }
      }

      // Close modal first to show loading state
      onClose();

      // Wait a bit longer for backend to process, then trigger refresh
      setTimeout(() => {
        actualOnUploadComplete?.(uploadedMedia);
      }, 1000);
    } catch (error) {
      console.error('Upload failed:', error);
      const errorMessage =
        error instanceof Error ? error.message : 'Unknown error';
      setUploadError(errorMessage);
    } finally {
      setIsUploading(false);
    }
  };

  const handleUpload = async () => {
    // Prevent creators from uploading submissions
    if (actualIsCreator && referenceType === 'submission') {
      toast({
        title: 'Invalid action',
        description: 'Creators cannot upload submissions',
        status: 'error',
        duration: 4000,
        isClosable: true,
      });
      return;
    }

    // Validate input - need files or link URL
    if (uploadMode === 'file' && selectedFiles.length === 0) {
      toast({
        title: 'No files selected',
        description: 'Please select files to upload',
        status: 'warning',
        duration: 4000,
        isClosable: true,
      });
      return;
    }

    if (uploadMode === 'link' && !linkUrl.trim()) {
      toast({
        title: 'Link URL required',
        description: 'Please enter a link URL',
        status: 'warning',
        duration: 4000,
        isClosable: true,
      });
      return;
    }

    if (!title.trim()) {
      toast({
        title: 'Title required',
        description: 'Please enter a title',
        status: 'warning',
        duration: 4000,
        isClosable: true,
      });
      return;
    }

    // Determine the time ranges to use for this upload
    let timeRangesToUse = previewTimeRanges;

    // Check for submissions with audio files - they need time ranges
    const isAudioFile = selectedFiles.some((file) =>
      file.type.startsWith('audio/')
    );

    if (referenceType === 'submission' && audioPreviewUrl && isAudioFile) {
      // Auto-add time range if fields have values but user didn't click Add
      if ((startTimeInput || endTimeInput) && previewTimeRanges.length === 0) {
        const start = parseFloat(startTimeInput) || 0;
        const end = parseFloat(endTimeInput) || audioDuration;

        if (start < end && end <= audioDuration) {
          // Use the auto-added time range directly
          timeRangesToUse = [{ start, end }];
          // Also update state for UI consistency
          setPreviewTimeRanges(timeRangesToUse);
          setStartTimeInput('');
          setEndTimeInput('');
        }
      }

      // Warn if no time ranges added for audio submissions
      if (timeRangesToUse.length === 0) {
        setShowTimeRangeWarning(true);
        return;
      }
    }

    // Proceed with upload
    await performUpload(timeRangesToUse);
  };

  return (
    <div className='fixed inset-0 z-[60] flex items-center justify-center'>
      {/* Backdrop */}
      <div
        className='absolute inset-0 bg-black/50 backdrop-blur-sm'
        onClick={onClose}
        onKeyDown={(e) => e.key === 'Escape' && onClose()}
        role='button'
        tabIndex={0}
        aria-label='Close modal'
      />

      {/* Modal */}
      <div className='relative mx-4 max-h-[90vh] w-full max-w-2xl overflow-y-auto rounded-2xl bg-background-primary p-8'>
        {/* Header */}
        <div className='mb-6 flex items-center justify-between'>
          <h2 className='text-2xl font-bold text-foreground-primary'>
            {actualTitle}
          </h2>
          <button
            onClick={onClose}
            className='text-foreground-secondary transition-colors hover:text-foreground-primary'
          >
            <svg
              className='h-6 w-6'
              fill='none'
              stroke='currentColor'
              viewBox='0 0 24 24'
            >
              <path
                strokeLinecap='round'
                strokeLinejoin='round'
                strokeWidth={2}
                d='M6 18L18 6M6 6l12 12'
              />
            </svg>
          </button>
        </div>

        {/* Content */}
        <div className='space-y-6'>
          {/* Reference Type Selection - Only show in full mode */}
          {!isAudioOnly && (
            <div>
              <label
                htmlFor='upload-type'
                className='mb-3 block text-sm font-medium text-foreground-primary'
              >
                Upload Type
              </label>
              <div
                className={`grid gap-4 ${actualIsCreator ? 'grid-cols-1' : 'grid-cols-2'}`}
              >
                <button
                  onClick={() => setReferenceType('reference')}
                  className={`rounded-lg border p-4 text-left transition-all ${
                    referenceType === 'reference'
                      ? 'border-accent-brand bg-accent-brand/10 text-accent-brand'
                      : 'border-border-primary bg-background-secondary text-foreground-secondary hover:border-accent-brand/50'
                  }`}
                >
                  <div className='flex items-center gap-3'>
                    <div className='flex h-8 w-8 items-center justify-center rounded-lg bg-foreground-tertiary/20'>
                      <svg
                        className='h-4 w-4'
                        fill='currentColor'
                        viewBox='0 0 24 24'
                      >
                        <path d='M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z' />
                      </svg>
                    </div>
                    <div>
                      <div className='font-medium'>Reference</div>
                      <div className='text-xs opacity-75'>
                        Share inspiration or examples
                      </div>
                    </div>
                  </div>
                </button>

                {/* Only show submission option for non-creators */}
                {!actualIsCreator && (
                  <button
                    onClick={() => setReferenceType('submission')}
                    className={`rounded-lg border p-4 text-left transition-all ${
                      referenceType === 'submission'
                        ? 'border-accent-brand bg-accent-brand/10 text-accent-brand'
                        : 'border-border-primary bg-background-secondary text-foreground-secondary hover:border-accent-brand/50'
                    }`}
                  >
                    <div className='flex items-center gap-3'>
                      <div className='flex h-8 w-8 items-center justify-center rounded-lg bg-foreground-tertiary/20'>
                        <svg
                          className='h-4 w-4'
                          fill='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path d='M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z' />
                        </svg>
                      </div>
                      <div>
                        <div className='font-medium'>Submission</div>
                        <div className='text-xs opacity-75'>
                          Upload your completed work
                        </div>
                      </div>
                    </div>
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Upload Mode Selection - Only show for references */}
          {referenceType === 'reference' && (
            <div>
              <div className='border-b border-border-primary'>
                <div className='flex gap-1'>
                  <button
                    onClick={() => {
                      setUploadMode('file');
                      setLinkUrl('');
                    }}
                    className={`flex items-center gap-2 px-4 py-2 text-sm font-medium transition-colors ${
                      uploadMode === 'file'
                        ? 'border-b-2 border-accent-brand text-accent-brand'
                        : 'text-foreground-secondary hover:text-foreground-primary'
                    }`}
                  >
                    <svg
                      className='h-4 w-4'
                      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>
                    Upload File
                  </button>

                  <button
                    onClick={() => {
                      setUploadMode('link');
                      setSelectedFiles([]);
                    }}
                    className={`flex items-center gap-2 px-4 py-2 text-sm font-medium transition-colors ${
                      uploadMode === 'link'
                        ? 'border-b-2 border-accent-brand text-accent-brand'
                        : 'text-foreground-secondary hover:text-foreground-primary'
                    }`}
                  >
                    <svg
                      className='h-4 w-4'
                      fill='none'
                      stroke='currentColor'
                      viewBox='0 0 24 24'
                    >
                      <path
                        strokeLinecap='round'
                        strokeLinejoin='round'
                        strokeWidth={2}
                        d='M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1'
                      />
                    </svg>
                    Add Link
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* File Upload Area - Show when in file mode or for submissions */}
          {uploadMode === 'file' && (
            <div>
              <label
                htmlFor='file-upload'
                className='mb-3 block text-sm font-medium text-foreground-primary'
              >
                Files
              </label>
              <div
                className='rounded-lg border-2 border-dashed border-border-primary p-8 text-center transition-colors hover:border-accent-brand/50'
                onClick={() => fileInputRef.current?.click()}
                onKeyDown={(e) =>
                  e.key === 'Enter' && fileInputRef.current?.click()
                }
                role='button'
                tabIndex={0}
                aria-label='Upload files'
              >
                <input
                  ref={fileInputRef}
                  type='file'
                  multiple
                  accept={isAudioOnly ? 'audio/*' : 'audio/*,image/*'}
                  onChange={handleFileSelect}
                  className='hidden'
                />
                <svg
                  className='mx-auto h-12 w-12 text-foreground-tertiary'
                  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>
                <p className='mt-2 text-sm text-foreground-secondary'>
                  Click to upload files or drag and drop
                </p>
                <p className='text-xs text-foreground-tertiary'>
                  {isAudioOnly
                    ? 'Audio files only'
                    : 'Audio and image files supported'}
                </p>
              </div>

              {/* Selected Files */}
              {selectedFiles.length > 0 && (
                <div className='mt-4 space-y-2'>
                  {selectedFiles.map((file, index) => (
                    <div
                      key={index}
                      className='flex items-center justify-between rounded-lg bg-background-secondary p-3'
                    >
                      <div className='flex items-center gap-3'>
                        <div className='flex h-8 w-8 items-center justify-center rounded-lg bg-accent-brand/10'>
                          {file.type.startsWith('audio/') ? (
                            <svg
                              className='h-4 w-4 text-accent-brand'
                              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>
                          ) : (
                            <svg
                              className='h-4 w-4 text-accent-brand'
                              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>
                          )}
                        </div>
                        <div>
                          <div className='text-sm font-medium text-foreground-primary'>
                            {file.name}
                          </div>
                          <div className='text-xs text-foreground-secondary'>
                            {(file.size / 1024 / 1024).toFixed(2)} MB
                          </div>
                        </div>
                      </div>
                      <button
                        onClick={() => removeFile(index)}
                        className='text-foreground-tertiary transition-colors hover:text-red-500'
                      >
                        <svg
                          className='h-4 w-4'
                          fill='none'
                          stroke='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path
                            strokeLinecap='round'
                            strokeLinejoin='round'
                            strokeWidth={2}
                            d='M6 18L18 6M6 6l12 12'
                          />
                        </svg>
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Link URL Input - Show when in link mode */}
          {uploadMode === 'link' && (
            <div>
              <label
                htmlFor='link-url'
                className='mb-3 block text-sm font-medium text-foreground-primary'
              >
                Link URL
              </label>
              <input
                id='link-url'
                type='url'
                value={linkUrl}
                onChange={(e) => setLinkUrl(e.target.value)}
                placeholder='https://example.com'
                className='w-full rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-foreground-primary placeholder-foreground-secondary focus:border-accent-brand focus:outline-none'
              />
            </div>
          )}

          {/* Task Selection for Submissions */}
          {referenceType === 'submission' && !actualIsCreator && (
            <div>
              <label
                htmlFor='task-select'
                className='mb-2 block text-sm font-medium text-foreground-primary'
              >
                Reply to Task (Optional)
              </label>
              {isLoadingTasks ? (
                <div className='rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-sm text-foreground-secondary'>
                  Loading tasks...
                </div>
              ) : projectTasks.length === 0 ? (
                <div className='rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-sm text-foreground-secondary'>
                  No tasks available
                </div>
              ) : (
                <select
                  id='task-select'
                  value={selectedParentTaskId || ''}
                  onChange={(e) => {
                    const newValue = e.target.value || null;
                    setSelectedParentTaskId(newValue);
                  }}
                  className='w-full rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-foreground-primary focus:border-accent-brand focus:outline-none'
                >
                  <option value=''>None (General submission)</option>
                  {projectTasks.map((task) => (
                    <option key={task.id} value={task.id}>
                      {task.content.length > 60
                        ? `${task.content.substring(0, 60)}...`
                        : task.content}
                      {task.time_range
                        ? ` (${task.time_range.start.toFixed(1)}s - ${task.time_range.end.toFixed(1)}s)`
                        : ''}
                    </option>
                  ))}
                </select>
              )}
            </div>
          )}

          {/* Title Input */}
          <div>
            <label
              htmlFor='title-input'
              className='mb-2 block text-sm font-medium text-foreground-primary'
            >
              Title <span className='text-red-500'>*</span>
            </label>
            <input
              id='title-input'
              type='text'
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder='Enter a title for your upload...'
              required
              className='w-full rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-foreground-primary placeholder-foreground-secondary focus:border-accent-brand focus:outline-none'
            />
          </div>

          {/* Comment Input */}
          <div>
            <label
              htmlFor='description-input'
              className='mb-2 block text-sm font-medium text-foreground-primary'
            >
              Comment
            </label>
            <textarea
              id='description-input'
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder='Add a comment...'
              rows={3}
              className='w-full rounded-lg border border-border-primary bg-background-secondary px-3 py-2 text-foreground-primary placeholder-foreground-secondary focus:border-accent-brand focus:outline-none'
            />
          </div>

          {/* Preview Time Ranges - Only show for submissions with audio */}
          {audioPreviewUrl && referenceType === 'submission' && (
            <div className='rounded-lg border border-border-primary bg-background-secondary p-4'>
              <h3 className='mb-3 block text-sm font-medium text-foreground-primary'>
                Preview Time Ranges (Optional)
              </h3>
              <p className='mb-4 text-xs text-foreground-secondary'>
                Add time ranges that the creator can preview before accepting
                your submission
              </p>

              {/* Hidden audio element for getting duration */}
              <audio
                ref={audioRef}
                src={audioPreviewUrl}
                onLoadedMetadata={(e) => {
                  const audio = e.target as HTMLAudioElement;
                  setAudioDuration(audio.duration);
                }}
                className='hidden'
              />

              {/* Time Range Input */}
              <div className='mb-3 flex items-end gap-2'>
                <div className='flex-1'>
                  <label
                    htmlFor='start-time'
                    className='mb-1 block text-xs text-foreground-secondary'
                  >
                    Start (seconds)
                  </label>
                  <input
                    id='start-time'
                    type='number'
                    min='0'
                    max={audioDuration}
                    step='0.1'
                    value={startTimeInput}
                    onChange={(e) => setStartTimeInput(e.target.value)}
                    placeholder='0'
                    className='w-full rounded border border-border-primary bg-background-primary px-2 py-1 text-sm text-foreground-primary focus:border-accent-brand focus:outline-none'
                  />
                </div>
                <div className='flex-1'>
                  <label
                    htmlFor='end-time'
                    className='mb-1 block text-xs text-foreground-secondary'
                  >
                    End (seconds)
                  </label>
                  <input
                    id='end-time'
                    type='number'
                    min='0'
                    max={audioDuration}
                    step='0.1'
                    value={endTimeInput}
                    onChange={(e) => setEndTimeInput(e.target.value)}
                    placeholder={
                      audioDuration > 0 ? audioDuration.toFixed(1) : '0'
                    }
                    className='w-full rounded border border-border-primary bg-background-primary px-2 py-1 text-sm text-foreground-primary focus:border-accent-brand focus:outline-none'
                  />
                </div>
                <button
                  type='button'
                  onClick={() => {
                    const start = parseFloat(startTimeInput) || 0;
                    const end = parseFloat(endTimeInput) || audioDuration;

                    if (start >= end) {
                      toast({
                        title: 'Invalid time range',
                        description: 'End time must be greater than start time',
                        status: 'warning',
                        duration: 4000,
                        isClosable: true,
                      });
                      return;
                    }

                    if (end > audioDuration) {
                      toast({
                        title: 'Invalid time range',
                        description: `End time cannot exceed audio duration (${audioDuration.toFixed(1)}s)`,
                        status: 'warning',
                        duration: 4000,
                        isClosable: true,
                      });
                      return;
                    }

                    setPreviewTimeRanges([
                      ...previewTimeRanges,
                      { start, end },
                    ]);

                    // Reset inputs
                    setStartTimeInput('');
                    setEndTimeInput('');
                  }}
                  className='rounded bg-accent-brand px-3 py-1 text-sm text-white transition-colors hover:bg-accent-brand/90'
                >
                  Add
                </button>
              </div>

              {/* List of added time ranges */}
              {previewTimeRanges.length > 0 && (
                <div className='space-y-2'>
                  <p className='text-xs font-medium text-foreground-secondary'>
                    Added Preview Ranges:
                  </p>
                  {previewTimeRanges.map((range, index) => (
                    <div
                      key={index}
                      className='flex items-center justify-between rounded border border-border-primary bg-background-primary px-3 py-2'
                    >
                      <span className='text-sm text-foreground-primary'>
                        {range.start.toFixed(1)}s - {range.end.toFixed(1)}s
                        {range.end - range.start > 0 &&
                          ` (${(range.end - range.start).toFixed(1)}s)`}
                      </span>
                      <button
                        type='button'
                        onClick={() => {
                          setPreviewTimeRanges(
                            previewTimeRanges.filter((_, i) => i !== index)
                          );
                        }}
                        className='text-foreground-tertiary transition-colors hover:text-red-500'
                      >
                        <svg
                          className='h-4 w-4'
                          fill='none'
                          stroke='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path
                            strokeLinecap='round'
                            strokeLinejoin='round'
                            strokeWidth={2}
                            d='M6 18L18 6M6 6l12 12'
                          />
                        </svg>
                      </button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {/* Actions */}
        <div className='mt-8 flex gap-3'>
          <button
            onClick={onClose}
            className='flex-1 rounded-lg bg-background-secondary px-6 py-3 text-foreground-primary transition-colors hover:bg-background-secondary/80'
          >
            Cancel
          </button>
          <button
            onClick={handleUpload}
            disabled={
              (uploadMode === 'file' && selectedFiles.length === 0) ||
              (uploadMode === 'link' && !linkUrl.trim()) ||
              !title.trim() ||
              isUploading
            }
            className='flex-1 rounded-lg bg-accent-brand px-6 py-3 text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
          >
            {isUploading ? (
              <div className='flex items-center justify-center gap-2'>
                <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>
                Uploading...
              </div>
            ) : isAudioOnly ? (
              'Add Audio References'
            ) : (
              `Upload ${referenceType === 'submission' ? 'Submission' : 'Reference'}`
            )}
          </button>
        </div>
      </div>

      {/* Warning dialog for submissions without time ranges */}
      <MarketplaceConfirmDialog
        isOpen={showTimeRangeWarning}
        onClose={() => setShowTimeRangeWarning(false)}
        onConfirm={() => {
          setShowTimeRangeWarning(false);
          // Proceed with upload without time ranges (empty array)
          performUpload([]);
        }}
        title='No Preview Time Ranges Added'
        message='You are uploading a submission without any preview time ranges. Creators will be able to listen to the entire song. Are you sure you want to continue?'
        confirmText='Upload Anyway'
        cancelText='Go Back'
        variant='warning'
        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>
        }
      />

      {/* Upload Error Dialog */}
      <MarketplaceConfirmDialog
        isOpen={!!uploadError}
        onClose={() => setUploadError(null)}
        onConfirm={() => setUploadError(null)}
        title='Upload Failed'
        message={
          uploadError
            ? `${uploadError}. Please try again.\n\nNote: non-audio uploads will be supported soon.`
            : ''
        }
        confirmText='Got it'
        variant='reject'
        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 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z'
            />
          </svg>
        }
      />
    </div>
  );
};

export default MarketplaceUploadMediaModal;
