'use client';

import Link from '@/components/link/Link';
import type { components } from '@/lib/gen';

type MarketplaceProject = components['schemas']['ProjectResponse'];

interface MarketplaceProjectRowProps {
  project: MarketplaceProject;
  viewMode?: 'browse' | 'my-projects';
}

const MarketplaceProjectRow = ({
  project,
  viewMode = 'browse',
}: MarketplaceProjectRowProps) => {
  const applicantCount = project.applicant_count;
  const hasApplicantCount =
    typeof applicantCount === 'number' && !Number.isNaN(applicantCount);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'DRAFT':
        return 'border-blue-500/30 bg-blue-500/10 text-blue-400';
      case 'OPEN':
        return 'border-green-500/30 bg-green-500/10 text-green-400';
      case 'IN_PROGRESS':
        return 'border-yellow-500/30 bg-yellow-500/10 text-yellow-400';
      case 'PENDING_REVIEW':
        return 'border-purple-500/30 bg-purple-500/10 text-purple-400';
      case 'COMPLETED':
        return 'border-teal-500/30 bg-teal-500/10 text-teal-400';
      case 'CANCELLED':
        return 'border-red-500/30 bg-red-500/10 text-red-400';
      default:
        return 'border-gray-500/30 bg-gray-500/10 text-gray-400';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'DRAFT':
        return 'Draft';
      case 'OPEN':
        return 'Open';
      case 'IN_PROGRESS':
        return 'In Progress';
      case 'PENDING_REVIEW':
        return 'Pending Review';
      case 'COMPLETED':
        return 'Completed';
      case 'CANCELLED':
        return 'Cancelled';
      default:
        return status;
    }
  };

  // Calculate days remaining from deadline
  const getDaysRemaining = (
    deadline: string | null | undefined
  ): string | null => {
    if (!deadline) return null;

    const deadlineDate = new Date(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));

    if (diffDays < 0) {
      return `${Math.abs(diffDays)} day${Math.abs(diffDays) !== 1 ? 's' : ''} overdue`;
    } else if (diffDays === 0) {
      return 'Due today';
    } else {
      return `${diffDays} day${diffDays !== 1 ? 's' : ''}`;
    }
  };

  return (
    <Link
      href={`/marketplace/project/${project.id}`}
      className='group flex h-[110px] cursor-pointer items-center gap-4 rounded-2xl bg-transparent px-3 py-3 transition-colors hover:bg-background-fog-thin'
    >
      {/* Image */}
      <div className='relative h-[86px] w-[67px] flex-shrink-0 overflow-hidden rounded-xl'>
        {project.original_clip_image_url ? (
          <img
            src={project.original_clip_image_url}
            alt={project.title}
            className='h-full w-full object-cover'
          />
        ) : (
          <div className='h-full w-full bg-gradient-to-br from-accent-brand/20 to-accent-brand/5' />
        )}
      </div>

      {/* Details */}
      <div className='min-w-0 flex-1'>
        {/* Title */}
        <div className='mb-1 flex items-center gap-2'>
          <div className='text-sm font-medium text-foreground-primary transition-colors group-hover:text-accent-brand'>
            {project.title}
          </div>
        </div>

        {/* Summary (fallback to description if summary not available) */}
        <div className='mb-2 line-clamp-1 text-xs text-foreground-secondary'>
          {project.summary != null && project.summary !== ''
            ? project.summary
            : project.description}
        </div>

        {/* Metadata */}
        <div className='flex items-center gap-3 text-xs text-foreground-tertiary'>
          <span className='rounded-md bg-accent-brand/10 px-2 py-1 font-medium text-accent-brand'>
            {project.credit_bounty} credits
          </span>
          {project.deadline &&
            (() => {
              const daysRemaining = getDaysRemaining(project.deadline);
              const isOverdue = daysRemaining?.includes('overdue');
              return (
                <span
                  className={`flex items-center gap-1 ${isOverdue ? 'text-red-400' : 'text-foreground-tertiary'}`}
                >
                  <svg
                    className='h-3 w-3'
                    fill='none'
                    stroke='currentColor'
                    viewBox='0 0 24 24'
                  >
                    <path
                      strokeLinecap='round'
                      strokeLinejoin='round'
                      strokeWidth={2}
                      d='M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z'
                    />
                  </svg>
                  {daysRemaining}
                </span>
              );
            })()}
          <span
            className={`inline-flex items-center rounded-lg border px-2 py-1 text-xs font-medium ${getStatusColor(project.status)}`}
          >
            {getStatusText(project.status)}
          </span>
          {viewMode === 'my-projects' && project.is_creator && (
            <span className='rounded-md bg-blue-500/10 px-2 py-1 text-xs font-medium text-blue-400'>
              Creator
            </span>
          )}
          {viewMode === 'my-projects' && project.is_fulfiller && (
            <span className='rounded-md bg-purple-500/10 px-2 py-1 text-xs font-medium text-purple-400'>
              Fulfiller
            </span>
          )}
          {viewMode === 'browse' &&
            project.creator_average_rating !== null &&
            project.creator_average_rating !== undefined &&
            project.creator_review_count !== null &&
            project.creator_review_count !== undefined &&
            project.creator_review_count > 0 && (
              <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>
                {project.creator_average_rating.toFixed(1)} (
                {project.creator_review_count})
              </span>
            )}
          {project.status === 'OPEN' && hasApplicantCount && (
            <span className='text-foreground-secondary'>
              {applicantCount} applicant
              {applicantCount !== 1 ? 's' : ''}
            </span>
          )}
          <span className='text-foreground-tertiary'>
            {new Date(project.created_at).toLocaleDateString()}
          </span>
        </div>
      </div>
    </Link>
  );
};

export default MarketplaceProjectRow;
