import { Check, Clock, Eye, Rocket, SkipForward, X, XCircle } from 'lucide-react';

import { useState } from 'react';

import { router, useForm } from '@inertiajs/react';

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/Components/ui/alert-dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/Components/ui/dropdown-menu';
import { LoadingButton } from '@/Components/ui/loading-button';
import { trackProductEvent } from '@/lib/analytics';

interface BulkActionsBarProps {
  selectedIds: number[];
  siteId: number;
  onClearSelection: () => void;
  onPublishClick?: () => void;
  hasAnyDrafts?: boolean;
}

type BulkActionType = 'approve' | 'reject' | 'reviewed' | 'deferred' | 'applied' | 'pending';

interface DialogState {
  open: boolean;
  action: BulkActionType | null;
}

const ACTION_CONFIG: Record<
  BulkActionType,
  { title: string; description: string; actionText: string; isDangerous: boolean }
> = {
  approve: {
    title: 'Approve recommendations',
    description: `You're about to approve ${0} recommendation(s). This will mark them as approved and ready for implementation.`,
    actionText: 'Approve',
    isDangerous: false,
  },
  reject: {
    title: 'Reject recommendations',
    description: `You're about to reject ${0} recommendation(s). This action cannot be easily undone.`,
    actionText: 'Reject',
    isDangerous: true,
  },
  reviewed: {
    title: 'Mark as reviewed',
    description: `You're about to mark ${0} recommendation(s) as reviewed.`,
    actionText: 'Mark as reviewed',
    isDangerous: false,
  },
  deferred: {
    title: 'Defer recommendations',
    description: `You're about to defer ${0} recommendation(s) for later review.`,
    actionText: 'Defer',
    isDangerous: false,
  },
  applied: {
    title: 'Mark as applied',
    description: `You're about to mark ${0} recommendation(s) as applied.`,
    actionText: 'Mark as applied',
    isDangerous: false,
  },
  pending: {
    title: 'Reset to pending',
    description: `You're about to reset ${0} recommendation(s) back to pending status.`,
    actionText: 'Reset',
    isDangerous: false,
  },
};

export default function BulkActionsBar({
  selectedIds,
  siteId,
  onClearSelection,
  onPublishClick,
  hasAnyDrafts = false,
}: BulkActionsBarProps) {
  const { processing } = useForm();
  const [dialogState, setDialogState] = useState<DialogState>({ open: false, action: null });

  const handleBulkUpdate = (status: string) => {
    // For reject, show confirmation dialog
    if (status === 'rejected') {
      setDialogState({ open: true, action: 'reject' });
    } else {
      executeBulkUpdate(status);
    }
  };

  const executeBulkUpdate = (status: string) => {
    router.patch(
      route('recommendations.bulkUpdateStatus', siteId),
      {
        recommendation_ids: selectedIds,
        lifecycle_status: status,
        status_notes: '',
      },
      {
        onSuccess: () => {
          trackProductEvent('recommendation_status_changed', {
            new_status: status,
            site_id: siteId,
            count: selectedIds.length,
            bulk: true,
          });
          onClearSelection();
          setDialogState({ open: false, action: null });
        },
        preserveScroll: true,
      },
    );
  };

  if (selectedIds.length === 0) {
    return null;
  }

  const dialogConfig = dialogState.action ? ACTION_CONFIG[dialogState.action] : null;

  return (
    <>
      <div role="toolbar" aria-label="Bulk actions" className="sticky bottom-0 z-10 border-t border-border bg-card p-4 shadow-lg">
        <div className="flex items-center justify-between gap-4">
          <div className="flex items-center gap-2">
            <span className="font-medium" aria-live="polite">
              {selectedIds.length} {selectedIds.length === 1 ? 'recommendation' : 'recommendations'}{' '}
              selected
            </span>
            <LoadingButton
              variant="ghost"
              size="sm"
              onClick={onClearSelection}
              loading={processing}
              disabled={processing}
            >
              <XCircle className="h-4 w-4 mr-1" />
              Clear
            </LoadingButton>
          </div>
          <div className="flex items-center gap-2">
            {hasAnyDrafts && onPublishClick && (
              <LoadingButton
                variant="default"
                size="sm"
                onClick={onPublishClick}
                loading={processing}
                disabled={processing}
              >
                <Rocket className="h-4 w-4 mr-1" />
                Publish to WordPress
              </LoadingButton>
            )}
            <LoadingButton
              variant="default"
              size="sm"
              onClick={() => handleBulkUpdate('approved')}
              loading={processing}
              disabled={processing}
            >
              <Check className="h-4 w-4 mr-1" />
              Approve
            </LoadingButton>
            <LoadingButton
              variant="destructive"
              size="sm"
              onClick={() => handleBulkUpdate('rejected')}
              loading={processing}
              disabled={processing}
            >
              <X className="h-4 w-4 mr-1" />
              Reject
            </LoadingButton>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <LoadingButton
                  variant="outline"
                  size="sm"
                  loading={processing}
                  disabled={processing}
                >
                  More actions
                </LoadingButton>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem onClick={() => handleBulkUpdate('reviewed')}>
                  <Eye className="h-4 w-4 mr-2" />
                  Mark as reviewed
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleBulkUpdate('deferred')}>
                  <Clock className="h-4 w-4 mr-2" />
                  Defer
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleBulkUpdate('applied')}>
                  <Rocket className="h-4 w-4 mr-2" />
                  Mark as applied
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => handleBulkUpdate('pending')}>
                  <SkipForward className="h-4 w-4 mr-2" />
                  Reset to pending
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </div>
      </div>

      {dialogConfig && (
        <AlertDialog
          open={dialogState.open}
          onOpenChange={(open) => {
            if (!open) setDialogState({ open: false, action: null });
          }}
        >
          <AlertDialogContent>
            <AlertDialogHeader>
              <AlertDialogTitle>{dialogConfig.title}</AlertDialogTitle>
              <AlertDialogDescription>
                {dialogConfig.description.replace('${0}', selectedIds.length.toString())}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <div className="flex gap-2 justify-end">
              <AlertDialogCancel disabled={processing}>Cancel</AlertDialogCancel>
              <AlertDialogAction
                disabled={processing}
                onClick={() => {
                  if (dialogState.action === 'reject') {
                    executeBulkUpdate('rejected');
                  }
                }}
                className={
                  dialogConfig.isDangerous
                    ? 'bg-red-600 dark:bg-red-700 text-white hover:bg-red-700 dark:hover:bg-red-800'
                    : ''
                }
              >
                {dialogConfig.actionText}
              </AlertDialogAction>
            </div>
          </AlertDialogContent>
        </AlertDialog>
      )}
    </>
  );
}
