import { memo, useCallback, useState } from 'react';
import { useDebouncedCallback } from 'use-debounce';
import { 
  AlertCircle, Edit, Info, ExternalLink, ChevronDown, ListTree, Calendar, Crown, Unlock 
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ActionButton } from '@/components/ui/action-button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
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 { UserAvatar } from '@/components/ui/user-avatar';
import { format } from 'date-fns';
import type { ModerationItem } from '@/types/moderation';
import { sanitizeURL, sanitizePlainText } from '@/lib/sanitize';
import { getErrorMessage } from '@/lib/errorHandler';

interface QueueItemActionsProps {
  item: ModerationItem;
  isMobile: boolean;
  actionLoading: string | null;
  isLockedByMe: boolean;
  isLockedByOther: boolean;
  currentLockSubmissionId?: string;
  notes: Record<string, string>;
  isAdmin: boolean;
  isSuperuser: boolean;
  queueIsLoading: boolean;
  isClaiming: boolean;
  onNoteChange: (id: string, value: string) => void;
  onApprove: (item: ModerationItem, action: 'approved' | 'rejected', notes?: string) => void;
  onResetToPending: (item: ModerationItem) => void;
  onRetryFailed: (item: ModerationItem) => void;
  onOpenReviewManager: (submissionId: string) => void;
  onOpenItemEditor: (submissionId: string) => void;
  onDeleteSubmission: (item: ModerationItem) => void;
  onInteractionFocus: (id: string) => void;
  onInteractionBlur: (id: string) => void;
  onClaim: () => void;
  onSuperuserReleaseLock?: (submissionId: string) => Promise<void>;
}

export const QueueItemActions = memo(({
  item,
  isMobile,
  actionLoading,
  isLockedByMe,
  isLockedByOther,
  currentLockSubmissionId,
  notes,
  isAdmin,
  isSuperuser,
  queueIsLoading,
  isClaiming,
  onNoteChange,
  onApprove,
  onResetToPending,
  onRetryFailed,
  onOpenReviewManager,
  onOpenItemEditor,
  onDeleteSubmission,
  onInteractionFocus,
  onInteractionBlur,
  onClaim,
  onSuperuserReleaseLock
}: QueueItemActionsProps) => {
  // Error state for retry functionality
  const [actionError, setActionError] = useState<{
    message: string;
    errorId?: string;
    action: 'approve' | 'reject';
  } | null>(null);

  // Memoize all handlers to prevent re-renders
  const handleNoteChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    onNoteChange(item.id, e.target.value);
  }, [onNoteChange, item.id]);

  // Debounced handlers with error tracking
  const handleApprove = useDebouncedCallback(
    async () => {
      if (actionLoading === item.id) return;
      try {
        setActionError(null);
        await onApprove(item, 'approved', notes[item.id]);
      } catch (error: any) {
        setActionError({
          message: getErrorMessage(error),
          errorId: error.errorId,
          action: 'approve',
        });
      }
    },
    300,
    { leading: true, trailing: false }
  );

  const handleReject = useDebouncedCallback(
    async () => {
      if (actionLoading === item.id) return;
      try {
        setActionError(null);
        await onApprove(item, 'rejected', notes[item.id]);
      } catch (error: any) {
        setActionError({
          message: getErrorMessage(error),
          errorId: error.errorId,
          action: 'reject',
        });
      }
    },
    300,
    { leading: true, trailing: false }
  );

  const handleResetToPending = useCallback(() => {
    onResetToPending(item);
  }, [onResetToPending, item]);

  const handleRetryFailed = useCallback(() => {
    onRetryFailed(item);
  }, [onRetryFailed, item]);

  const handleOpenReviewManager = useCallback(() => {
    onOpenReviewManager(item.id);
  }, [onOpenReviewManager, item.id]);

  const handleOpenItemEditor = useCallback(() => {
    onOpenItemEditor(item.id);
  }, [onOpenItemEditor, item.id]);

  const handleDeleteSubmission = useCallback(() => {
    onDeleteSubmission(item);
  }, [onDeleteSubmission, item]);

  const handleFocus = useCallback(() => {
    onInteractionFocus(item.id);
  }, [onInteractionFocus, item.id]);

  const handleBlur = useCallback(() => {
    onInteractionBlur(item.id);
  }, [onInteractionBlur, item.id]);

  const handleReverseNoteChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
    onNoteChange(`reverse-${item.id}`, e.target.value);
  }, [onNoteChange, item.id]);

  const handleReverseApprove = useDebouncedCallback(
    () => {
      if (actionLoading === item.id) {
        return;
      }
      onApprove(item, 'approved', notes[`reverse-${item.id}`]);
    },
    300,
    { leading: true, trailing: false }
  );

  const handleReverseReject = useDebouncedCallback(
    () => {
      if (actionLoading === item.id) {
        return;
      }
      onApprove(item, 'rejected', notes[`reverse-${item.id}`]);
    },
    300,
    { leading: true, trailing: false }
  );

  return (
    <>
      {/* Error Display with Retry */}
      {actionError && (
        <Alert variant="destructive" className="mb-4">
          <AlertCircle className="h-4 w-4" />
          <AlertTitle>Action Failed: {actionError.action}</AlertTitle>
          <AlertDescription>
            <div className="space-y-2">
              <p className="text-sm">{actionError.message}</p>
              {actionError.errorId && (
                <p className="text-xs font-mono bg-destructive/10 px-2 py-1 rounded">
                  Reference ID: {actionError.errorId.slice(0, 8)}
                </p>
              )}
              <div className="flex gap-2 mt-3">
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => {
                    setActionError(null);
                    if (actionError.action === 'approve') handleApprove();
                    else if (actionError.action === 'reject') handleReject();
                  }}
                >
                  Retry {actionError.action}
                </Button>
                <Button size="sm" variant="ghost" onClick={() => setActionError(null)}>
                  Dismiss
                </Button>
              </div>
            </div>
          </AlertDescription>
        </Alert>
      )}

      {/* 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>
                    <ActionButton
                      action="claim"
                      onClick={onClaim}
                      disabled={queueIsLoading || isClaiming}
                      isLoading={isClaiming}
                      size="sm"
                      className="ml-4"
                    />
                  </div>
                </AlertDescription>
              </Alert>
            </div>
          )}

          {/* Superuser Lock Override - Show for locked items */}
          {isSuperuser && isLockedByOther && onSuperuserReleaseLock && (
            <Alert className="border-purple-500/50 bg-purple-500/10">
              <Crown className="h-4 w-4 text-purple-600" />
              <AlertTitle className="text-purple-900 dark:text-purple-100">
                Superuser Override
              </AlertTitle>
              <AlertDescription className="text-purple-800 dark:text-purple-200">
                <div className="flex flex-col gap-2 mt-2">
                  <p className="text-sm">
                    This submission is locked by another moderator. 
                    You can force-release this lock.
                  </p>
                  <Button
                    size="sm"
                    variant="outline"
                    className="border-purple-500 text-purple-700 hover:bg-purple-50 dark:hover:bg-purple-950"
                    onClick={() => onSuperuserReleaseLock(item.id)}
                    disabled={actionLoading === item.id}
                  >
                    <Unlock className="w-4 h-4 mr-2" />
                    Force Release Lock
                  </Button>
                </div>
              </AlertDescription>
            </Alert>
          )}
          
          <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={sanitizeURL(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"
                    >
                      {sanitizePlainText(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">
                      {sanitizePlainText(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={handleNoteChange}
                onFocus={handleFocus}
                onBlur={handleBlur}
                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={handleOpenReviewManager}
                    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>
                  
                  {isLockedByMe && (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          onClick={handleOpenItemEditor}
                          disabled={actionLoading === item.id}
                          variant="outline"
                          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>Edit submission items (Press E)</p>
                      </TooltipContent>
                    </Tooltip>
                  )}
                </>
              )}
              
              <ActionButton
                action="approve"
                onClick={handleApprove}
                disabled={actionLoading === item.id || isLockedByOther || currentLockSubmissionId !== item.id}
                isLoading={actionLoading === item.id}
                loadingText={
                  item.submission_items && item.submission_items.length > 5
                    ? `Processing ${item.submission_items.length} items...`
                    : 'Processing...'
                }
                className="flex-1"
                size={isMobile ? "default" : "default"}
                isMobile={isMobile}
              />
              <ActionButton
                action="reject"
                onClick={handleReject}
                disabled={actionLoading === item.id || isLockedByOther || currentLockSubmissionId !== item.id}
                isLoading={actionLoading === item.id}
                className="flex-1"
                size={isMobile ? "default" : "default"}
                isMobile={isMobile}
              />
            </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>
          <ActionButton
            action="reset"
            onClick={handleResetToPending}
            disabled={actionLoading === item.id}
            isLoading={actionLoading === item.id}
            className="w-full"
          />
        </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={handleOpenReviewManager}
              disabled={actionLoading === item.id}
              variant="outline"
              className="flex-1"
            >
              <ListTree className="w-4 h-4 mr-2" />
              Review Items
            </Button>
            <ActionButton
              action="reset"
              onClick={handleResetToPending}
              disabled={actionLoading === item.id}
              isLoading={actionLoading === item.id}
              className="flex-1"
            >
              Reset All
            </ActionButton>
            <ActionButton
              action="retry"
              onClick={handleRetryFailed}
              disabled={actionLoading === item.id}
              isLoading={actionLoading === item.id}
              className="flex-1"
            />
          </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={sanitizeURL(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"
                    >
                      {sanitizePlainText(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">
                      {sanitizePlainText(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={handleReverseNoteChange}
              onFocus={handleFocus}
              onBlur={handleBlur}
              rows={2}
            />
            <div className={`flex gap-2 ${isMobile ? 'flex-col' : ''}`}>
              {item.status === 'approved' && (
                <ActionButton
                  action="reject"
                  onClick={handleReverseReject}
                  disabled={actionLoading === item.id}
                  isLoading={actionLoading === item.id}
                  className="flex-1"
                  size={isMobile ? "default" : "default"}
                  isMobile={isMobile}
                >
                  Change to Rejected
                </ActionButton>
              )}
              {item.status === 'rejected' && (
                <ActionButton
                  action="approve"
                  onClick={handleReverseApprove}
                  disabled={actionLoading === item.id}
                  isLoading={actionLoading === item.id}
                  className="flex-1"
                  size={isMobile ? "default" : "default"}
                  isMobile={isMobile}
                >
                  Change to Approved
                </ActionButton>
              )}
            </div>
          </div>
        </div>
      )}
      
      {/* Delete button for rejected submissions (admin/superadmin only) */}
      {item.status === 'rejected' && item.type === 'content_submission' && (isAdmin || isSuperuser) && (
        <div className="pt-2">
          <ActionButton
            action="delete"
            onClick={handleDeleteSubmission}
            disabled={actionLoading === item.id}
            isLoading={actionLoading === item.id}
            className="w-full"
            size={isMobile ? "default" : "default"}
            isMobile={isMobile}
          >
            Delete Submission
          </ActionButton>
        </div>
      )}
    </>
  );
});

QueueItemActions.displayName = 'QueueItemActions';
