'use client';

import { useState } from 'react';
import { EXECUTION_OUTCOME_META, type ExecutionOutcome } from '@pac/types';
import { cn } from '@/lib/utils';
import { tone } from './shared';

/// outcome 选项从 @pac/types EXECUTION_OUTCOME_META 派生(单一真理源,跟后端共享)
/// 改 enum / label / 状态机映射只在 packages/types 一处改,前后端同步生效
const OUTCOME_OPTIONS = (
  Object.entries(EXECUTION_OUTCOME_META) as Array<[ExecutionOutcome, (typeof EXECUTION_OUTCOME_META)[ExecutionOutcome]]>
).map(([value, meta]) => ({
  value,
  label: meta.labelZh,
  tone: meta.tone,
  drives: meta.drivesStatus,
}));

const CHANNELS = [
  {
    value: 'phone',
    label: '电话',
    tone: 'sky',
    d: 'M2.5 4.5c0-1.1.9-2 2-2h2.3c.9 0 1.7.6 1.9 1.5l.8 3a2 2 0 0 1-.6 2L7.4 10a12 12 0 0 0 5.6 5.6l1-1.5a2 2 0 0 1 2-.6l3 .8c.9.2 1.5 1 1.5 1.9V18.5c0 1.1-.9 2-2 2A18 18 0 0 1 2.5 4.5z',
  },
  {
    value: 'wecom',
    label: '企微',
    tone: 'emerald',
    d: 'M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z',
  },
  {
    value: 'sms',
    label: '短信',
    tone: 'violet',
    d: 'M4 5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H8l-4 4V5z',
  },
];

/// drivesStatus → 用户口径中文提示
///   completed — 终态(成功转化 / 客户决策放弃跟进)
///   abandoned — 终态(系统层面无效或客服主动放弃)
///   keep      — 任务保留等下次跟进(熔断器到上限会自动 abandon)
const STATE_HINTS: Record<string, string> = {
  completed: '本次任务将结案',
  abandoned: '本次任务将关闭(放弃)',
  keep: '本次任务保留,等下次跟进',
};

const ABANDON_REASONS = ['号码空号 / 错号', '已转介他人', '明确不需要治疗', '迁居外地', '投诉 / 不愿打扰', '其他'];

export function OutcomeForm({
  plan,
  onSubmit,
  onCreateAppointment,
  defaultChannel = 'phone',
}: {
  plan: { contactAttempts: number };
  onSubmit: (data: {
    channel: string;
    outcome: string;
    notes: string;
    scheduledNextAt: string;
    abandonReasons: string[];
  }) => void;
  onCreateAppointment: () => void;
  defaultChannel?: string;
}) {
  const [channel, setChannel] = useState(defaultChannel);
  const [outcome, setOutcome] = useState<string | null>(null);
  const [notes, setNotes] = useState('');
  const [scheduledNextAt, setScheduledNextAt] = useState('');
  const [abandonReasons, setAbandonReasons] = useState<string[]>([]);
  const [submitted, setSubmitted] = useState(false);

  const cur = OUTCOME_OPTIONS.find((o) => o.value === outcome);
  const needsScheduledNext =
    !!outcome && ['scheduled_next', 'considering', 'rescheduled', 'pending_info'].includes(outcome);
  const needsAbandonReasons = !!outcome && ['abandoned', 'refused', 'declined_recent'].includes(outcome);
  const isSuccess = outcome === 'success_appointed';
  const canSubmit = !!outcome && !!channel && !submitted;

  const handleSubmit = () => {
    if (!canSubmit) return;
    setSubmitted(true);
    onSubmit({ channel, outcome: outcome!, notes, scheduledNextAt, abandonReasons });
    setTimeout(() => {
      setSubmitted(false);
      setOutcome(null);
      setNotes('');
      setScheduledNextAt('');
      setAbandonReasons([]);
      setChannel(defaultChannel);
    }, 2400);
  };

  return (
    <div className="flex flex-col gap-2.5 h-full min-h-0">
      <div className="flex-none">
        <div className="text-[10.5px] font-semibold text-slate-500 uppercase tracking-wider mb-1.5">
          触达方式 <span className="text-rose-500">*</span>
          <span className="ml-2 font-normal normal-case text-[10px] text-slate-400 tracking-normal">系统建议电话</span>
        </div>
        <div className="grid grid-cols-3 gap-1">
          {CHANNELS.map((c) => {
            const T = tone(c.tone);
            const selected = c.value === channel;
            return (
              <button
                key={c.value}
                onClick={() => setChannel(c.value)}
                className={cn(
                  'px-2 py-1.5 rounded text-[11.5px] border transition-colors inline-flex items-center justify-center gap-1.5',
                  selected
                    ? `${T.bg} ${T.text} border-current font-medium ring-1 ring-current/30`
                    : 'bg-white text-slate-700 border-slate-200 hover:border-slate-300 hover:bg-slate-50',
                )}
              >
                <svg
                  viewBox="0 0 24 24"
                  className="w-3.5 h-3.5"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <path d={c.d} />
                </svg>
                {c.label}
              </button>
            );
          })}
        </div>
      </div>

      <div className="flex-none">
        <div className="text-[10.5px] font-semibold text-slate-500 uppercase tracking-wider mb-1.5">
          通话结果 <span className="text-rose-500">*</span>
        </div>
        <div className="grid grid-cols-2 gap-1">
          {OUTCOME_OPTIONS.map((o) => {
            const T = tone(o.tone);
            const selected = o.value === outcome;
            return (
              <button
                key={o.value}
                onClick={() => setOutcome(o.value)}
                className={cn(
                  'px-2 py-1 rounded text-left text-[11px] border transition-colors flex items-center gap-1.5',
                  selected
                    ? `${T.bg} ${T.text} border-current font-medium ring-1 ring-current/30`
                    : 'bg-white text-slate-700 border-slate-200 hover:border-slate-300 hover:bg-slate-50',
                )}
              >
                <span className={cn('flex-none w-1.5 h-1.5 rounded-full', selected ? T.dot : 'bg-slate-300')} />
                <span className="truncate">{o.label}</span>
              </button>
            );
          })}
        </div>
        {cur && (
          <div className={cn('mt-1.5 text-[10.5px] flex items-center gap-1.5', tone(cur.tone).text)}>
            <svg viewBox="0 0 24 24" className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M5 12h14M13 5l7 7-7 7" strokeLinecap="round" />
            </svg>
            <span>{STATE_HINTS[cur.drives] || '本次任务将更新'}</span>
          </div>
        )}
      </div>

      {needsScheduledNext && (
        <div className="flex-none rounded bg-amber-50 border border-amber-200 px-2.5 py-2">
          <label className="block text-[10.5px] font-semibold text-amber-900 mb-1">下次回访时间</label>
          <input
            type="datetime-local"
            value={scheduledNextAt}
            onChange={(e) => setScheduledNextAt(e.target.value)}
            className="w-full px-2 py-1 rounded border border-amber-200 bg-white text-[12px]"
          />
        </div>
      )}
      {needsAbandonReasons && (
        <div className="flex-none rounded bg-rose-50 border border-rose-200 px-2.5 py-2">
          <label className="block text-[10.5px] font-semibold text-rose-900 mb-1.5">放弃原因(可多选)</label>
          <div className="grid grid-cols-2 gap-1">
            {ABANDON_REASONS.map((r) => (
              <label
                key={r}
                className="flex items-center gap-1.5 px-1.5 py-1 rounded bg-white border border-rose-100 text-[10.5px] cursor-pointer"
              >
                <input
                  type="checkbox"
                  checked={abandonReasons.includes(r)}
                  onChange={() =>
                    setAbandonReasons(
                      abandonReasons.includes(r) ? abandonReasons.filter((x) => x !== r) : [...abandonReasons, r],
                    )
                  }
                  className="accent-rose-600 scale-90"
                />
                <span className="text-slate-700 truncate">{r}</span>
              </label>
            ))}
          </div>
        </div>
      )}

      <div className="flex-1 min-h-0 flex flex-col">
        <label className="flex-none text-[10.5px] font-semibold text-slate-500 uppercase tracking-wider mb-1">
          通话纪要
        </label>
        <textarea
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          placeholder="患者反馈、关键点、需告知医生的信息……"
          className="flex-1 min-h-[60px] px-2.5 py-1.5 rounded border border-slate-200 bg-white text-[12.5px] resize-none focus:outline-none focus:ring-2 focus:ring-teal-200 focus:border-teal-300"
        />
      </div>

      <div className="flex-none flex items-center justify-between gap-2 pt-1">
        <span className="text-[10px] text-slate-400 leading-tight">
          本次为第 <strong className="text-slate-600 tabular-nums">{plan.contactAttempts + 1}</strong> 次触达
        </span>
        <div className="flex items-center gap-1.5">
          {isSuccess && (
            <button
              onClick={onCreateAppointment}
              className="px-3 py-1.5 rounded text-[12px] border border-teal-300 text-teal-700 hover:bg-teal-50 inline-flex items-center gap-1 transition-colors"
            >
              <svg
                viewBox="0 0 24 24"
                className="w-3.5 h-3.5"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <rect x="3" y="4" width="18" height="18" rx="2" />
                <path d="M16 2v4M8 2v4M3 10h18M12 14v4M10 16h4" />
              </svg>
              新建预约
            </button>
          )}
          <button
            disabled={!canSubmit}
            onClick={handleSubmit}
            className={cn(
              'px-4 py-1.5 rounded text-[12.5px] font-semibold inline-flex items-center gap-1.5 transition-colors',
              submitted
                ? 'bg-emerald-600 text-white'
                : canSubmit
                  ? 'bg-teal-600 text-white hover:bg-teal-700'
                  : 'bg-slate-100 text-slate-400 cursor-not-allowed',
            )}
          >
            {submitted ? (
              <>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="w-3.5 h-3.5">
                  <path d="M5 13l4 4L19 7" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                已归档
              </>
            ) : (
              <>
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.8"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="w-3.5 h-3.5"
                >
                  <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" />
                </svg>
                提交
              </>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
