import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Clock3, ExternalLink, ListOrdered, LoaderCircle, Square, TriangleAlert } from 'lucide-react';
import { Link } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { useStandardizationQueue, formatStandardizationTaskSummary } from '@/contexts/StandardizationQueueContext';
import { stopStandardizeTask } from '@/services/automationService';

const STANDARDIZATION_MONITOR_QUERY_KEY = ['standardization', 'monitor', 'tasks'] as const;

export function StandardizationStatusBar() {
  const queryClient = useQueryClient();
  const {
    queueItems,
    onlineRunningTask,
    offlineProcessingTasks,
    retryQueueItem,
    removeQueueItem,
  } = useStandardizationQueue();
  const [stoppingTaskId, setStoppingTaskId] = useState<string | null>(null);

  const queuedItems = queueItems.filter((item) => item.status === 'queued' || item.status === 'submitting');
  const failedItems = queueItems.filter((item) => item.status === 'failed');
  const nextQueuedItem = queuedItems[0] ?? null;
  const firstFailedItem = failedItems[0] ?? null;

  if (!onlineRunningTask && queuedItems.length === 0 && offlineProcessingTasks.length === 0 && failedItems.length === 0) {
    return null;
  }

  async function handleStopOnlineTask() {
    if (!onlineRunningTask) {
      return;
    }

    setStoppingTaskId(onlineRunningTask.id);
    try {
      const response = await stopStandardizeTask(onlineRunningTask.id);
      toast.success(response.message || `已发送停止指令：${onlineRunningTask.batch_id}`, {
        duration: 3500,
        position: 'bottom-right',
      });
      await queryClient.invalidateQueries({ queryKey: STANDARDIZATION_MONITOR_QUERY_KEY });
    } catch (error) {
      toast.error(`停止在线标准化失败：${error instanceof Error ? error.message : String(error)}`, {
        duration: 5000,
        position: 'bottom-right',
      });
    } finally {
      setStoppingTaskId(null);
    }
  }

  return (
    <div className="shrink-0 px-6 pb-1">
      <div className="rounded-[22px] border border-slate-200 bg-white/95 px-4 py-3 shadow-sm backdrop-blur">
        <div className="flex flex-wrap items-center gap-2">
          <Badge className="gap-1 bg-blue-600 text-white hover:bg-blue-600">
            <LoaderCircle className="h-3.5 w-3.5" />
            在线执行 {onlineRunningTask ? 1 : 0}
          </Badge>
          <Badge variant="secondary" className="gap-1">
            <ListOrdered className="h-3.5 w-3.5" />
            在线排队 {queuedItems.length}
          </Badge>
          <Badge variant="outline">离线运行 {offlineProcessingTasks.length}</Badge>
          {failedItems.length > 0 ? <Badge variant="destructive">排队失败 {failedItems.length}</Badge> : null}
          {onlineRunningTask ? (
            <Button
              size="sm"
              variant="outline"
              onClick={() => { void handleStopOnlineTask(); }}
              disabled={onlineRunningTask.status === 'stopping' || stoppingTaskId === onlineRunningTask.id}
            >
              <Square className="h-3.5 w-3.5" />
              {onlineRunningTask.status === 'stopping' || stoppingTaskId === onlineRunningTask.id ? '停止中' : '停止在线任务'}
            </Button>
          ) : null}
          <Button asChild size="sm" variant="outline" className="ml-auto">
            <Link to="/standardized?tab=tasks">
              查看任务
              <ExternalLink className="h-3.5 w-3.5" />
            </Link>
          </Button>
        </div>

        <div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted-foreground">
          {onlineRunningTask ? <span>在线执行中：{formatStandardizationTaskSummary(onlineRunningTask)}</span> : null}
          {nextQueuedItem ? (
            <span className="inline-flex items-center gap-2">
              <span>下一个在线任务：{nextQueuedItem.batchId} · {nextQueuedItem.totalRows} 条</span>
              <Button
                size="sm"
                variant="ghost"
                className="h-6 px-2 text-xs text-muted-foreground"
                onClick={() => removeQueueItem(nextQueuedItem.id)}
              >
                取消排队
              </Button>
            </span>
          ) : null}
          {offlineProcessingTasks[0] ? <span>离线执行中：{formatStandardizationTaskSummary(offlineProcessingTasks[0])}</span> : null}
        </div>

        {firstFailedItem ? (
          <div className="mt-3 flex flex-wrap items-center gap-2 rounded-2xl border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900">
            <TriangleAlert className="h-3.5 w-3.5" />
            <span>在线队列提交失败：{firstFailedItem.batchId} · {firstFailedItem.errorMessage || '请重试'}</span>
            <div className="ml-auto flex items-center gap-1.5">
              <Button size="sm" variant="outline" onClick={() => retryQueueItem(firstFailedItem.id)}>
                <Clock3 className="h-3.5 w-3.5" />
                重试
              </Button>
              <Button size="sm" variant="ghost" onClick={() => removeQueueItem(firstFailedItem.id)}>
                移除
              </Button>
            </div>
          </div>
        ) : null}
      </div>
    </div>
  );
}