import { useState } from 'react';
import { AlertTriangle, Bell, ExternalLink, LoaderCircle, Monitor } from 'lucide-react';

import { useSearchManualIntervention } from '@/contexts/SearchManualInterventionContext';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';

function formatDateTime(value: string) {
  if (!value) {
    return '-';
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return value;
  }

  return date.toLocaleString('zh-CN', { hour12: false });
}

export function SearchManualInterventionBell() {
  const [open, setOpen] = useState(false);
  const {
    alerts,
    activeCount,
    openAlert,
    openingTaskId,
    previewSelectedSound,
    selectedSoundId,
    setSelectedSoundId,
    soundOptions,
  } = useSearchManualIntervention();

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="relative flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-600 transition-colors hover:bg-slate-50"
        aria-label="打开验证码提醒"
      >
        <Bell className="h-4 w-4" />
        {activeCount > 0 ? (
          <span className="absolute -right-1 -top-1 inline-flex min-h-5 min-w-5 items-center justify-center rounded-full bg-rose-500 px-1 text-[10px] font-semibold text-white">
            {activeCount > 9 ? '9+' : activeCount}
          </span>
        ) : null}
      </button>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="sm:max-w-2xl">
          <div className="flex flex-col gap-4 pr-10 sm:flex-row sm:items-start sm:justify-between">
            <DialogHeader className="space-y-0 text-left">
              <DialogTitle>消息提醒</DialogTitle>
            </DialogHeader>

            <div className="flex w-full flex-col gap-2 sm:w-[460px] sm:flex-none">

              <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
                <Select value={selectedSoundId} onValueChange={setSelectedSoundId}>
                  <SelectTrigger className="h-10 flex-1 bg-white text-sm">
                    <SelectValue placeholder="请选择提醒铃声" />
                  </SelectTrigger>
                  <SelectContent>
                    {soundOptions.map((sound) => (
                      <SelectItem key={sound.id} value={sound.id}>
                        {sound.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>

                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  className="h-10 border-slate-300 bg-white px-4"
                  onClick={() => { void previewSelectedSound(); }}
                >
                  试听当前铃声
                </Button>
              </div>
            </div>
          </div>

          {alerts.length === 0 ? (
            <div className="rounded-2xl border border-dashed border-slate-200 px-4 py-10 text-center text-sm text-muted-foreground">
              当前没有待处理的验证码提醒。
            </div>
          ) : (
            <div className="max-h-[60vh] space-y-3 overflow-auto pr-1">
              {alerts.map((alert) => (
                <button
                  key={alert.alertId}
                  type="button"
                  onClick={() => { void openAlert(alert); }}
                  disabled={openingTaskId === alert.taskId}
                  className="w-full rounded-2xl border border-orange-200 bg-orange-50/80 p-4 text-left transition-colors hover:bg-orange-100 disabled:cursor-not-allowed disabled:opacity-70"
                >
                  <div className="flex items-start gap-3">
                    <div className="mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-orange-100 text-orange-700">
                      {openingTaskId === alert.taskId ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <AlertTriangle className="h-4 w-4" />}
                    </div>

                    <div className="min-w-0 flex-1">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="text-sm font-semibold text-orange-950">{alert.message}</span>
                        <Badge variant="outline" className="border-orange-300 bg-white/70 text-orange-800">
                          {alert.headless ? '无头接管' : '浏览器前台'}
                        </Badge>
                      </div>

                      <div className="mt-2 grid gap-1 text-xs text-orange-900/80 sm:grid-cols-2">
                        <span>批次：{alert.batchId || '-'}</span>
                        <span>任务：{alert.taskId.slice(0, 8)}</span>
                        <span>材料：{alert.materialName || alert.materialId || '-'}</span>
                        <span>账户：{alert.accountName || alert.accountId || '-'}</span>
                        <span>时间：{formatDateTime(alert.detectedAt)}</span>
                        <span className="inline-flex items-center gap-1">
                          <Monitor className="h-3.5 w-3.5" />
                          点击后打开验证码页面
                        </span>
                      </div>

                      {alert.pageUrl ? (
                        <div className="mt-2 flex items-center gap-1 text-[11px] text-orange-700/75">
                          <ExternalLink className="h-3.5 w-3.5" />
                          <span className="truncate">{alert.pageUrl}</span>
                        </div>
                      ) : null}
                    </div>
                  </div>
                </button>
              ))}
            </div>
          )}
        </DialogContent>
      </Dialog>
    </>
  );
}