'use client';

import Link from 'next/link';
import { MapPin, Clock, Banknote, ChevronRight, Briefcase, MessageSquare } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { formatCurrency, formatDate } from '@/lib/utils';
import { cn } from '@/lib/utils';

interface JobCardProps {
  job: {
    id: string;
    title: string;
    description: string;
    budget?: number | string;
    location: string;
    status: string;
    createdAt: string;
    invitedWorkerId?: string | null;
    category?: { name: string; slug: string };
    _count?: { quotations: number };
  };
  href?: string;
  variant?: 'default' | 'listing';
}

const statusColors: Record<string, 'default' | 'secondary' | 'success' | 'warning' | 'destructive'> = {
  OPEN: 'success',
  QUOTED: 'warning',
  ACCEPTED: 'default',
  IN_PROGRESS: 'warning',
  COMPLETED: 'secondary',
  CANCELLED: 'destructive',
};

function isRecentJob(createdAt: string) {
  const days = (Date.now() - new Date(createdAt).getTime()) / (1000 * 60 * 60 * 24);
  return days <= 3;
}

export function JobCard({ job, href, variant = 'default' }: JobCardProps) {
  const isOpen = job.status === 'OPEN';
  const isRecent = isRecentJob(job.createdAt);

  if (variant === 'listing') {
    const content = (
      <Card
        className={cn(
          'group overflow-hidden transition-all hover:shadow-lg hover:border-slate-300',
          isOpen && 'border-l-[3px] border-l-accent'
        )}
      >
        <CardContent className="p-0">
          <div className="flex flex-col sm:flex-row sm:items-stretch">
            {/* Main content */}
            <div className="flex flex-1 gap-3 p-4 min-w-0">
              <div
                className={cn(
                  'hidden sm:flex h-12 w-12 shrink-0 items-center justify-center rounded-lg',
                  isOpen ? 'bg-emerald-50 text-accent' : 'bg-slate-100 text-slate-500'
                )}
              >
                <Briefcase className="h-5 w-5" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex flex-wrap items-center gap-1.5 mb-1">
                  {job.category && (
                    <Badge variant="secondary" className="normal-case tracking-normal">
                      {job.category.name}
                    </Badge>
                  )}
                  {isOpen && (
                    <Badge variant="success" className="normal-case tracking-normal">
                      Open
                    </Badge>
                  )}
                  {isRecent && (
                    <Badge variant="default" className="normal-case tracking-normal bg-primary/10 text-primary">
                      New
                    </Badge>
                  )}
                </div>
                <h3 className="font-bold text-slate-900 text-base sm:text-lg leading-snug group-hover:text-primary transition-colors line-clamp-2">
                  {job.title}
                </h3>
                <p className="text-sm text-muted mt-1.5 line-clamp-2 leading-relaxed">
                  {job.description}
                </p>
                <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-3 text-xs text-muted">
                  <span className="inline-flex items-center gap-1">
                    <MapPin className="h-3.5 w-3.5 shrink-0 text-slate-400" />
                    {job.location}
                  </span>
                  <span className="inline-flex items-center gap-1">
                    <Clock className="h-3.5 w-3.5 shrink-0 text-slate-400" />
                    {formatDate(job.createdAt)}
                  </span>
                  {job._count && job._count.quotations > 0 && (
                    <span className="inline-flex items-center gap-1 text-primary font-medium">
                      <MessageSquare className="h-3.5 w-3.5" />
                      {job._count.quotations} quote{job._count.quotations > 1 ? 's' : ''}
                    </span>
                  )}
                </div>
              </div>
            </div>

            {/* Budget + CTA */}
            <div className="flex sm:flex-col items-center justify-between sm:justify-center gap-3 border-t sm:border-t-0 sm:border-l border-border bg-slate-50/80 px-4 py-3 sm:py-4 sm:w-36 lg:w-40 shrink-0">
              {job.budget ? (
                <div className="text-left sm:text-center">
                  <p className="text-[10px] uppercase tracking-wide text-muted font-semibold">Budget</p>
                  <p className="text-lg font-bold text-accent flex items-center sm:justify-center gap-1">
                    <Banknote className="h-4 w-4 hidden sm:block" />
                    {formatCurrency(Number(job.budget))}
                  </p>
                </div>
              ) : (
                <p className="text-xs text-muted sm:text-center">Budget negotiable</p>
              )}
              {href && (
                <span className="inline-flex items-center gap-0.5 text-xs font-semibold text-primary group-hover:gap-1.5 transition-all">
                  View job
                  <ChevronRight className="h-4 w-4" />
                </span>
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    );

    if (href) return <Link href={href} className="block">{content}</Link>;
    return content;
  }

  // Default compact card (dashboards)
  const content = (
    <Card
      className={cn(
        'group hover:shadow-md hover:border-slate-300 transition-all',
        isOpen && 'border-l-4 border-l-accent'
      )}
    >
      <CardContent className="p-4">
        <div className="flex items-start gap-3">
          <div className="flex-1 min-w-0">
            <div className="flex flex-wrap items-center gap-2 mb-1.5">
              {job.category && (
                <Badge variant="secondary">{job.category.name}</Badge>
              )}
              <Badge variant={statusColors[job.status] || 'secondary'}>
                {job.status.replace('_', ' ')}
              </Badge>
            </div>
            <h3 className="font-bold text-slate-900 group-hover:text-primary transition-colors line-clamp-1">
              {job.title}
            </h3>
            <p className="text-sm text-muted line-clamp-2 mt-1">{job.description}</p>
            <div className="flex flex-wrap items-center gap-x-4 gap-y-1 mt-2.5 text-xs text-muted">
              <span className="flex items-center gap-1">
                <MapPin className="h-3.5 w-3.5 shrink-0" />
                {job.location}
              </span>
              <span className="flex items-center gap-1">
                <Clock className="h-3.5 w-3.5 shrink-0" />
                Posted {formatDate(job.createdAt)}
              </span>
            </div>
            {job._count && job._count.quotations > 0 && (
              <p className="text-xs text-primary mt-2 font-semibold">
                {job._count.quotations} quote{job._count.quotations > 1 ? 's' : ''} received
              </p>
            )}
          </div>
          <div className="flex flex-col items-end gap-2 shrink-0">
            {job.budget && (
              <span className="flex items-center gap-1 text-sm font-bold text-accent whitespace-nowrap">
                <Banknote className="h-4 w-4" />
                {formatCurrency(Number(job.budget))}
              </span>
            )}
            {href && (
              <ChevronRight className="h-5 w-5 text-slate-300 group-hover:text-primary transition-colors" />
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );

  if (href) return <Link href={href}>{content}</Link>;
  return content;
}

export function JobListingSkeleton() {
  return (
    <div className="space-y-3">
      {[1, 2, 3].map((i) => (
        <div key={i} className="rounded-lg border border-border bg-surface p-4 animate-pulse">
          <div className="flex gap-4">
            <div className="hidden sm:block h-12 w-12 rounded-lg bg-slate-200 shrink-0" />
            <div className="flex-1 space-y-2">
              <div className="h-4 w-24 rounded bg-slate-200" />
              <div className="h-5 w-3/4 rounded bg-slate-200" />
              <div className="h-4 w-full rounded bg-slate-100" />
              <div className="h-3 w-1/2 rounded bg-slate-100" />
            </div>
            <div className="hidden sm:block w-28 space-y-2">
              <div className="h-3 w-16 rounded bg-slate-200 ml-auto" />
              <div className="h-6 w-20 rounded bg-slate-200 ml-auto" />
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}
