/**
 * PendingApprovals Component
 *
 * Displays pending approval requests that need user attention.
 * Only renders when there are approvals to show.
 *
 * @see Issue #53
 */

'use client';

import { formatDistanceToNow } from 'date-fns';
import {
  AlertCircle,
  CheckCircle2,
  XCircle,
  GitBranch,
  Code2,
  Building2,
  Rocket,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Link } from '@/lib/i18n/routing';
import { cn } from '@/lib/utils';
import type { PendingApproval } from '@/lib/api/hooks/useDashboard';

export interface PendingApprovalsProps {
  /** Pending approvals to display */
  approvals?: PendingApproval[];
  /** Whether data is loading */
  isLoading?: boolean;
  /** Callback when approval is approved */
  onApprove?: (approval: PendingApproval) => void;
  /** Callback when approval is rejected */
  onReject?: (approval: PendingApproval) => void;
  /** Additional CSS classes */
  className?: string;
}

const typeConfig: Record<
  PendingApproval['type'],
  { icon: typeof GitBranch; label: string; color: string }
> = {
  sprint_boundary: {
    icon: GitBranch,
    label: 'Sprint Boundary',
    color: 'text-blue-500',
  },
  code_review: {
    icon: Code2,
    label: 'Code Review',
    color: 'text-purple-500',
  },
  architecture_decision: {
    icon: Building2,
    label: 'Architecture',
    color: 'text-orange-500',
  },
  deployment: {
    icon: Rocket,
    label: 'Deployment',
    color: 'text-green-500',
  },
};

const priorityConfig: Record<
  PendingApproval['priority'],
  { label: string; variant: 'default' | 'secondary' | 'destructive' | 'outline' }
> = {
  low: { label: 'Low', variant: 'outline' },
  medium: { label: 'Medium', variant: 'secondary' },
  high: { label: 'High', variant: 'default' },
  critical: { label: 'Critical', variant: 'destructive' },
};

function ApprovalSkeleton() {
  return (
    <div className="flex items-start gap-4 rounded-lg border p-4">
      <Skeleton className="h-10 w-10 rounded-full" />
      <div className="flex-1 space-y-2">
        <Skeleton className="h-5 w-3/4" />
        <Skeleton className="h-4 w-full" />
        <Skeleton className="h-4 w-1/2" />
      </div>
      <div className="flex gap-2">
        <Skeleton className="h-9 w-20" />
        <Skeleton className="h-9 w-20" />
      </div>
    </div>
  );
}

interface ApprovalItemProps {
  approval: PendingApproval;
  onApprove?: () => void;
  onReject?: () => void;
}

function ApprovalItem({ approval, onApprove, onReject }: ApprovalItemProps) {
  const config = typeConfig[approval.type];
  const Icon = config.icon;
  const priority = priorityConfig[approval.priority];

  const timeAgo = formatDistanceToNow(new Date(approval.requestedAt), { addSuffix: true });

  return (
    <div className="flex flex-col gap-4 rounded-lg border p-4 sm:flex-row sm:items-start">
      <div
        className={cn(
          'flex h-10 w-10 items-center justify-center rounded-full bg-muted',
          config.color
        )}
      >
        <Icon className="h-5 w-5" />
      </div>

      <div className="flex-1 space-y-1">
        <div className="flex flex-wrap items-center gap-2">
          <h4 className="font-medium">{approval.title}</h4>
          <Badge variant={priority.variant} className="text-xs">
            {priority.label}
          </Badge>
        </div>
        <p className="text-sm text-muted-foreground">{approval.description}</p>
        <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
          <Link
            href={`/projects/${approval.projectId}`}
            className="hover:text-primary hover:underline"
          >
            {approval.projectName}
          </Link>
          <span>-</span>
          <span>Requested by {approval.requestedBy}</span>
          <span>-</span>
          <span>{timeAgo}</span>
        </div>
      </div>

      <div className="flex gap-2">
        <Button
          size="sm"
          variant="outline"
          className="text-destructive hover:bg-destructive hover:text-destructive-foreground"
          onClick={onReject}
        >
          <XCircle className="mr-1 h-4 w-4" />
          Reject
        </Button>
        <Button size="sm" onClick={onApprove}>
          <CheckCircle2 className="mr-1 h-4 w-4" />
          Approve
        </Button>
      </div>
    </div>
  );
}

export function PendingApprovals({
  approvals,
  isLoading = false,
  onApprove,
  onReject,
  className,
}: PendingApprovalsProps) {
  // Don't render if no approvals and not loading
  if (!isLoading && (!approvals || approvals.length === 0)) {
    return null;
  }

  return (
    <Card className={className}>
      <CardHeader className="pb-3">
        <div className="flex items-center gap-2">
          <AlertCircle className="h-5 w-5 text-amber-500" />
          <CardTitle className="text-lg">Pending Approvals</CardTitle>
          {approvals && approvals.length > 0 && (
            <Badge variant="secondary">{approvals.length}</Badge>
          )}
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        {isLoading ? (
          <>
            <ApprovalSkeleton />
            <ApprovalSkeleton />
          </>
        ) : (
          approvals?.map((approval) => (
            <ApprovalItem
              key={approval.id}
              approval={approval}
              onApprove={() => onApprove?.(approval)}
              onReject={() => onReject?.(approval)}
            />
          ))
        )}
      </CardContent>
    </Card>
  );
}
