'use client';

import Image from 'next/image';
import { 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 { useMarketplaceProject } from './MarketplaceProjectProvider';

const MarketplaceApplicationsList = () => {
  const {
    applications: realApplications,
    isCreator,
    handleAcceptApplication,
    handleRejectApplication,
    project,
  } = useMarketplaceProject();

  const { openModalWithData } = useModalContext();

  const ITEMS_PER_PAGE = 5;
  const [currentPage, setCurrentPage] = useState(1);
  const [confirmDialog, setConfirmDialog] = useState<{
    isOpen: boolean;
    type: 'accept' | 'reject';
    applicationId: string;
    applicantName: string;
  }>({
    isOpen: false,
    type: 'accept',
    applicationId: '',
    applicantName: '',
  });

  // Use real applications data
  const applications = realApplications;

  // Only show for creators when there are applications
  if (!isCreator || applications.length === 0) {
    return null;
  }

  // Pagination calculations
  const totalPages = Math.ceil(applications.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const paginatedApplications = applications.slice(startIndex, endIndex);

  // Generate page numbers to display
  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    const maxPagesToShow = 7;

    if (totalPages <= maxPagesToShow) {
      // Show all pages if total is small
      return Array.from({ length: totalPages }, (_, i) => i + 1);
    }

    // Always show first page
    pages.push(1);

    if (currentPage > 3) {
      pages.push('...');
    }

    // Show pages around current page
    const start = Math.max(2, currentPage - 1);
    const end = Math.min(totalPages - 1, currentPage + 1);

    for (let i = start; i <= end; i++) {
      pages.push(i);
    }

    if (currentPage < totalPages - 2) {
      pages.push('...');
    }

    // Always show last page
    if (totalPages > 1) {
      pages.push(totalPages);
    }

    return pages;
  };

  return (
    <div className='mb-8 rounded-xl border border-border-primary bg-background-primary p-6'>
      <div className='mb-4 flex items-center gap-2'>
        <svg
          className='h-5 w-5 text-accent-brand'
          fill='none'
          stroke='currentColor'
          viewBox='0 0 24 24'
        >
          <path
            strokeLinecap='round'
            strokeLinejoin='round'
            strokeWidth={2}
            d='M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z'
          />
        </svg>
        <h3 className='text-lg font-semibold text-foreground-primary'>
          Applications
        </h3>
        <span
          className='rounded-full px-2 py-0.5 text-xs font-medium text-white'
          style={{ backgroundColor: '#3A304D', color: '#A080D0' }}
        >
          {applications.length}
        </span>
      </div>

      {/* Applications as Chat Messages - Compact Style */}
      <div className='space-y-2'>
        {paginatedApplications.map((application) => (
          <div key={application.id} className='group flex gap-2 py-1'>
            <div className='flex-shrink-0'>
              <button
                onClick={() => {
                  if (!project) return;
                  openModalWithData(
                    ModalTypes.MARKETPLACE_PARTICIPANT_REVIEWS,
                    {
                      userId: Number(application.fulfiller_id),
                      userName:
                        application.fulfiller_display_name ||
                        `User #${application.fulfiller_id}`,
                      userRole: 'fulfiller' as const,
                      userAvatarUrl: application.fulfiller_avatar_url,
                      userHandle: application.fulfiller_handle || undefined,
                      projectId: project.id,
                      projectStatus: project.status,
                      canLeaveReview: false, // Creator can't review applicants before they're accepted
                    }
                  );
                }}
                className='cursor-pointer transition-opacity hover:opacity-80'
              >
                <div
                  className={`flex h-6 w-6 items-center justify-center rounded-full text-xs font-medium ${'bg-green-500 text-white'}`}
                >
                  {application.fulfiller_avatar_url ? (
                    <Image
                      src={application.fulfiller_avatar_url}
                      alt={application.fulfiller_display_name || 'User'}
                      width={24}
                      height={24}
                      className='h-6 w-6 rounded-full object-cover'
                    />
                  ) : (
                    'A'
                  )}
                </div>
              </button>
            </div>
            <div className='min-w-0 flex-1'>
              <div className='mb-0.5 flex items-center gap-2'>
                <button
                  onClick={() => {
                    if (!project) return;
                    openModalWithData(
                      ModalTypes.MARKETPLACE_PARTICIPANT_REVIEWS,
                      {
                        userId: Number(application.fulfiller_id),
                        userName:
                          application.fulfiller_display_name ||
                          `User #${application.fulfiller_id}`,
                        userRole: 'fulfiller' as const,
                        userAvatarUrl: application.fulfiller_avatar_url,
                        userHandle: application.fulfiller_handle || undefined,
                        projectId: project.id,
                        projectStatus: project.status,
                        canLeaveReview: false, // Creator can't review applicants before they're accepted
                      }
                    );
                  }}
                  className='cursor-pointer text-xs font-medium text-foreground-primary transition-colors hover:text-accent-brand'
                >
                  {application.fulfiller_display_name ||
                    `User #${application.fulfiller_id}`}
                </button>
                <span className='text-xs text-foreground-tertiary'>
                  • {new Date(application.applied_at).toLocaleTimeString()}
                </span>
                {/* Star Rating */}
                {application.fulfiller_average_rating !== null &&
                  application.fulfiller_average_rating !== undefined && (
                    <span className='flex items-center gap-1 text-foreground-secondary'>
                      <svg
                        className='h-3 w-3 text-yellow-500'
                        fill='currentColor'
                        viewBox='0 0 20 20'
                      >
                        <path d='M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z' />
                      </svg>
                      <span className='text-[10px]'>
                        {application.fulfiller_average_rating.toFixed(1)}
                      </span>
                    </span>
                  )}
                {/* Completed Projects Count */}
                {application.fulfiller_completed_project_count !== null &&
                  application.fulfiller_completed_project_count !== undefined &&
                  application.fulfiller_completed_project_count > 0 && (
                    <span
                      className='rounded-full px-1.5 py-0.5 text-[10px] font-medium'
                      style={{
                        backgroundColor: 'rgba(34, 197, 94, 0.1)',
                        color: '#22c55e',
                      }}
                    >
                      {application.fulfiller_completed_project_count}{' '}
                      {application.fulfiller_completed_project_count === 1
                        ? 'project'
                        : 'projects'}
                    </span>
                  )}
                <span
                  className='rounded-full px-1.5 py-0.5 text-[10px] font-medium'
                  style={{
                    backgroundColor: 'rgba(58, 48, 77, 0.3)',
                    color: '#A080D0',
                  }}
                >
                  {application.estimated_completion_days ?? 7}d
                </span>
                {application.status === 'PENDING' && (
                  <div className='ml-auto flex gap-1.5'>
                    <MarketplaceButton
                      variant='accept'
                      onClick={() => {
                        setConfirmDialog({
                          isOpen: true,
                          type: 'accept',
                          applicationId: application.id,
                          applicantName:
                            application.fulfiller_display_name ||
                            `User #${application.fulfiller_id}`,
                        });
                      }}
                    >
                      Accept
                    </MarketplaceButton>
                    <MarketplaceButton
                      variant='reject'
                      onClick={() => {
                        setConfirmDialog({
                          isOpen: true,
                          type: 'reject',
                          applicationId: application.id,
                          applicantName:
                            application.fulfiller_display_name ||
                            `User #${application.fulfiller_id}`,
                        });
                      }}
                    >
                      Reject
                    </MarketplaceButton>
                  </div>
                )}
              </div>
              <p className='line-clamp-2 text-xs text-foreground-secondary'>
                {application.message}
              </p>
              {/* Portfolio URL */}
              {application.portfolio_url && (
                <div className='mt-1.5 flex items-center gap-1.5'>
                  <svg
                    className='h-3 w-3 flex-shrink-0 text-foreground-tertiary'
                    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>
                  <a
                    href={application.portfolio_url}
                    target='_blank'
                    rel='noopener noreferrer'
                    className='truncate text-xs text-accent-brand transition-colors hover:text-accent-brand/80'
                    onClick={(e) => e.stopPropagation()}
                  >
                    {application.portfolio_url}
                  </a>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className='mt-4 flex items-center justify-between border-t border-border-primary pt-4'>
          <div className='text-xs text-foreground-secondary'>
            Showing {startIndex + 1}-{Math.min(endIndex, applications.length)}{' '}
            of {applications.length} applications
          </div>
          <div className='flex items-center gap-1'>
            {/* Previous Button */}
            <button
              onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
              disabled={currentPage === 1}
              className='flex h-7 w-7 items-center justify-center rounded border border-border-primary bg-background-primary text-foreground-primary transition-colors hover:bg-background-secondary disabled:cursor-not-allowed disabled:opacity-50'
              aria-label='Previous page'
            >
              <svg
                className='h-3 w-3'
                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>

            {/* Page Numbers */}
            {getPageNumbers().map((page, index) =>
              page === '...' ? (
                <span
                  key={`ellipsis-${index}`}
                  className='flex h-7 w-7 items-center justify-center text-xs text-foreground-tertiary'
                >
                  ...
                </span>
              ) : (
                <button
                  key={page}
                  onClick={() => setCurrentPage(page as number)}
                  className={`flex h-7 w-7 items-center justify-center rounded text-xs font-medium transition-colors ${
                    currentPage === page
                      ? 'bg-accent-brand text-white'
                      : 'border border-border-primary bg-background-primary text-foreground-primary hover:bg-background-secondary'
                  }`}
                  aria-label={`Page ${page}`}
                  aria-current={currentPage === page ? 'page' : undefined}
                >
                  {page}
                </button>
              )
            )}

            {/* Next Button */}
            <button
              onClick={() =>
                setCurrentPage((prev) => Math.min(totalPages, prev + 1))
              }
              disabled={currentPage === totalPages}
              className='flex h-7 w-7 items-center justify-center rounded border border-border-primary bg-background-primary text-foreground-primary transition-colors hover:bg-background-secondary disabled:cursor-not-allowed disabled:opacity-50'
              aria-label='Next page'
            >
              <svg
                className='h-3 w-3'
                fill='none'
                stroke='currentColor'
                viewBox='0 0 24 24'
              >
                <path
                  strokeLinecap='round'
                  strokeLinejoin='round'
                  strokeWidth={2}
                  d='M9 5l7 7-7 7'
                />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* Confirmation Dialog */}
      <MarketplaceConfirmDialog
        isOpen={confirmDialog.isOpen}
        onClose={() => setConfirmDialog({ ...confirmDialog, isOpen: false })}
        onConfirm={async () => {
          try {
            if (confirmDialog.type === 'accept') {
              await handleAcceptApplication(confirmDialog.applicationId);
            } else {
              await handleRejectApplication(confirmDialog.applicationId);
            }
          } catch (error) {
            console.error(`Error ${confirmDialog.type}ing application:`, error);
            alert(
              `Failed to ${confirmDialog.type} application. Please try again.`
            );
          }
        }}
        title={
          confirmDialog.type === 'accept'
            ? 'Accept Application'
            : 'Reject Application'
        }
        message={
          confirmDialog.type === 'accept'
            ? `Are you sure you want to accept ${confirmDialog.applicantName}'s application? They will be assigned to this project.`
            : `Are you sure you want to reject ${confirmDialog.applicantName}'s application? This action cannot be undone.`
        }
        confirmText={confirmDialog.type === 'accept' ? 'Accept' : 'Reject'}
        cancelText='Cancel'
        variant={confirmDialog.type}
        icon={
          confirmDialog.type === 'accept' ? (
            <svg
              className='h-6 w-6'
              fill='none'
              stroke='currentColor'
              viewBox='0 0 24 24'
            >
              <path
                strokeLinecap='round'
                strokeLinejoin='round'
                strokeWidth={2}
                d='M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z'
              />
            </svg>
          ) : (
            <svg
              className='h-6 w-6'
              fill='none'
              stroke='currentColor'
              viewBox='0 0 24 24'
            >
              <path
                strokeLinecap='round'
                strokeLinejoin='round'
                strokeWidth={2}
                d='M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z'
              />
            </svg>
          )
        }
      />
    </div>
  );
};

export default MarketplaceApplicationsList;
