'use client';

import { useState } from 'react';
import { toast } from 'sonner';
import type { UserRole } from '@pac/types';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { useAuthStore } from '@/stores/auth-store';
import { mockLogin } from '@/lib/auth-api';
import { cn } from '@/lib/utils';

/**
 * MockLoginDialog — 试部署 / 演示用快速登录(只在 dev 启用)
 *
 * 用途:还没接 host SSO 时,客服 / 演示者可一键以 瑞尔/瑞泰 × staff/leader/admin
 *      身份登录工作台。后端 env `PAC_ENABLE_MOCK_LOGIN=false` 一关即生产模式。
 *
 * 不可关闭(open=true 强制保持):未鉴权用户**必须选一个身份**才能进列表页。
 * 已鉴权后由 AuthGate 接管,放行 children。
 *
 * 设计:6 个按钮,2 brand × 3 role 网格;点击 → mockLogin API → setTokens → reload。
 */

type TenantSlug = 'ruier' | 'ruitai';

const TENANTS: { slug: TenantSlug; nameZh: string; tone: string }[] = [
  { slug: 'ruier', nameZh: '瑞尔', tone: 'border-teal-200 bg-teal-50/40' },
  { slug: 'ruitai', nameZh: '瑞泰', tone: 'border-sky-200 bg-sky-50/40' },
];

const ROLES: { key: UserRole; nameZh: string; desc: string }[] = [
  { key: 'staff', nameZh: '员工', desc: '执行客服 · 看自己的召回任务' },
  { key: 'leader', nameZh: '主管', desc: '看本团队所有任务 · 可指派 / 回收' },
  { key: 'admin', nameZh: '管理员', desc: '全部权限 · 含后台管理' },
];

export function MockLoginDialog({ open }: { open: boolean }) {
  const setTokens = useAuthStore((s) => s.setTokens);
  const [busy, setBusy] = useState<string | null>(null); // 'ruier:staff' 等

  const pick = async (tenant: TenantSlug, role: UserRole) => {
    const key = `${tenant}:${role}`;
    if (busy) return;
    setBusy(key);
    try {
      const r = await mockLogin({ tenant, role });
      setTokens({
        accessToken: r.accessToken,
        refreshToken: r.refreshToken,
        expiresIn: r.expiresIn,
      });
      const tNameZh = TENANTS.find((t) => t.slug === tenant)?.nameZh ?? tenant;
      const rNameZh = ROLES.find((r) => r.key === role)?.nameZh ?? role;
      toast.success(`已登录:${tNameZh} · ${rNameZh}`, {
        description: '(模拟身份,真生产环境会接宿主 SSO)',
      });
      // AuthGate 监听 isAuthenticated,setTokens 后自动放行
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      toast.error('登录失败', { description: msg.slice(0, 120) });
      setBusy(null);
    }
  };

  return (
    <Dialog open={open}>
      <DialogContent
        // 禁掉 ESC / 点遮罩关闭 — 未鉴权必须选身份才能进
        onEscapeKeyDown={(e) => e.preventDefault()}
        onPointerDownOutside={(e) => e.preventDefault()}
        // 隐藏右上 X 关闭按钮(子树里的 DialogPrimitive.Close)
        className="max-w-2xl [&>button[aria-label='Close']]:hidden"
      >
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <span className="inline-flex h-7 w-7 items-center justify-center rounded-md bg-teal-600 text-[12px] font-bold text-white">
              PAC
            </span>
            <span>快速登录</span>
            <span className="rounded-md bg-amber-100 px-1.5 py-0.5 text-[10.5px] font-medium text-amber-700">
              模拟身份 · 试部署
            </span>
          </DialogTitle>
          <DialogDescription className="text-[12px]">
            生产环境会接宿主 SSO,这里是<strong>开发 / 试部署</strong>的快速通道。请选一个身份进入工作台:
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-3 pt-2">
          {TENANTS.map((t) => (
            <div
              key={t.slug}
              className={cn('rounded-lg border p-3', t.tone)}
            >
              <div className="mb-2 flex items-center gap-2 text-[13px] font-semibold text-slate-800">
                <span>{t.nameZh}</span>
                <span className="text-[10.5px] font-normal text-slate-500">
                  {t.slug === 'ruier' ? '3 家诊所(杭州大厦/高德 · 北京朝阳)' : '2 家诊所(通善学前街 · 上海世纪公园)'}
                </span>
              </div>
              <div className="grid gap-2 sm:grid-cols-3">
                {ROLES.map((r) => {
                  const key = `${t.slug}:${r.key}`;
                  const loading = busy === key;
                  return (
                    <button
                      key={key}
                      type="button"
                      onClick={() => pick(t.slug, r.key)}
                      disabled={!!busy}
                      className={cn(
                        'group flex flex-col items-start gap-1 rounded-md border bg-white px-3 py-2 text-left transition-all',
                        loading
                          ? 'border-teal-400 ring-2 ring-teal-200'
                          : 'border-slate-200 hover:border-teal-400 hover:bg-teal-50/40',
                        busy && !loading && 'opacity-50',
                      )}
                    >
                      <div className="text-[12.5px] font-semibold text-slate-800">
                        {loading ? '登录中…' : r.nameZh}
                      </div>
                      <div className="text-[10.5px] leading-tight text-slate-500">{r.desc}</div>
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        <p className="pt-1 text-[10.5px] leading-relaxed text-slate-400">
          提示:登录后 token 写入浏览器 localStorage(2h 有效 · 自动 refresh),
          清浏览器数据或换浏览器会重新弹此对话框。
        </p>
      </DialogContent>
    </Dialog>
  );
}
