'use client';

import { useState } from 'react';
import { CLOSE_REASON_META, CloseReason } from '@pac/types';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';

/**
 * 关闭机会弹窗 —— 宿主回访模式下(顶栏有「回访」按钮)替代通话结果区的关闭入口。
 * 原因清单 / 说明必填 / outcome 映射 全部来自 CLOSE_REASON_META(@pac/types 单一真理源);
 * 提交行为由调用方 onConfirm 承接(execution 通道 + 需要时双写召回反馈)。
 */
const CLOSE_REASONS = (Object.keys(CLOSE_REASON_META) as CloseReason[]).map((key) => ({
  key,
  ...CLOSE_REASON_META[key],
}));

export type CloseReasonKey = CloseReason;

export function CloseOpportunityDialog({
  open,
  onOpenChange,
  onConfirm,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  /** 确认关闭(reason + 其他原因时的说明)。未接后端前由调用方决定提示行为。 */
  onConfirm?: (reason: CloseReasonKey, note?: string) => void;
}) {
  const [reason, setReason] = useState<CloseReasonKey | null>(null);
  const [note, setNote] = useState('');

  const selected = CLOSE_REASONS.find((r) => r.key === reason);
  const needNote = selected?.needNote === true;
  const canConfirm = !!reason && (!needNote || note.trim().length > 0);

  const reset = () => {
    setReason(null);
    setNote('');
  };

  return (
    <Dialog
      open={open}
      onOpenChange={(v) => {
        onOpenChange(v);
        if (!v) reset();
      }}
    >
      <DialogContent className="sm:max-w-[520px]">
        <DialogHeader>
          <DialogTitle className="text-[15px]">关闭机会</DialogTitle>
        </DialogHeader>

        <div className="space-y-3">
          <div className="text-[12.5px] font-medium text-slate-900">
            选择关闭原因 <span className="text-rose-600">*</span>
          </div>
          {/* 原因单选卡:两列;「其他原因」独占整行 */}
          <div className="grid grid-cols-2 gap-2">
            {CLOSE_REASONS.map((r) => {
              const active = reason === r.key;
              return (
                <button
                  key={r.key}
                  type="button"
                  onClick={() => setReason(r.key)}
                  className={cn(
                    'flex items-center gap-2 rounded-md border px-3 py-2.5 text-left text-[12.5px] transition-colors',
                    r.key === 'other' && 'col-span-2',
                    active
                      ? 'border-teal-400 bg-teal-50 font-medium text-teal-800'
                      : 'border-slate-200 bg-white text-slate-700 hover:border-teal-300 hover:bg-teal-50/50',
                  )}
                >
                  <span
                    className={cn(
                      'flex h-3.5 w-3.5 flex-none items-center justify-center rounded-full border',
                      active ? 'border-teal-600' : 'border-slate-300',
                    )}
                  >
                    {active && <span className="h-2 w-2 rounded-full bg-teal-600" />}
                  </span>
                  {r.labelZh}
                </button>
              );
            })}
          </div>

          {needNote && (
            <div className="space-y-1.5">
              <div className="text-[12.5px] font-medium text-slate-900">
                请描述具体原因 <span className="text-rose-600">*</span>
              </div>
              <textarea
                value={note}
                onChange={(e) => setNote(e.target.value)}
                rows={3}
                placeholder="请详细描述关闭机会的具体原因,以便后续分析和改进…"
                className="w-full resize-y rounded-md border border-slate-200 bg-white px-3 py-2 text-[12.5px] text-slate-900 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-teal-200 focus:border-teal-400"
              />
            </div>
          )}

          {selected && (
            <div className="rounded-md border border-teal-100 bg-teal-50/60 px-3 py-2">
              <div className="text-[11.5px] font-semibold text-teal-800">已选关闭原因</div>
              <div className="mt-0.5 text-[12px] text-slate-700">
                {selected.labelZh} · {selected.desc}
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" size="sm" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button
            size="sm"
            disabled={!canConfirm}
            onClick={() => {
              if (!reason) return;
              onConfirm?.(reason, needNote ? note.trim() : undefined);
              onOpenChange(false);
              reset();
            }}
          >
            确认关闭
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
