import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { LoaderCircle, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import {
  fetchAutomationServiceMonitorState,
  getInitialAutomationServiceMonitorState,
  restartAutomationServiceFromDevServer,
  type AutomationServiceMonitorState,
} from '@/services/automationControlService';

const AUTOMATION_SERVICE_STATUS_QUERY_KEY = ['automation', 'service', 'monitor'] as const;
const DEFAULT_STATUS_POLL_MS = 5000;
const FAST_STATUS_POLL_MS = 1500;

const AUTOMATION_STATUS_META: Record<AutomationServiceMonitorState['status'], {
  label: string;
  badgeClassName: string;
  dotClassName: string;
  busy: boolean;
}> = {
  checking: {
    label: '检测中',
    badgeClassName: 'border-slate-200 bg-slate-50/90 text-slate-600',
    dotClassName: 'bg-slate-400',
    busy: true,
  },
  online: {
    label: '自动化服务在线',
    badgeClassName: 'border-emerald-200 bg-emerald-50/90 text-emerald-700',
    dotClassName: 'bg-emerald-500',
    busy: false,
  },
  offline: {
    label: '自动化服务离线',
    badgeClassName: 'border-rose-200 bg-rose-50/90 text-rose-700',
    dotClassName: 'bg-rose-500',
    busy: false,
  },
  starting: {
    label: '处理中',
    badgeClassName: 'border-amber-200 bg-amber-50/90 text-amber-700',
    dotClassName: 'bg-amber-500',
    busy: true,
  },
  'restart-sent': {
    label: '重启中',
    badgeClassName: 'border-amber-200 bg-amber-50/90 text-amber-700',
    dotClassName: 'bg-amber-500',
    busy: true,
  },
  unmanaged: {
    label: '不可管理',
    badgeClassName: 'border-orange-200 bg-orange-50/90 text-orange-700',
    dotClassName: 'bg-orange-500',
    busy: false,
  },
  unsupported: {
    label: '仅监测',
    badgeClassName: 'border-slate-200 bg-slate-50/90 text-slate-600',
    dotClassName: 'bg-slate-400',
    busy: false,
  },
};

export function AutomationServiceIndicator() {
  const queryClient = useQueryClient();
  const [restartRequestPending, setRestartRequestPending] = useState(false);
  const [restartConfirmOpen, setRestartConfirmOpen] = useState(false);

  const { data: automationState = getInitialAutomationServiceMonitorState() } = useQuery({
    queryKey: AUTOMATION_SERVICE_STATUS_QUERY_KEY,
    queryFn: fetchAutomationServiceMonitorState,
    retry: false,
    refetchInterval: (query) => {
      const current = (query.state.data as AutomationServiceMonitorState | undefined) ?? getInitialAutomationServiceMonitorState();
      return current.status === 'checking' || current.status === 'starting' || current.status === 'restart-sent'
        ? FAST_STATUS_POLL_MS
        : DEFAULT_STATUS_POLL_MS;
    },
    refetchIntervalInBackground: true,
  });

  const automationMeta = AUTOMATION_STATUS_META[automationState.status];
  const canShowRestartButton = automationState.canStart;
  const isRestartButtonDisabled = restartRequestPending || automationState.status === 'starting' || automationState.status === 'restart-sent';

  async function handleRestartAutomationService() {
    if (isRestartButtonDisabled || !automationState.canStart) {
      return;
    }

    setRestartRequestPending(true);
    queryClient.setQueryData<AutomationServiceMonitorState>(AUTOMATION_SERVICE_STATUS_QUERY_KEY, {
      ...automationState,
      status: 'starting',
      message: '正在尝试重启自动化服务',
      checkedAt: new Date().toISOString(),
    });

    try {
      const nextState = await restartAutomationServiceFromDevServer();
      queryClient.setQueryData(AUTOMATION_SERVICE_STATUS_QUERY_KEY, nextState);
      toast.success(nextState.message || '已发送自动化服务重启请求');
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      toast.error(`重启自动化服务失败：${message}`);
    } finally {
      setRestartRequestPending(false);
      void queryClient.invalidateQueries({ queryKey: AUTOMATION_SERVICE_STATUS_QUERY_KEY });
    }
  }

  return (
    <div className="flex items-center gap-2">
      <div
        title={automationState.message}
        className={cn(
          'inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium leading-none shadow-sm',
          automationMeta.badgeClassName,
        )}
      >
        {automationMeta.busy ? (
          <LoaderCircle className="h-3.5 w-3.5 animate-spin" />
        ) : (
          <span className={cn('h-2.5 w-2.5 rounded-full', automationMeta.dotClassName)} />
        )}
        <span>{automationMeta.label}</span>
      </div>

      {canShowRestartButton ? (
        <Button
          type="button"
          variant="outline"
          size="sm"
          title="重启本地自动化服务，会中断当前后端任务"
          disabled={isRestartButtonDisabled}
          onClick={() => {
            setRestartConfirmOpen(true);
          }}
          className="h-8 rounded-full border-blue-200 px-3 text-xs font-semibold text-blue-700 hover:bg-blue-50 hover:text-blue-800"
        >
          {isRestartButtonDisabled ? <LoaderCircle className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
          {isRestartButtonDisabled ? '重启中' : '重启服务'}
        </Button>
      ) : null}

      <AlertDialog open={restartConfirmOpen} onOpenChange={setRestartConfirmOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认重启自动化服务</AlertDialogTitle>
            <AlertDialogDescription>
              这会重启当前本地自动化后端，并中断正在执行的标准化、搜索或询价任务。确认继续吗？
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={restartRequestPending}>取消</AlertDialogCancel>
            <AlertDialogAction
              disabled={restartRequestPending}
              onClick={() => {
                setRestartConfirmOpen(false);
                void handleRestartAutomationService();
              }}
            >
              确认重启
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
