import { memo, useState, useCallback } from 'react';
import { CheckCircle, XCircle, Eye, Calendar, MessageSquare, FileText, Image, ListTree, RefreshCw, AlertCircle, Lock, Trash2, AlertTriangle, Edit, Info, ExternalLink, ChevronDown } from 'lucide-react';
import { usePhotoSubmissionItems } from '@/hooks/usePhotoSubmissionItems';
import { PhotoGrid } from '@/components/common/PhotoGrid';
import { normalizePhotoData } from '@/lib/photoHelpers';
import type { PhotoItem } from '@/types/photos';
import { getSubmissionTypeLabel } from '@/lib/moderation/entities';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { UserAvatar } from '@/components/ui/user-avatar';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { format } from 'date-fns';
import { SubmissionItemsList } from './SubmissionItemsList';
import { MeasurementDisplay } from '@/components/ui/measurement-display';
import { ValidationSummary } from './ValidationSummary';
import type { ValidationResult } from '@/lib/entityValidationSchemas';
import type { LockStatus } from '@/lib/moderation/lockHelpers';
import type { ModerationItem } from '@/types/moderation';
import { handleError } from '@/lib/errorHandler';

interface QueueItemProps {
  item: ModerationItem;
  isMobile: boolean;
  actionLoading: string | null;
  isLockedByMe: boolean;
  isLockedByOther: boolean;
  lockStatus: LockStatus;
  currentLockSubmissionId?: string;
  notes: Record<string, string>;
  isAdmin: boolean;
  isSuperuser: boolean;
  queueIsLoading: boolean;
  isInitialRender?: boolean;
  onNoteChange: (id: string, value: string) => void;
  onApprove: (item: ModerationItem, action: 'approved' | 'rejected', notes?: string) => void;
  onResetToPending: (item: ModerationItem) => void;
  onRetryFailed: (item: ModerationItem) => void;
  onOpenPhotos: (photos: any[], index: number) => void;
  onOpenReviewManager: (submissionId: string) => void;
  onOpenItemEditor: (submissionId: string) => void;
  onClaimSubmission: (submissionId: string) => void;
  onDeleteSubmission: (item: ModerationItem) => void;
  onInteractionFocus: (id: string) => void;
  onInteractionBlur: (id: string) => void;
}

const getStatusBadgeVariant = (status: string): "default" | "secondary" | "destructive" | "outline" => {
  switch (status) {
    case 'pending': return 'default';
    case 'approved': return 'secondary';
    case 'rejected': return 'destructive';
    case 'flagged': return 'destructive';
    case 'partially_approved': return 'outline';
    default: return 'outline';
  }
};

export const QueueItem = memo(({
  item,
  isMobile,
  actionLoading,
  isLockedByMe,
  isLockedByOther,
  lockStatus,
  currentLockSubmissionId,
  notes,
  isAdmin,
  isSuperuser,
  queueIsLoading,
  isInitialRender = false,
  onNoteChange,
  onApprove,
  onResetToPending,
  onRetryFailed,
  onOpenPhotos,
  onOpenReviewManager,
  onOpenItemEditor,
  onClaimSubmission,
  onDeleteSubmission,
  onInteractionFocus,
  onInteractionBlur
}: QueueItemProps) => {
  const [validationResult, setValidationResult] = useState<ValidationResult | null>(null);
  const [isClaiming, setIsClaiming] = useState(false);
  
  // Fetch relational photo data for photo submissions
  const { photos: photoItems, loading: photosLoading } = usePhotoSubmissionItems(
    item.submission_type === 'photo' ? item.id : undefined
  );
  
  // Check if submission has any moderator-edited items
  const hasModeratorEdits = item.submission_items?.some(
    si => si.original_data && Object.keys(si.original_data).length > 0
  );
  
  const handleValidationChange = useCallback((result: ValidationResult) => {
    setValidationResult(result);
  }, []);
  
  const handleClaim = useCallback(async () => {
    setIsClaiming(true);
    try {
      await onClaimSubmission(item.id);
      // On success, component will re-render with new lock state
    } catch (error: unknown) {
      handleError(error, {
        action: 'Claim Submission',
        metadata: { submissionId: item.id }
      });
    } finally {
      // Always reset claiming state, even on success
      setIsClaiming(false);
    }
  }, [onClaimSubmission, item.id]);
  
  return (
    <Card 
      key={item.id} 
      className={`border-l-4 transition-all duration-300 ${
        item._removing ? 'opacity-0 scale-95 pointer-events-none' : ''
      } ${
        hasModeratorEdits ? 'ring-2 ring-blue-200 dark:ring-blue-800' : ''
      } ${
        validationResult?.blockingErrors && validationResult.blockingErrors.length > 0 ? 'border-l-red-600' :
        item.status === 'flagged' ? 'border-l-red-500' :
        item.status === 'approved' ? 'border-l-green-500' :
        item.status === 'rejected' ? 'border-l-red-400' :
        item.status === 'partially_approved' ? 'border-l-yellow-500' :
        'border-l-amber-500'
      }`}
      style={{ 
        opacity: actionLoading === item.id ? 0.5 : (item._removing ? 0 : 1),
        pointerEvents: actionLoading === item.id ? 'none' : 'auto',
        transition: isInitialRender ? 'none' : 'all 300ms ease-in-out'
      }}
    >
      <CardHeader className={isMobile ? "pb-3 p-4" : "pb-4"}>
        <div className={`flex gap-3 ${isMobile ? 'flex-col' : 'items-center justify-between'}`}>
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant={getStatusBadgeVariant(item.status)} className={isMobile ? "text-xs" : ""}>
              {item.type === 'review' ? (
                <>
                  <MessageSquare className="w-3 h-3 mr-1" />
                  Review
                </>
              ) : item.submission_type === 'photo' ? (
                <>
                  <Image className="w-3 h-3 mr-1" />
                  Photo
                </>
              ) : (
                <>
                  <FileText className="w-3 h-3 mr-1" />
                  Submission
                </>
              )}
            </Badge>
            <Badge variant={getStatusBadgeVariant(item.status)} className={isMobile ? "text-xs" : ""}>
              {item.status === 'partially_approved' ? 'Partially Approved' : 
               item.status.charAt(0).toUpperCase() + item.status.slice(1)}
            </Badge>
            {hasModeratorEdits && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Badge 
                    variant="secondary" 
                    className="bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-300 border border-blue-300 dark:border-blue-700"
                  >
                    <Edit className="w-3 h-3 mr-1" />
                    Edited
                  </Badge>
                </TooltipTrigger>
                <TooltipContent>
                  <p>This submission has been modified by a moderator</p>
                </TooltipContent>
              </Tooltip>
            )}
            {item.status === 'partially_approved' && (
              <Badge variant="outline" className="bg-yellow-100 dark:bg-yellow-900/30 text-yellow-800 dark:text-yellow-300 border-yellow-300 dark:border-yellow-700">
                <AlertCircle className="w-3 h-3 mr-1" />
                Needs Retry
              </Badge>
            )}
            {isLockedByOther && item.type === 'content_submission' && (
              <Badge variant="outline" className="bg-orange-100 dark:bg-orange-900/30 text-orange-800 dark:text-orange-300 border-orange-300 dark:border-orange-700">
                <Lock className="w-3 h-3 mr-1" />
                Locked by Another Moderator
              </Badge>
            )}
            {currentLockSubmissionId === item.id && item.type === 'content_submission' && (
              <Badge variant="outline" className="bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300 border-blue-300 dark:border-blue-700">
                <Lock className="w-3 h-3 mr-1" />
                Claimed by You
              </Badge>
            )}
            {item.submission_items && item.submission_items.length > 0 && (
              <ValidationSummary
                item={{
                  item_type: item.submission_items[0].item_type,
                  item_data: item.submission_items[0].item_data,
                  id: item.submission_items[0].id,
                }}
                compact={true}
                onValidationChange={handleValidationChange}
              />
            )}
          </div>
          <Tooltip>
            <TooltipTrigger asChild>
              <div className={`flex items-center gap-2 text-muted-foreground ${isMobile ? 'text-xs' : 'text-sm'}`}>
                <Calendar className={isMobile ? "w-3 h-3" : "w-4 h-4"} />
                {format(new Date(item.created_at), isMobile ? 'MMM d, HH:mm:ss' : 'MMM d, yyyy HH:mm:ss.SSS')}
              </div>
            </TooltipTrigger>
            <TooltipContent>
              <p className="text-xs">Full timestamp:</p>
              <p className="font-mono">{item.created_at}</p>
            </TooltipContent>
          </Tooltip>
        </div>
        
        {item.user_profile && (
          <div className={`flex items-center gap-3 ${isMobile ? 'text-xs' : 'text-sm'}`}>
            <UserAvatar
              key={item.user_profile.avatar_url || `user-${item.user_id}`}
              avatarUrl={item.user_profile.avatar_url}
              fallbackText={item.user_profile.display_name || item.user_profile.username || 'U'}
              size={isMobile ? "sm" : "md"}
            />
            <div>
              <span className="font-medium">
                {item.user_profile.display_name || item.user_profile.username}
              </span>
              {item.user_profile.display_name && (
                <span className={`text-muted-foreground block ${isMobile ? 'text-xs' : 'text-xs'}`}>
                  @{item.user_profile.username}
                </span>
              )}
            </div>
          </div>
        )}
      </CardHeader>
      
      <CardContent className={`${isMobile ? 'p-4 pt-0 space-y-4' : 'p-6 pt-0'}`}>
      <div className={`bg-muted/50 rounded-lg ${isMobile ? 'p-3 space-y-3' : 'p-4'} ${
        !isMobile 
          ? item.type === 'content_submission'
            ? 'lg:grid lg:grid-cols-[1fr,320px] lg:gap-6 2xl:grid-cols-[1fr,400px,320px] 2xl:gap-6'
            : 'lg:grid lg:grid-cols-[1fr,320px] lg:gap-6'
          : ''
      }`}>
          {item.type === 'review' ? (
            <div>
              {item.content.title && (
                <h4 className="font-semibold mb-2">{item.content.title}</h4>
              )}
              {item.content.content && (
                <p className="text-sm mb-2">{item.content.content}</p>
              )}
              <div className="flex items-center gap-2 text-sm text-muted-foreground mb-2">
                <span>Rating: {item.content.rating}/5</span>
              </div>
              
              {/* Entity Names for Reviews */}
              {(item.entity_name || item.park_name) && (
                <div className="space-y-1 mb-2">
                  {item.entity_name && (
                    <div className="text-sm text-muted-foreground">
                      <span className="text-xs">{item.park_name ? 'Ride:' : 'Park:'} </span>
                      <span className="text-base font-medium text-foreground">{item.entity_name}</span>
                    </div>
                  )}
                  {item.park_name && (
                    <div className="text-sm text-muted-foreground">
                      <span className="text-xs">Park: </span>
                      <span className="text-base font-medium text-foreground">{item.park_name}</span>
                    </div>
                  )}
                </div>
              )}
               {item.content.photos && item.content.photos.length > 0 && (() => {
                const reviewPhotos: PhotoItem[] = normalizePhotoData({
                  type: 'review',
                  photos: item.content.photos
                });
                
                return (
                  <div className="mt-3">
                    <div className="text-sm font-medium mb-2">Attached Photos:</div>
                    <PhotoGrid 
                      photos={reviewPhotos}
                      onPhotoClick={onOpenPhotos}
                      maxDisplay={isMobile ? 3 : 4}
                      className="grid-cols-2 md:grid-cols-3"
                    />
                    {item.content.photos[0]?.caption && (
                      <p className="text-sm text-muted-foreground mt-2">
                        {item.content.photos[0].caption}
                      </p>
                    )}
                  </div>
                );
              })()}
            </div>
          ) : item.submission_type === 'photo' ? (
            <div>
              <div className="text-sm text-muted-foreground mb-3">
                Photo Submission
              </div>
              
              {/* Submission Title */}
              {item.content.title && (
                <div className="mb-3">
                  <div className="text-sm font-medium mb-1">Title:</div>
                  <p className="text-sm">{item.content.title}</p>
                </div>
              )}
              
              {/* Photos from relational table */}
              {photosLoading ? (
                <div className="text-sm text-muted-foreground">Loading photos...</div>
              ) : photoItems.length > 0 ? (
                <div className="space-y-2">
                  <div className="text-sm font-medium flex items-center justify-between">
                    <span>Photos ({photoItems.length}):</span>
                    {import.meta.env.DEV && photoItems[0] && (
                      <span className="text-xs text-muted-foreground">
                        URL: {photoItems[0].cloudflare_image_url?.slice(0, 30)}...
                      </span>
                    )}
                  </div>
                  <PhotoGrid
                    photos={photoItems.map(photo => ({
                      id: photo.id,
                      url: photo.cloudflare_image_url,
                      filename: photo.filename || `Photo ${photo.order_index + 1}`,
                      caption: photo.caption,
                      title: photo.title,
                      date_taken: photo.date_taken,
                    }))}
                    onPhotoClick={onOpenPhotos}
                  />
                </div>
              ) : (
                <Alert variant="destructive" className="mt-4">
                  <AlertTriangle className="h-4 w-4" />
                  <AlertTitle>No Photos Found</AlertTitle>
                  <AlertDescription>
                    This photo submission has no photos attached. This may be a data integrity issue.
                  </AlertDescription>
                </Alert>
              )}
              
              {/* Context Information */}
              {item.entity_name && (
                <div className="mt-3 pt-3 border-t text-sm">
                  <span className="text-muted-foreground">For: </span>
                  <span className="font-medium">{item.entity_name}</span>
                  {item.park_name && (
                    <>
                      <span className="text-muted-foreground"> at </span>
                      <span className="font-medium">{item.park_name}</span>
                    </>
                  )}
                </div>
              )}
            </div>
          ) : (
            <>
              {/* Main content area - spans 1st column on all layouts */}
              <div>
                <SubmissionItemsList 
                  submissionId={item.id}
                  view="detailed"
                  showImages={true}
                />
              </div>
              
              {/* Middle column for wide screens - shows extended submission details */}
              {!isMobile && item.type === 'content_submission' && (
                <div className="hidden 2xl:block space-y-3">
                  <div className="bg-card rounded-md border p-3">
                    <div className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
                      Review Summary
                    </div>
                    <div className="text-sm space-y-2">
                      <div>
                        <span className="text-muted-foreground">Type:</span>{' '}
                        <span className="font-medium">{getSubmissionTypeLabel(item.submission_type)}</span>
                      </div>
                      {item.submission_items && item.submission_items.length > 0 && (
                        <div>
                          <span className="text-muted-foreground">Items:</span>{' '}
                          <span className="font-medium">{item.submission_items.length}</span>
                        </div>
                      )}
                      {item.status === 'partially_approved' && (
                        <div>
                          <span className="text-muted-foreground">Status:</span>{' '}
                          <span className="font-medium text-yellow-600 dark:text-yellow-400">
                            Partially Approved
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </>
          )}
          
          {/* Right sidebar on desktop: metadata & context */}
          {!isMobile && (item.entity_name || item.park_name || item.user_profile) && (
            <div className="space-y-3">
              {(item.entity_name || item.park_name) && (
                <div className="bg-card rounded-md border p-3 space-y-2">
                  <div className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    Context
                  </div>
                  {item.entity_name && (
                    <div className="text-sm">
                      <span className="text-xs text-muted-foreground block mb-0.5">
                        {item.park_name ? 'Ride' : 'Entity'}
                      </span>
                      <span className="font-medium">{item.entity_name}</span>
                    </div>
                  )}
                  {item.park_name && (
                    <div className="text-sm">
                      <span className="text-xs text-muted-foreground block mb-0.5">Park</span>
                      <span className="font-medium">{item.park_name}</span>
                    </div>
                  )}
                </div>
              )}
              
              {item.user_profile && (
                <div className="bg-card rounded-md border p-3 space-y-2">
                  <div className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
                    Submitter
                  </div>
                  <div className="flex items-center gap-2">
                    <Avatar className="h-8 w-8">
                      <AvatarImage src={item.user_profile.avatar_url} />
                      <AvatarFallback className="text-xs">
                        {(item.user_profile.display_name || item.user_profile.username)?.slice(0, 2).toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <div className="text-sm">
                      <div className="font-medium">
                        {item.user_profile.display_name || item.user_profile.username}
                      </div>
                      {item.user_profile.display_name && (
                        <div className="text-xs text-muted-foreground">
                          @{item.user_profile.username}
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
        
        {/* Action buttons based on status */}
        {(item.status === 'pending' || item.status === 'flagged') && (
          <>
            {/* Claim button for unclaimed submissions */}
            {!isLockedByOther && currentLockSubmissionId !== item.id && (
              <div className="mb-4">
                <Alert className="border-blue-200 bg-blue-50 dark:bg-blue-950/20">
                  <AlertCircle className="h-4 w-4 text-blue-600" />
                  <AlertTitle className="text-blue-900 dark:text-blue-100">Unclaimed Submission</AlertTitle>
                  <AlertDescription className="text-blue-800 dark:text-blue-200">
                    <div className="flex items-center justify-between mt-2">
                      <span className="text-sm">Claim this submission to lock it for 15 minutes while you review</span>
                      <Button
                        onClick={handleClaim}
                        disabled={queueIsLoading || isClaiming}
                        size="sm"
                        className="ml-4"
                      >
                        {isClaiming ? (
                          <>
                            <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                            Claiming...
                          </>
                        ) : (
                          <>
                            <Lock className="w-4 h-4 mr-2" />
                            Claim Submission
                          </>
                        )}
                      </Button>
                    </div>
                  </AlertDescription>
                </Alert>
              </div>
            )}
            
            <div className={isMobile ? 'space-y-4 mt-4' : 'grid grid-cols-1 lg:grid-cols-[1fr,auto] gap-6 items-start mt-4'}>
              {/* Submitter Context - shown before moderator can add their notes */}
              {(item.submission_items?.[0]?.item_data?.source_url || item.submission_items?.[0]?.item_data?.submission_notes) && (
                <div className="space-y-3 mb-4 p-4 bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg lg:col-span-2">
                  <div className="flex items-center gap-2 mb-2">
                    <Info className="w-4 h-4 text-blue-600 dark:text-blue-400" />
                    <h4 className="text-sm font-semibold text-blue-900 dark:text-blue-100">
                      Submitter Context
                    </h4>
                  </div>
                  
                  {item.submission_items?.[0]?.item_data?.source_url && (
                    <div className="text-sm">
                      <span className="font-medium text-blue-900 dark:text-blue-100">Source: </span>
                      <a 
                        href={item.submission_items[0].item_data.source_url} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        className="text-blue-600 hover:underline dark:text-blue-400 inline-flex items-center gap-1"
                      >
                        {item.submission_items[0].item_data.source_url}
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    </div>
                  )}

                  {item.submission_items?.[0]?.item_data?.submission_notes && (
                    <div className="text-sm">
                      <span className="font-medium text-blue-900 dark:text-blue-100">Submitter Notes: </span>
                      <p className="mt-1 whitespace-pre-wrap text-blue-800 dark:text-blue-200">
                        {item.submission_items[0].item_data.submission_notes}
                      </p>
                    </div>
                  )}
                </div>
              )}
              
              {/* Left: Notes textarea */}
              <div className="space-y-2">
                <Label htmlFor={`notes-${item.id}`}>Moderation Notes (optional)</Label>
                <Textarea
                  id={`notes-${item.id}`}
                  placeholder="Add notes about your moderation decision..."
                  value={notes[item.id] || ''}
                  onChange={(e) => onNoteChange(item.id, e.target.value)}
                  onFocus={() => onInteractionFocus(item.id)}
                  onBlur={() => onInteractionBlur(item.id)}
                  rows={isMobile ? 2 : 4}
                  className={!isMobile ? 'min-h-[120px]' : ''}
                  disabled={isLockedByOther || currentLockSubmissionId !== item.id}
                />
              </div>
              
              {/* Right: Action buttons */}
              <div className={isMobile ? 'flex flex-col gap-2' : 'grid grid-cols-2 gap-2 min-w-[400px]'}>

              {/* Show Review Items button for content submissions */}
              {item.type === 'content_submission' && (
                <>
                  <Button
                    onClick={() => onOpenReviewManager(item.id)}
                    disabled={actionLoading === item.id || isLockedByOther || currentLockSubmissionId !== item.id}
                    variant="outline"
                    className={`flex-1 ${isMobile ? 'h-11' : ''}`}
                    size={isMobile ? "default" : "default"}
                  >
                    <ListTree className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
                    Review Items
                  </Button>
                  
                  {isAdmin && isLockedByMe && (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          onClick={() => onOpenItemEditor(item.id)}
                          disabled={actionLoading === item.id}
                          variant="ghost"
                          className={isMobile ? 'h-11' : ''}
                          size={isMobile ? "default" : "default"}
                        >
                          <Edit className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
                          {!isMobile && "Edit"}
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>Quick edit first pending item</p>
                      </TooltipContent>
                    </Tooltip>
                  )}
                </>
              )}
              
              <Button
                onClick={() => onApprove(item, 'approved', notes[item.id])}
                disabled={actionLoading === item.id || isLockedByOther || currentLockSubmissionId !== item.id}
                className={`flex-1 ${isMobile ? 'h-11' : ''}`}
                size={isMobile ? "default" : "default"}
              >
                <CheckCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
                Approve
              </Button>
              <Button
                variant="destructive"
                onClick={() => onApprove(item, 'rejected', notes[item.id])}
                disabled={actionLoading === item.id || isLockedByOther || currentLockSubmissionId !== item.id}
                className={`flex-1 ${isMobile ? 'h-11' : ''}`}
                size={isMobile ? "default" : "default"}
              >
                <XCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
                Reject
              </Button>
              </div>
            </div>
          </>
        )}

        {/* Reset button for rejected items */}
        {item.status === 'rejected' && item.type === 'content_submission' && (
          <div className="space-y-3 pt-4 border-t bg-red-50 dark:bg-red-950/20 -mx-4 px-4 py-3 rounded-b-lg">
            <div className="flex items-start gap-2 text-sm text-red-800 dark:text-red-300">
              <AlertCircle className="w-5 h-5 mt-0.5 flex-shrink-0" />
              <div>
                <p className="font-medium">This submission was rejected</p>
                <p className="text-xs mt-1">You can reset it to pending to re-review and approve it.</p>
              </div>
            </div>
            <Button
              onClick={() => onResetToPending(item)}
              disabled={actionLoading === item.id}
              variant="outline"
              className="w-full"
            >
              <RefreshCw className="w-4 h-4 mr-2" />
              Reset to Pending
            </Button>
          </div>
        )}

        {/* Retry/Reset buttons for partially approved items */}
        {item.status === 'partially_approved' && item.type === 'content_submission' && (
          <div className="space-y-3 pt-4 border-t bg-yellow-50 dark:bg-yellow-950/20 -mx-4 px-4 py-3 rounded-b-lg">
            <div className="flex items-start gap-2 text-sm text-yellow-800 dark:text-yellow-300">
              <AlertCircle className="w-5 h-5 mt-0.5 flex-shrink-0" />
              <div>
                <p className="font-medium">This submission was partially approved</p>
                <p className="text-xs mt-1">Some items failed. You can retry them or reset everything to pending.</p>
              </div>
            </div>
            <div className="flex gap-2">
              <Button
                onClick={() => onOpenReviewManager(item.id)}
                disabled={actionLoading === item.id}
                variant="outline"
                className="flex-1"
              >
                <ListTree className="w-4 h-4 mr-2" />
                Review Items
              </Button>
              <Button
                onClick={() => onResetToPending(item)}
                disabled={actionLoading === item.id}
                variant="outline"
                className="flex-1"
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                Reset All
              </Button>
              <Button
                onClick={() => onRetryFailed(item)}
                disabled={actionLoading === item.id}
                className="flex-1 bg-yellow-600 hover:bg-yellow-700"
              >
                <RefreshCw className="w-4 h-4 mr-2" />
                Retry Failed
              </Button>
            </div>
          </div>
        )}
        
        {/* Reviewer Information for approved/rejected items */}
        {(item.status === 'approved' || item.status === 'rejected') && (item.reviewed_at || item.reviewer_notes || item.submission_items?.[0]?.item_data?.source_url || item.submission_items?.[0]?.item_data?.submission_notes) && (
          <div className="space-y-3 pt-4 border-t">
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Calendar className="w-4 h-4" />
              <span>Reviewed {item.reviewed_at ? format(new Date(item.reviewed_at), 'MMM d, yyyy HH:mm') : 'recently'}</span>
              {item.reviewer_profile && (
                <>
                  <span>by</span>
                  <div className="flex items-center gap-2">
                    <UserAvatar
                      key={item.reviewer_profile.avatar_url || `reviewer-${item.reviewed_by}`}
                      avatarUrl={item.reviewer_profile.avatar_url}
                      fallbackText={item.reviewer_profile.display_name || item.reviewer_profile.username || 'R'}
                      size="sm"
                      className="h-6 w-6"
                    />
                    <span className="font-medium">
                      {item.reviewer_profile.display_name || item.reviewer_profile.username}
                    </span>
                  </div>
                </>
              )}
            </div>
            
            {/* Submitter Context (shown in collapsed state after review) */}
            {(item.submission_items?.[0]?.item_data?.source_url || item.submission_items?.[0]?.item_data?.submission_notes) && (
              <Collapsible>
                <CollapsibleTrigger className="flex items-center gap-2 text-sm font-medium hover:underline">
                  <ChevronDown className="w-4 h-4" />
                  View Submitter Context
                </CollapsibleTrigger>
                <CollapsibleContent className="mt-2 bg-muted/30 p-3 rounded-lg">
                  {item.submission_items?.[0]?.item_data?.source_url && (
                    <div className="text-sm mb-2">
                      <span className="font-medium">Source: </span>
                      <a 
                        href={item.submission_items[0].item_data.source_url} 
                        target="_blank" 
                        rel="noopener noreferrer"
                        className="text-blue-600 hover:underline inline-flex items-center gap-1"
                      >
                        {item.submission_items[0].item_data.source_url}
                        <ExternalLink className="w-3 h-3" />
                      </a>
                    </div>
                  )}
                  {item.submission_items?.[0]?.item_data?.submission_notes && (
                    <div className="text-sm">
                      <span className="font-medium">Submitter Notes: </span>
                      <p className="mt-1 whitespace-pre-wrap text-muted-foreground">
                        {item.submission_items[0].item_data.submission_notes}
                      </p>
                    </div>
                  )}
                </CollapsibleContent>
              </Collapsible>
            )}
            
            {item.reviewer_notes && (
              <div className="bg-muted/30 p-3 rounded-lg">
                <p className="text-sm font-medium mb-1">Moderator Notes:</p>
                <p className="text-sm text-muted-foreground">{item.reviewer_notes}</p>
              </div>
            )}
            
            {/* Reverse Decision Buttons */}
            <div className="space-y-2">
              <Label className="text-sm">Reverse Decision</Label>
              <Textarea
                placeholder="Add notes about reversing this decision..."
                value={notes[`reverse-${item.id}`] || ''}
                onChange={(e) => onNoteChange(`reverse-${item.id}`, e.target.value)}
                onFocus={() => onInteractionFocus(item.id)}
                onBlur={() => onInteractionBlur(item.id)}
                rows={2}
              />
              <div className={`flex gap-2 ${isMobile ? 'flex-col' : ''}`}>
                {item.status === 'approved' && (
                  <Button
                    variant="destructive"
                    onClick={() => onApprove(item, 'rejected', notes[`reverse-${item.id}`])}
                    disabled={actionLoading === item.id}
                    className={`flex-1 ${isMobile ? 'h-11' : ''}`}
                    size={isMobile ? "default" : "default"}
                  >
                    <XCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
                    Change to Rejected
                  </Button>
                )}
                {item.status === 'rejected' && (
                  <Button
                    onClick={() => onApprove(item, 'approved', notes[`reverse-${item.id}`])}
                    disabled={actionLoading === item.id}
                    className={`flex-1 ${isMobile ? 'h-11' : ''}`}
                    size={isMobile ? "default" : "default"}
                  >
                    <CheckCircle className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
                    Change to Approved
                  </Button>
                )}
              </div>
            </div>
          </div>
        )}
        
        {/* Delete button for rejected submissions (admin/superadmin only) */}
        {item.status === 'rejected' && item.type === 'content_submission' && (isAdmin || isSuperuser) && (
          <div className="pt-2">
            <Button
              variant="destructive"
              onClick={() => onDeleteSubmission(item)}
              disabled={actionLoading === item.id}
              className={`w-full ${isMobile ? 'h-11' : ''}`}
              size={isMobile ? "default" : "default"}
            >
              <Trash2 className={isMobile ? "w-5 h-5 mr-2" : "w-4 h-4 mr-2"} />
              Delete Submission
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  );
}, (prevProps, nextProps) => {
  // Quick checks first (cheapest)
  if (prevProps.item.id !== nextProps.item.id) return false;
  if (prevProps.item.status !== nextProps.item.status) return false;
  if (prevProps.actionLoading !== nextProps.actionLoading) return false;
  if (prevProps.currentLockSubmissionId !== nextProps.currentLockSubmissionId) return false;
  if (prevProps.notes[prevProps.item.id] !== nextProps.notes[nextProps.item.id]) return false;
  if (prevProps.notes[`reverse-${prevProps.item.id}`] !== nextProps.notes[`reverse-${nextProps.item.id}`]) return false;
  
  // Check lock status
  if (prevProps.isLockedByOther !== nextProps.isLockedByOther) return false;
  if (prevProps.lockStatus !== nextProps.lockStatus) return false;
  
  // Deep comparison of critical fields (use strict equality for reference stability)
  if (prevProps.item.status !== nextProps.item.status) return false;
  if (prevProps.item.reviewed_at !== nextProps.item.reviewed_at) return false;
  if (prevProps.item.reviewer_notes !== nextProps.item.reviewer_notes) return false;
  if (prevProps.item.assigned_to !== nextProps.item.assigned_to) return false;
  if (prevProps.item.locked_until !== nextProps.item.locked_until) return false;
  if (prevProps.item.escalated !== nextProps.item.escalated) return false;
  
  // Only check content reference, not deep equality (performance)
  if (prevProps.item.content !== nextProps.item.content) return false;
  
  // All checks passed - items are identical
  return true;
});

QueueItem.displayName = 'QueueItem';
