'use client';

import { observer } from 'mobx-react-lite';
import Image from 'next/image';
import React, { useState } from 'react';

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

import MarketplaceButton from '../shared/MarketplaceButton';
import MarketplaceConfirmDialog from '../shared/MarketplaceConfirmDialog';
import MarketplaceDeadlineForm from '../shared/MarketplaceDeadlineForm';
import MarketplaceMediaLibrary from './MarketplaceMediaLibrary';
import { useMarketplaceProject } from './MarketplaceProjectProvider';

export type Props = React.HTMLAttributes<HTMLDivElement> & {
  className?: string;
};

const MarketplaceProjectSidebar: React.FC<Props> = observer((props) => {
  const { className = '', ...restProps } = props;
  const { openModalWithData } = useModalContext();
  const [showSupportModal, setShowSupportModal] = useState(false);

  const {
    project,
    isLoading,
    isCreator,
    selectedMediaFilter: _selectedMediaFilter,
    setSelectedMediaFilter: _setSelectedMediaFilter,
    isEditingDescription: _isEditingDescription,
    editDescription: _editDescription,
    setEditDescription: _setEditDescription,
    handleEditDescription: _handleEditDescription,
    handleSaveDescription: _handleSaveDescription,
    handleCancelDescriptionEdit: _handleCancelDescriptionEdit,
    handleSaveDeadline,
    handleUnpublishProject,
    handleDeleteProject,
    handlePublishProject,
    isPublishing,
    isSavingProject,
    showClipboardSuccess,
    setShowClipboardSuccess,
    mediaReferences,
    fetchMediaReferences,
    viewMode,
    activeMediaId,
    setActiveMediaId,
    filterByMediaId,
    setFilterByMediaId,
    messagesByMedia,
  } = useMarketplaceProject();

  // Skeleton loading state
  if (isLoading) {
    return (
      <div
        className={`h-screen w-72 flex-shrink-0 overflow-y-auto border-l border-border-primary bg-background-secondary p-4 ${className}`}
        {...restProps}
      >
        <div className='space-y-4'>
          {/* Status Skeleton */}
          <div>
            <div className='mb-2 h-4 w-12 animate-pulse rounded bg-background-primary' />
            <div className='h-6 w-20 animate-pulse rounded bg-background-primary' />
          </div>

          {/* Credit Bounty Skeleton */}
          <div>
            <div className='mb-2 h-4 w-20 animate-pulse rounded bg-background-primary' />
            <div className='h-8 w-24 animate-pulse rounded bg-background-primary' />
          </div>

          {/* Actions Skeleton */}
          <div className='space-y-3'>
            <div className='h-10 w-full animate-pulse rounded-lg bg-background-primary' />
            <div className='h-10 w-full animate-pulse rounded-lg bg-background-primary' />
          </div>

          {/* Description Skeleton */}
          <div className='border-t border-border-primary pt-4'>
            <div className='mb-3 h-4 w-24 animate-pulse rounded bg-background-primary' />
            <div className='h-20 w-full animate-pulse rounded-lg bg-background-primary' />
          </div>
        </div>
      </div>
    );
  }

  if (!project) return null;

  const renderStatusBadge = (status: string) => {
    const statusConfig = {
      DRAFT: {
        label: 'Draft',
        color: 'text-gray-400',
        borderColor: 'border-gray-400/30',
        bg: 'bg-gray-400/10',
        hover: 'hover:bg-gray-400/20',
      },
      OPEN: {
        label: 'Open',
        color: 'text-green-400',
        borderColor: 'border-green-400/30',
        bg: 'bg-green-400/10',
        hover: 'hover:bg-green-400/20',
      },
      IN_PROGRESS: {
        label: 'In Progress',
        color: 'text-green-400',
        borderColor: 'border-green-400/30',
        bg: 'bg-green-400/10',
        hover: 'hover:bg-green-400/20',
      },
      COMPLETED: {
        label: 'Completed',
        color: 'text-purple-400',
        borderColor: 'border-purple-400/30',
        bg: 'bg-purple-400/10',
        hover: 'hover:bg-purple-400/20',
      },
      CANCELLED: {
        label: 'Cancelled',
        color: 'text-red-400',
        borderColor: 'border-red-400/30',
        bg: 'bg-red-400/10',
        hover: 'hover:bg-red-400/20',
      },
      PENDING_REVIEW: {
        label: 'Pending Review',
        color: 'text-yellow-400',
        borderColor: 'border-yellow-400/30',
        bg: 'bg-yellow-400/10',
        hover: 'hover:bg-yellow-400/20',
      },
      REVISION_REQUESTED: {
        label: 'Revision Requested',
        color: 'text-orange-400',
        borderColor: 'border-orange-400/30',
        bg: 'bg-orange-400/10',
        hover: 'hover:bg-orange-400/20',
      },
    };

    const config =
      statusConfig[status as keyof typeof statusConfig] || statusConfig.DRAFT;

    return (
      <span
        className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium transition-colors ${config.color} ${config.borderColor} ${config.bg} ${config.hover}`}
      >
        {config.label}
      </span>
    );
  };

  return (
    <div
      className={`flex h-screen w-72 flex-shrink-0 flex-col border-l border-border-primary bg-background-secondary ${className}`}
      {...restProps}
    >
      <div className='flex-1 overflow-y-auto p-4'>
        <div className='space-y-4'>
          {/* Status */}
          <div>
            <h3 className='mb-2 text-sm font-medium text-foreground-secondary'>
              Status
            </h3>
            <div className='flex items-center gap-2'>
              {renderStatusBadge(project.status)}
              {project.status === 'OPEN' &&
                !project.fulfiller_id &&
                isCreator && (
                  <MarketplaceButton
                    variant='warning'
                    onClick={handleUnpublishProject}
                    title='Unpublish project'
                    icon={
                      <svg
                        className='h-3 w-3'
                        fill='none'
                        stroke='currentColor'
                        viewBox='0 0 24 24'
                      >
                        <path
                          strokeLinecap='round'
                          strokeLinejoin='round'
                          strokeWidth={2}
                          d='M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6'
                        />
                      </svg>
                    }
                  >
                    Unpublish
                  </MarketplaceButton>
                )}
              {project.status === 'DRAFT' && isCreator && (
                <>
                  <button
                    onClick={handlePublishProject}
                    disabled={isPublishing}
                    className='flex items-center gap-1 rounded-lg border border-accent-brand/30 bg-accent-brand/10 px-2 py-1 text-xs font-medium text-accent-brand transition-colors hover:bg-accent-brand/20 disabled:opacity-50'
                    title='Publish project'
                  >
                    {isPublishing ? (
                      <>
                        <svg
                          className='h-3 w-3 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>
                        Publishing...
                      </>
                    ) : (
                      <>
                        <svg
                          className='h-3 w-3'
                          fill='none'
                          stroke='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path
                            strokeLinecap='round'
                            strokeLinejoin='round'
                            strokeWidth={2}
                            d='M12 19l9 2-9-18-9 18 9-2zm0 0v-8'
                          />
                        </svg>
                        Publish
                      </>
                    )}
                  </button>
                  <button
                    onClick={handleDeleteProject}
                    className='flex items-center gap-1 rounded-lg border border-red-500/30 bg-red-500/10 px-2 py-1 text-xs font-medium text-red-400 transition-colors hover:bg-red-500/20'
                    title='Delete project'
                  >
                    <svg
                      className='h-3 w-3'
                      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>
          </div>

          {/* Credit Bounty */}
          <div>
            <h3 className='mb-2 text-sm font-medium text-foreground-secondary'>
              Credit Bounty
            </h3>
            <p className='text-lg font-bold text-accent-brand'>
              {project.credit_bounty} credits
            </p>
          </div>

          {/* Deadline - Editable for creators when project is not completed */}
          {isCreator && project.status !== 'COMPLETED' ? (
            <MarketplaceDeadlineForm
              deadline={project.deadline}
              onSave={handleSaveDeadline}
              isSaving={isSavingProject}
              isCreator={isCreator}
              compact={true}
            />
          ) : project.deadline ? (
            (() => {
              const deadlineDate = new Date(project.deadline);
              const now = new Date();
              // Set both to start of day for accurate day calculation
              const deadlineStart = new Date(
                deadlineDate.getFullYear(),
                deadlineDate.getMonth(),
                deadlineDate.getDate()
              );
              const nowStart = new Date(
                now.getFullYear(),
                now.getMonth(),
                now.getDate()
              );
              const diffTime = deadlineStart.getTime() - nowStart.getTime();
              const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24));
              const isOverdue = diffDays < 0;
              const isDueToday = diffDays === 0;
              const isDueSoon = diffDays > 0 && diffDays <= 3;

              const formatDate = (date: Date) => {
                return date.toLocaleDateString('en-US', {
                  month: 'short',
                  day: 'numeric',
                  year: 'numeric',
                });
              };

              return (
                <div>
                  <h3 className='mb-2 text-sm font-medium text-foreground-secondary'>
                    Deadline
                  </h3>
                  <div className='space-y-1'>
                    <p className='text-sm font-medium text-foreground-primary'>
                      {formatDate(deadlineDate)}
                    </p>
                    {isOverdue ? (
                      <p className='text-xs font-medium text-red-400'>
                        {Math.abs(diffDays)} day
                        {Math.abs(diffDays) !== 1 ? 's' : ''} overdue
                      </p>
                    ) : isDueToday ? (
                      <p className='text-xs font-medium text-yellow-400'>
                        Due today
                      </p>
                    ) : isDueSoon ? (
                      <p className='text-xs font-medium text-yellow-400'>
                        {diffDays} day{diffDays !== 1 ? 's' : ''} left
                      </p>
                    ) : (
                      <p className='text-xs text-foreground-tertiary'>
                        {diffDays} day{diffDays !== 1 ? 's' : ''} remaining
                      </p>
                    )}
                  </div>
                </div>
              );
            })()
          ) : null}

          {/* Number of Applicants - Only show for non-creators when project is open */}
          {!isCreator && project.status === 'OPEN' && (
            <div>
              <h3 className='mb-2 text-sm font-medium text-foreground-secondary'>
                Applicants
              </h3>
              <p className='text-2xl font-bold text-accent-brand'>
                {project.applicant_count || 0}
              </p>
            </div>
          )}

          {/* Actions - Only show for creators when project is open */}
          {isCreator && project.status === 'OPEN' && (
            <div className='space-y-3'>
              {/* Share Button */}
              <button
                onClick={() => {
                  navigator.clipboard.writeText(window.location.href);
                  setShowClipboardSuccess(true);
                  setTimeout(() => setShowClipboardSuccess(false), 2000);
                }}
                className='w-full rounded-lg border px-4 py-2 text-sm font-medium text-foreground-secondary transition-colors hover:text-foreground-primary'
                style={{
                  backgroundColor: 'transparent',
                  borderColor: '#374151',
                  borderStyle: 'dashed',
                }}
              >
                <div className='flex items-center justify-center gap-2'>
                  {showClipboardSuccess ? (
                    <>
                      <svg
                        className='h-4 w-4'
                        fill='currentColor'
                        viewBox='0 0 20 20'
                        aria-hidden='true'
                      >
                        <path
                          fillRule='evenodd'
                          d='M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z'
                          clipRule='evenodd'
                        />
                      </svg>
                      Link copied
                    </>
                  ) : (
                    <>
                      <svg
                        className='h-4 w-4'
                        fill='none'
                        stroke='currentColor'
                        viewBox='0 0 24 24'
                        aria-hidden='true'
                      >
                        <path
                          strokeLinecap='round'
                          strokeLinejoin='round'
                          strokeWidth={2}
                          d='M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.367 2.684 3 3 0 00-5.367-2.684z'
                        />
                      </svg>
                      Share Project
                    </>
                  )}
                </div>
              </button>
            </div>
          )}

          {/* Participants - Show when project has a fulfiller */}
          {project.fulfiller_id && (
            <div className='border-t border-border-primary pt-4'>
              <h3 className='mb-3 text-sm font-medium text-foreground-secondary'>
                Participants
              </h3>
              <div className='flex flex-wrap items-center gap-4'>
                {/* Creator */}
                <button
                  onClick={() => {
                    // Don't open modal if clicking on yourself
                    if (isCreator) {
                      return;
                    }

                    openModalWithData(
                      ModalTypes.MARKETPLACE_PARTICIPANT_REVIEWS,
                      {
                        userId: Number(project.creator_id),
                        userName:
                          project.creator_display_name ||
                          project.creator_handle ||
                          'Creator',
                        userRole: 'creator' as const,
                        userAvatarUrl: project.creator_avatar_url,
                        userHandle: project.creator_handle || undefined,
                        projectId: project.id,
                        projectStatus: project.status,
                        canLeaveReview: true,
                      }
                    );
                  }}
                  className={`flex items-center gap-2 rounded-lg p-2 transition-colors ${
                    isCreator ? 'cursor-default' : 'hover:bg-background-primary'
                  }`}
                >
                  <div className='flex h-6 w-6 items-center justify-center rounded-full bg-accent-brand text-xs font-medium text-white'>
                    {project.creator_avatar_url ? (
                      <Image
                        src={project.creator_avatar_url}
                        alt={project.creator_display_name || 'Creator'}
                        width={24}
                        height={24}
                        className='h-6 w-6 rounded-full object-cover'
                      />
                    ) : (
                      'C'
                    )}
                  </div>
                  <div className='min-w-0'>
                    <div className='text-xs font-medium text-foreground-primary'>
                      {project.creator_display_name ||
                        project.creator_handle ||
                        'Creator'}
                    </div>
                    <div className='text-xs text-foreground-tertiary'>
                      Creator
                    </div>
                  </div>
                </button>

                {/* Fulfiller */}
                {project.fulfiller_id && (
                  <button
                    onClick={() => {
                      // Don't open modal if clicking on yourself (fulfiller viewing fulfiller)
                      if (!isCreator) {
                        return;
                      }

                      openModalWithData(
                        ModalTypes.MARKETPLACE_PARTICIPANT_REVIEWS,
                        {
                          userId: Number(project.fulfiller_id),
                          userName:
                            project.fulfiller_display_name ||
                            project.fulfiller_handle ||
                            'Fulfiller',
                          userRole: 'fulfiller' as const,
                          userAvatarUrl: project.fulfiller_avatar_url,
                          userHandle: project.fulfiller_handle || undefined,
                          projectId: project.id,
                          projectStatus: project.status,
                          canLeaveReview: true,
                        }
                      );
                    }}
                    className={`flex items-center gap-2 rounded-lg p-2 transition-colors ${
                      !isCreator
                        ? 'cursor-default'
                        : 'hover:bg-background-primary'
                    }`}
                  >
                    <div className='flex h-6 w-6 items-center justify-center rounded-full bg-green-500 text-xs font-medium text-white'>
                      {project.fulfiller_avatar_url ? (
                        <Image
                          src={project.fulfiller_avatar_url}
                          alt={project.fulfiller_display_name || 'Fulfiller'}
                          width={24}
                          height={24}
                          className='h-6 w-6 rounded-full object-cover'
                        />
                      ) : (
                        'F'
                      )}
                    </div>
                    <div className='min-w-0'>
                      <div className='text-xs font-medium text-foreground-primary'>
                        {project.fulfiller_display_name ||
                          project.fulfiller_handle ||
                          'Fulfiller'}
                      </div>
                      <div className='text-xs text-foreground-tertiary'>
                        Fulfiller
                      </div>
                    </div>
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Media Library - Replaces submissions section */}
          <div className='border-t border-border-primary pt-4'>
            <MarketplaceMediaLibrary
              mediaReferences={mediaReferences}
              messagesByMedia={messagesByMedia}
              activeMediaId={activeMediaId}
              onMediaSelect={(mediaId) => {
                setActiveMediaId(mediaId);
                // Don't filter comments - only set active track
                // Dispatch event to scroll to media in media view
                if (viewMode === 'media') {
                  const event = new CustomEvent('switchActiveMedia', {
                    detail: { mediaId },
                  });
                  window.dispatchEvent(event);
                }
              }}
              filterByMediaId={filterByMediaId}
              onClearFilter={() => setFilterByMediaId(null)}
              isWaveformCollapsed={false}
              project={project}
              isCreator={isCreator}
              fetchMediaReferences={fetchMediaReferences}
            />
          </div>
        </div>
      </div>

      {/* Support Button - Fixed to bottom */}
      <div className='flex-shrink-0 border-t border-border-primary bg-background-secondary p-4'>
        <MarketplaceButton
          variant='secondary'
          onClick={() => setShowSupportModal(true)}
          icon={
            <svg
              className='h-4 w-4'
              fill='none'
              stroke='currentColor'
              viewBox='0 0 24 24'
            >
              <path
                strokeLinecap='round'
                strokeLinejoin='round'
                strokeWidth={2}
                d='M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z'
              />
            </svg>
          }
        >
          Support
        </MarketplaceButton>
      </div>

      {/* Support Modal */}
      <MarketplaceConfirmDialog
        isOpen={showSupportModal}
        onClose={() => setShowSupportModal(false)}
        onConfirm={() => setShowSupportModal(false)}
        title='Contact Support'
        message='For all disputes, issues, or questions regarding marketplace projects, please contact our support team at support@suno.com'
        confirmText='Got it'
        cancelText='Cancel'
        variant='primary'
        icon={
          <svg
            className='h-6 w-6'
            fill='none'
            stroke='currentColor'
            viewBox='0 0 24 24'
          >
            <path
              strokeLinecap='round'
              strokeLinejoin='round'
              strokeWidth={2}
              d='M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z'
            />
          </svg>
        }
      />
    </div>
  );
});

export default MarketplaceProjectSidebar;
