'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Filter, Loader2, PhoneCall, Search, X } from 'lucide-react';
import { PERSONA_TAG_FILTER_DIMS, Permission, type PlanListItem } from '@pac/types';
import { cn } from '@/lib/utils';
import { useHasPermission } from '@/hooks/use-permission';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { usePatientPicker, type PickerFilters } from './use-patient-picker';

/**
 * PatientPickerRail — 详情页固定左栏(第 4 列):一页式工作台的"选患者"列。
 *
 * 吸收列表页核心要素(列表页将弃用):view tab / 搜索 / 排序 / 真实号码 /
 * ⭐画像标签筛选(价值分群 / 生命周期 / 紧迫度 / 潜在治疗,同维 OR 跨维 AND,服务端 SQL)。
 * 不带 KPI 面板(按需求剔除)。点患者 → 路由切详情;本组件挂在 plans/layout(路由段之上),
 * 切患者不重挂、列表状态(筛选/滚动位置/已加载页)全保留。
 */

type View = PickerFilters['view'];
const VIEW_TABS: Array<{ v: View; label: string }> = [
  { v: 'pool', label: '召回池' },
  { v: 'mine', label: '我的' },
  { v: 'all', label: '全部' },
];

export function PatientPickerRail({ currentPlanId }: { currentPlanId: string }) {
  const router = useRouter();
  const canViewAll = useHasPermission(Permission.PLAN_VIEW_ALL);

  const [view, setView] = useState<View>('mine');
  const [search, setSearch] = useState('');
  const [keyword, setKeyword] = useState(''); // 防抖后的值(真正上服务端)
  const [sort, setSort] = useState<PickerFilters['sort']>('priority_desc');
  const [realPhoneOnly, setRealPhoneOnly] = useState(false);
  const [tags, setTags] = useState<Set<string>>(new Set()); // "key:value"

  useEffect(() => {
    const t = setTimeout(() => setKeyword(search.trim()), 300);
    return () => clearTimeout(t);
  }, [search]);

  const filters: PickerFilters = useMemo(
    () => ({
      view,
      keyword: keyword || undefined,
      sort,
      phoneVerified: realPhoneOnly ? true : undefined,
      personaTags: tags.size ? [...tags].join(',') : undefined,
    }),
    [view, keyword, sort, realPhoneOnly, tags],
  );
  const { items, total, loading, hasMore, error, loadMore } = usePatientPicker(filters);

  // 触底加载
  const listRef = useRef<HTMLDivElement>(null);
  const onScroll = () => {
    const el = listRef.current;
    if (!el || loading || !hasMore) return;
    if (el.scrollHeight - el.scrollTop - el.clientHeight < 120) loadMore();
  };

  const toggleTag = (k: string) =>
    setTags((prev) => {
      const next = new Set(prev);
      if (next.has(k)) next.delete(k);
      else next.add(k);
      return next;
    });

  return (
    <aside className="flex h-full w-[300px] flex-none flex-col border-r border-slate-200 bg-white">
      {/* view tabs */}
      <div className="flex flex-none gap-1 border-b border-slate-100 px-2 pt-2">
        {VIEW_TABS.filter((t) => t.v !== 'all' || canViewAll).map((t) => (
          <button
            key={t.v}
            type="button"
            onClick={() => setView(t.v)}
            className={cn(
              'rounded-t-md px-3 py-1.5 text-[12.5px] transition-colors',
              view === t.v
                ? 'border-b-2 border-teal-600 font-semibold text-teal-700'
                : 'text-slate-500 hover:text-slate-800',
            )}
          >
            {t.label}
          </button>
        ))}
        <span className="ml-auto self-center pr-1 text-[10.5px] tabular-nums text-slate-400">
          {total} 人
        </span>
      </div>

      {/* 搜索 + 工具行 */}
      <div className="flex-none space-y-1.5 border-b border-slate-100 p-2">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
          <input
            type="search"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="姓名 / 手机 / 患者号"
            className="h-7 w-full rounded-md border border-slate-200 bg-slate-50 pl-7 pr-2 text-[12px] outline-none placeholder:text-slate-400 focus:border-teal-300 focus:bg-white"
          />
        </div>
        <div className="flex items-center gap-1.5">
          <select
            value={sort}
            onChange={(e) => setSort(e.target.value as PickerFilters['sort'])}
            className="h-6.5 rounded-md border border-slate-200 bg-white px-1.5 py-0.5 text-[11px] text-slate-600"
          >
            <option value="priority_desc">优先级 高→低</option>
            <option value="priority_asc">优先级 低→高</option>
            <option value="created_desc">最新生成</option>
          </select>
          <button
            type="button"
            onClick={() => setRealPhoneOnly((v) => !v)}
            title="只看已核实的真实手机号"
            className={cn(
              'inline-flex h-6 items-center gap-1 rounded-md border px-1.5 text-[11px] transition-colors',
              realPhoneOnly
                ? 'border-teal-300 bg-teal-50 font-medium text-teal-700'
                : 'border-slate-200 bg-white text-slate-500 hover:bg-slate-50',
            )}
          >
            <PhoneCall className="h-3 w-3" />真
          </button>
          <PersonaTagFilter selected={tags} onToggle={toggleTag} onClear={() => setTags(new Set())} />
        </div>
        {/* 已选标签 chips */}
        {tags.size > 0 && (
          <div className="flex flex-wrap gap-1">
            {[...tags].map((kv) => {
              const [k, v] = kv.split(':');
              const dim = PERSONA_TAG_FILTER_DIMS.find((d) => d.key === k);
              const opt = dim?.options.find((o) => o.value === v);
              return (
                <button
                  key={kv}
                  type="button"
                  onClick={() => toggleTag(kv)}
                  className="inline-flex items-center gap-0.5 rounded-full bg-teal-50 px-1.5 py-0.5 text-[10.5px] text-teal-700 ring-1 ring-inset ring-teal-200 hover:bg-teal-100"
                  title={`${dim?.nameZh}:${opt?.zh}(点击移除)`}
                >
                  {opt?.zh ?? v}
                  <X className="h-2.5 w-2.5" />
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* 患者列表 */}
      <div ref={listRef} onScroll={onScroll} className="min-h-0 flex-1 overflow-y-auto">
        {error && <div className="p-3 text-center text-[11.5px] text-rose-500">{error}</div>}
        {items.map((p) => (
          <PatientRow
            key={p.id}
            plan={p}
            active={p.id === currentPlanId}
            onClick={() => router.push(`/plans/${p.id}`)}
          />
        ))}
        {loading && (
          <div className="flex justify-center py-3">
            <Loader2 className="h-4 w-4 animate-spin text-slate-300" />
          </div>
        )}
        {!loading && items.length === 0 && !error && (
          <div className="p-6 text-center text-[11.5px] text-slate-400">没有匹配的患者</div>
        )}
        {!loading && hasMore && (
          <button
            type="button"
            onClick={loadMore}
            className="block w-full py-2 text-center text-[11px] text-teal-700 hover:bg-teal-50/50"
          >
            加载更多({items.length}/{total})
          </button>
        )}
      </div>
    </aside>
  );
}

// ── 画像标签筛选 popover(4 维度分组多选)────────────────────
function PersonaTagFilter({
  selected,
  onToggle,
  onClear,
}: {
  selected: Set<string>;
  onToggle: (kv: string) => void;
  onClear: () => void;
}) {
  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          className={cn(
            'inline-flex h-6 items-center gap-1 rounded-md border px-1.5 text-[11px] transition-colors',
            selected.size > 0
              ? 'border-teal-300 bg-teal-50 font-medium text-teal-700'
              : 'border-slate-200 bg-white text-slate-500 hover:bg-slate-50',
          )}
        >
          <Filter className="h-3 w-3" />
          画像标签{selected.size > 0 ? ` ${selected.size}` : ''}
        </button>
      </PopoverTrigger>
      <PopoverContent align="start" className="w-64 p-2">
        <div className="mb-1 flex items-center justify-between px-1">
          <span className="text-[11px] font-medium text-slate-500">按画像圈人(跨维交集)</span>
          {selected.size > 0 && (
            <button type="button" onClick={onClear} className="text-[10.5px] text-teal-700 hover:underline">
              清空
            </button>
          )}
        </div>
        <div className="max-h-80 space-y-2 overflow-y-auto">
          {PERSONA_TAG_FILTER_DIMS.map((dim) => (
            <div key={dim.key}>
              <div className="px-1 py-0.5 text-[10.5px] font-medium uppercase tracking-wide text-slate-400">
                {dim.nameZh}
              </div>
              <div className="flex flex-wrap gap-1 px-1 pb-1">
                {dim.options.map((o) => {
                  const kv = `${dim.key}:${o.value}`;
                  const on = selected.has(kv);
                  return (
                    <button
                      key={kv}
                      type="button"
                      onClick={() => onToggle(kv)}
                      className={cn(
                        'rounded-full border px-2 py-0.5 text-[11px] transition-colors',
                        on
                          ? 'border-teal-300 bg-teal-50 font-medium text-teal-700'
                          : 'border-slate-200 bg-white text-slate-600 hover:border-teal-200 hover:bg-teal-50/40',
                      )}
                    >
                      {o.zh}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </PopoverContent>
    </Popover>
  );
}

// ── 患者行(紧凑单列卡)────────────────────────────────────
function PatientRow({
  plan: p,
  active,
  onClick,
}: {
  plan: PlanListItem;
  active: boolean;
  onClick: () => void;
}) {
  const score = Math.round(p.priorityScore);
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        'block w-full border-b border-slate-100 px-3 py-2 text-left transition-colors',
        active ? 'bg-teal-50/70 ring-1 ring-inset ring-teal-200' : 'hover:bg-slate-50',
      )}
    >
      <div className="flex items-center gap-1.5">
        <span className={cn('truncate text-[13px] font-semibold', active ? 'text-teal-800' : 'text-slate-900')}>
          {p.patient.name ?? p.patient.nameMasked ?? '—'}
        </span>
        <span className="flex-none text-[10.5px] text-slate-400 tabular-nums">
          {p.patient.gender === 'male' ? '男' : p.patient.gender === 'female' ? '女' : ''}
          {p.patient.age != null ? `·${p.patient.age}` : ''}
        </span>
        {p.patient.phoneVerified && (
          <span className="flex-none rounded bg-teal-50 px-1 text-[9.5px] font-medium leading-4 text-teal-700 ring-1 ring-inset ring-teal-200">
            真
          </span>
        )}
        <span
          className={cn(
            'ml-auto flex-none text-[13px] font-bold tabular-nums',
            score >= 80 ? 'text-rose-600' : score >= 60 ? 'text-amber-600' : 'text-slate-400',
          )}
        >
          {score}
        </span>
      </div>
      <div className="mt-0.5 flex items-center gap-1.5">
        <span className="flex-none rounded bg-slate-100 px-1.5 py-0.5 text-[10px] text-slate-600">
          {p.scenarioLabel}
        </span>
        <span className="truncate font-mono text-[10.5px] text-slate-400 tabular-nums">
          {p.patient.phoneMasked ?? ''}
        </span>
        {p.status !== 'active' && (
          <span className="ml-auto flex-none text-[10px] text-slate-400">
            {p.status === 'assigned' ? '进行中' : p.status === 'completed' ? '已完成' : p.status === 'abandoned' ? '已放弃' : p.status}
          </span>
        )}
      </div>
    </button>
  );
}
