'use client';

import { observer } from 'mobx-react-lite';
import { useRouter } from 'next/navigation';
import { useState } from 'react';

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

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

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

const MarketplaceProjectTopBar: React.FC<Props> = observer((props) => {
  const { className: _className } = props;
  const router = useRouter();
  const [withdrawConfirmOpen, setWithdrawConfirmOpen] = useState(false);
  const { openModalWithData } = useModalContext();

  const {
    project,
    isLoading,
    isEditingTitle,
    editTitle,
    isSavingProject,
    isPublishing,
    handleSaveTitle,
    handlePublishProject,
    handleEditTitle,
    handleCancelTitleEdit,
    setEditTitle,
    viewMode,
    setViewMode,
    mediaReferences,
    userApplication,
    isCheckingApplication,
    setShowApplicationModal,
    handleWithdrawApplication,
    fetchProject,
    canApply,
    activeProjectsCount,
    activeProjectLimit,
    isLoadingActiveProjectsCount,
    currentUser,
  } = useMarketplaceProject();

  // Show skeleton while loading project data
  if (isLoading) {
    return (
      <div className='border-b border-border-primary bg-background-secondary px-6 py-4'>
        <div className='flex items-center gap-4'>
          {/* Back button skeleton */}
          <div className='flex items-center gap-2 rounded-lg px-3 py-2'>
            <div className='h-4 w-4 animate-pulse rounded bg-background-primary' />
            <div className='h-4 w-24 animate-pulse rounded bg-background-primary' />
          </div>
          {/* Title skeleton */}
          <div className='h-6 w-48 animate-pulse rounded bg-background-primary' />
        </div>
      </div>
    );
  }

  if (!project) return null;

  const isCreator = project.is_creator;

  return (
    <>
      {/* Hidden instruction text for screen readers */}
      <div id='title-edit-instructions' className='sr-only'>
        Press Enter to save or Escape to cancel
      </div>

      {/* Chat Header */}
      <div className='border-b border-border-primary bg-background-secondary px-6 py-4'>
        <div className='flex items-center justify-between gap-4'>
          <div className='flex items-center gap-4'>
            <button
              onClick={() => router.push('/marketplace')}
              className='group flex items-center gap-2 rounded-lg px-3 py-2 text-foreground-secondary transition-colors hover:bg-background-primary hover:text-foreground-primary focus:ring-2 focus:ring-accent-brand/50 focus:ring-offset-2 focus:outline-none'
              aria-label='Back to marketplace'
              type='button'
            >
              <svg
                className='h-4 w-4 transition-transform duration-200 group-hover:-translate-x-0.5'
                fill='none'
                stroke='currentColor'
                viewBox='0 0 24 24'
              >
                <path
                  strokeLinecap='round'
                  strokeLinejoin='round'
                  strokeWidth={2}
                  d='M15 19l-7-7 7-7'
                />
              </svg>
            </button>

            {/* Editable Project Title for Creators */}
            {isCreator ? (
              <div className='flex items-center gap-2'>
                {isEditingTitle ? (
                  <div className='flex items-center gap-2'>
                    <input
                      type='text'
                      value={editTitle}
                      onChange={(e) => setEditTitle(e.target.value)}
                      className='rounded border border-border-primary bg-transparent px-2 py-1 text-xl font-semibold text-foreground-primary focus:border-accent-brand focus:ring-2 focus:ring-accent-brand/50 focus:outline-none'
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          handleSaveTitle(editTitle);
                        } else if (e.key === 'Escape') {
                          handleCancelTitleEdit();
                        }
                      }}
                      onBlur={() => handleSaveTitle(editTitle)}
                      aria-label='Edit project title'
                      aria-describedby='title-edit-instructions'
                    />
                    <button
                      onClick={() => handleSaveTitle(editTitle)}
                      disabled={isSavingProject || !editTitle.trim()}
                      className='rounded text-accent-brand hover:text-accent-brand/80 focus:ring-2 focus:ring-accent-brand/50 focus:ring-offset-2 focus:outline-none disabled:opacity-50'
                      aria-label='Save title changes'
                      type='button'
                    >
                      <svg
                        className='h-4 w-4'
                        fill='none'
                        stroke='currentColor'
                        viewBox='0 0 24 24'
                      >
                        <path
                          strokeLinecap='round'
                          strokeLinejoin='round'
                          strokeWidth={2}
                          d='M5 13l4 4L19 7'
                        />
                      </svg>
                    </button>
                    <button
                      onClick={handleCancelTitleEdit}
                      className='rounded text-foreground-secondary hover:text-foreground-primary focus:ring-2 focus:ring-accent-brand/50 focus:ring-offset-2 focus:outline-none'
                      aria-label='Cancel title editing'
                      type='button'
                    >
                      <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 className='group flex items-center gap-2'>
                    <h1 className='text-xl font-semibold text-foreground-primary'>
                      {project.title.replace('Edit: ', '')}
                    </h1>
                    <div className='flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100'>
                      <button
                        onClick={handleEditTitle}
                        className='rounded text-foreground-secondary hover:text-foreground-primary focus:ring-2 focus:ring-accent-brand/50 focus:ring-offset-2 focus:outline-none'
                        aria-label='Edit project title'
                        type='button'
                      >
                        <svg
                          className='h-4 w-4'
                          fill='none'
                          stroke='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path
                            strokeLinecap='round'
                            strokeLinejoin='round'
                            strokeWidth={2}
                            d='M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z'
                          />
                        </svg>
                      </button>
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <h1 className='text-xl font-semibold text-foreground-primary'>
                {project.title.replace('Edit: ', '')}
              </h1>
            )}
          </div>

          {/* Right Side Actions */}
          <div className='flex items-center gap-2'>
            {/* Preview Listing Button - Only show for creators in DRAFT or OPEN status */}
            {(project.status === 'DRAFT' || project.status === 'OPEN') &&
              isCreator && (
                <MarketplaceButton
                  variant='secondary'
                  onClick={() => {
                    openModalWithData(ModalTypes.MARKETPLACE_EDIT_LISTING, {
                      projectId: project.id,
                      title: project.title,
                      summary: (project as any).summary || null,
                      description: project.description,
                      creditBounty: project.credit_bounty,
                      deadline: project.deadline || null,
                      originalClipImageUrl:
                        project.original_clip_image_url || null,
                      status: project.status,
                      onSaveComplete: () => {
                        // Refresh project data after save
                        fetchProject();
                      },
                    });
                  }}
                >
                  Preview Listing
                </MarketplaceButton>
              )}
            {/* View Mode Toggle */}
            <MarketplaceButton
              variant={viewMode === 'chat' ? 'secondary' : 'secondary'}
              onClick={() =>
                setViewMode(viewMode === 'chat' ? 'media' : 'chat')
              }
            >
              {viewMode === 'chat'
                ? 'Group messages by track'
                : 'Show single chat'}
            </MarketplaceButton>
          </div>
        </div>
      </div>

      {/* Project Ready to Publish Alert - Only show when needed */}
      {project.status === 'DRAFT' && isCreator && (
        <div className='animate-in fade-in bg-background-primary px-6 py-4 duration-300'>
          <div className='mx-auto max-w-3xl'>
            <MarketplaceAlert
              icon={
                <svg
                  className='mt-0.5 h-5 w-5 flex-shrink-0 text-accent-brand'
                  fill='currentColor'
                  viewBox='0 0 24 24'
                  aria-hidden='true'
                >
                  <path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z' />
                </svg>
              }
              title='Project Ready to Publish'
              text='Your project is complete and ready to be published to the marketplace. Once published, fulfillers will be able to apply to edit your project.'
              buttons={[
                {
                  label: isPublishing ? 'Publishing...' : 'Publish',
                  onClick: handlePublishProject,
                  variant: 'primary',
                  disabled: isPublishing,
                },
              ]}
              variant='warning'
              aria-label='Project ready to publish notification'
            />
          </div>
        </div>
      )}

      {/* Submissions Pending Review Alert - Only show for creators when project has pending submissions */}
      {project.status === 'PENDING_REVIEW' &&
        isCreator &&
        (() => {
          // Find the pending submission
          const pendingSubmission = mediaReferences.find(
            (m) =>
              m.reference_type === 'submission' &&
              (m.is_accepted === null || m.is_accepted === undefined)
          );

          const handleViewSubmission = () => {
            if (!pendingSubmission) return;

            // Dispatch custom event to scroll/switch to the pending submission
            // Both chat and media views will handle this appropriately
            window.dispatchEvent(
              new CustomEvent('switchActiveMedia', {
                detail: { mediaId: pendingSubmission.id },
              })
            );
          };

          return (
            <div className='mt-1 flex justify-center border-b border-border-primary/30 bg-background-primary/50 px-4 py-3'>
              <div className='flex items-center gap-3'>
                <svg
                  className='h-4 w-4 flex-shrink-0 text-accent-brand/80'
                  fill='currentColor'
                  viewBox='0 0 24 24'
                  aria-hidden='true'
                >
                  <path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z' />
                </svg>
                <span className='text-sm font-medium text-foreground-primary'>
                  Submission Pending Review
                </span>
                <button
                  onClick={handleViewSubmission}
                  className='rounded-lg border border-accent-brand/30 bg-accent-brand/10 px-3 py-1 text-xs font-medium text-accent-brand transition-colors hover:bg-accent-brand/20'
                >
                  View Submission
                </button>
              </div>
            </div>
          );
        })()}

      {/* Fulfiller Work Alert - Only show for fulfillers when project is in progress */}
      {project.status === 'IN_PROGRESS' &&
        !isCreator &&
        project.fulfiller_id &&
        currentUser?.id &&
        Number(project.fulfiller_id) === currentUser.id && (
          <div className='mt-1 flex justify-center border-b border-border-primary/30 bg-background-primary/50 px-4 py-3'>
            <div className='flex items-center gap-3'>
              <svg
                className='h-4 w-4 flex-shrink-0 text-accent-brand/80'
                fill='currentColor'
                viewBox='0 0 24 24'
                aria-hidden='true'
              >
                <path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z' />
              </svg>
              <span className='text-sm font-medium text-foreground-primary'>
                Review the project requests and submit your tracks
              </span>
            </div>
          </div>
        )}

      {/* Completed Project Download Alert - Only show for creators when project is completed */}
      {project.status === 'COMPLETED' &&
        isCreator &&
        (() => {
          // Find all accepted submissions
          const acceptedSubmissions = mediaReferences.filter(
            (m) => m.reference_type === 'submission' && m.is_accepted === true
          );

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

          return (
            <div className='mt-1 flex flex-col items-center border-b border-border-primary/30 bg-background-primary/50 px-4 py-3'>
              <div className='flex items-center gap-3'>
                <svg
                  className='h-4 w-4 flex-shrink-0 text-green-500/80'
                  fill='currentColor'
                  viewBox='0 0 24 24'
                  aria-hidden='true'
                >
                  <path d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z' />
                </svg>
                <span className='text-sm font-medium text-foreground-primary'>
                  Project completed! You can download the accepted tracks below.
                </span>
              </div>
              <div className='mt-2 flex flex-wrap justify-center gap-2'>
                {acceptedSubmissions.map((submission) => (
                  <a
                    key={submission.id}
                    href={submission.url}
                    download
                    className='flex items-center gap-1.5 rounded-lg border border-green-500/30 bg-green-500/10 px-3 py-1.5 text-xs font-medium text-green-400 transition-colors hover:bg-green-500/20'
                    onClick={(e) => e.stopPropagation()}
                  >
                    <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='M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4'
                      />
                    </svg>
                    <span>
                      {submission.title.replace('Edit: ', '') || 'Download'}
                    </span>
                  </a>
                ))}
              </div>
            </div>
          );
        })()}

      {/* Application Alert - Only show for non-creators when project is open */}
      {project.status === 'OPEN' && !isCreator && (
        <div className='animate-in fade-in bg-background-primary px-6 py-4 duration-300'>
          <div className='mx-auto max-w-3xl'>
            {isCheckingApplication ? (
              <div className='space-y-3'>
                <div className='h-5 w-48 animate-pulse rounded bg-background-secondary' />
                <div className='h-10 w-full animate-pulse rounded bg-background-secondary' />
              </div>
            ) : userApplication ? (
              <MarketplaceAlert
                variant={
                  userApplication.status === 'PENDING'
                    ? 'warning'
                    : userApplication.status === 'ACCEPTED'
                      ? 'success'
                      : userApplication.status === 'REJECTED'
                        ? 'error'
                        : 'info'
                }
                title={
                  userApplication.status === 'PENDING'
                    ? 'Your application is pending review'
                    : userApplication.status === 'ACCEPTED'
                      ? 'Congratulations! Your application was accepted'
                      : userApplication.status === 'REJECTED'
                        ? 'Your application was not selected'
                        : 'You withdrew your application'
                }
                text={
                  userApplication.status === 'REJECTED' &&
                  userApplication.message
                    ? `You cannot apply again to this project as your application was already reviewed.`
                    : userApplication.status === 'REJECTED'
                      ? 'You cannot apply again to this project as your application was already reviewed.'
                      : userApplication.message
                        ? `"${userApplication.message}"`
                        : undefined
                }
                buttons={
                  userApplication.status === 'PENDING'
                    ? [
                        {
                          label: 'Withdraw Application',
                          onClick: () => setWithdrawConfirmOpen(true),
                          variant: 'secondary',
                        },
                      ]
                    : []
                }
                aria-label='Application status notification'
              />
            ) : isLoadingActiveProjectsCount ? (
              <MarketplaceAlert
                icon={
                  <svg
                    className='mt-0.5 h-5 w-5 flex-shrink-0 text-accent-brand'
                    fill='none'
                    stroke='currentColor'
                    viewBox='0 0 24 24'
                    aria-hidden='true'
                  >
                    <path
                      strokeLinecap='round'
                      strokeLinejoin='round'
                      strokeWidth={2}
                      d='M12 4v16m8-8H4'
                    />
                  </svg>
                }
                title='Loading...'
                text='Checking application eligibility...'
                variant='warning'
                aria-label='Loading application status'
              />
            ) : canApply ? (
              <MarketplaceAlert
                icon={
                  <svg
                    className='mt-0.5 h-5 w-5 flex-shrink-0 text-accent-brand'
                    fill='none'
                    stroke='currentColor'
                    viewBox='0 0 24 24'
                    aria-hidden='true'
                  >
                    <path
                      strokeLinecap='round'
                      strokeLinejoin='round'
                      strokeWidth={2}
                      d='M12 4v16m8-8H4'
                    />
                  </svg>
                }
                title='Apply to Work on This Project'
                text='Share your skills and experience to work on this project.'
                buttons={[
                  {
                    label: 'Apply Now',
                    onClick: () => setShowApplicationModal(true),
                    variant: 'primary',
                  },
                ]}
                variant='warning'
                aria-label='Apply to project notification'
              />
            ) : (
              <MarketplaceAlert
                icon={
                  <svg
                    className='mt-0.5 h-5 w-5 flex-shrink-0 text-accent-brand'
                    fill='none'
                    stroke='currentColor'
                    viewBox='0 0 24 24'
                    aria-hidden='true'
                  >
                    <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>
                }
                title='Application Limit Reached'
                text={`You have ${activeProjectsCount || 0} active project${(activeProjectsCount || 0) !== 1 ? 's' : ''} (limit: ${activeProjectLimit}). Please complete one of your open projects before applying to new ones.`}
                variant='warning'
                aria-label='Application limit notification'
              />
            )}
          </div>
        </div>
      )}

      {/* Withdraw Application Confirmation Dialog */}
      {userApplication && (
        <MarketplaceConfirmDialog
          isOpen={withdrawConfirmOpen}
          onClose={() => setWithdrawConfirmOpen(false)}
          onConfirm={async () => {
            try {
              await handleWithdrawApplication(userApplication.id);
              setWithdrawConfirmOpen(false);
            } catch (error) {
              console.error('Error withdrawing application:', error);
              // Error will be shown in the dialog, so we just close it
              setWithdrawConfirmOpen(false);
            }
          }}
          title='Withdraw Application'
          message='Are you sure you want to withdraw your application? This action cannot be undone.'
          confirmText='Withdraw'
          cancelText='Cancel'
          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>
          }
        />
      )}
    </>
  );
});

export default MarketplaceProjectTopBar;
