'use client';

import { useState } from 'react';
import {
  EXECUTION_OUTCOME_META,
  EXECUTION_OUTCOME_GROUP_META,
  type ExecutionOutcome,
  type ExecutionOutcomeGroup,
} from '@pac/types';
import { cn } from '@/lib/utils';
import { tone } from './shared';
import { DatePicker } from '@/components/ui/date-picker';
import { Input } from '@/components/ui/input';

/// 本地日期 ⇄ 'yyyy-MM-dd' 字符串(避免 new Date(ISO) 的时区偏移)
const toYMD = (d: Date) =>
  `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const fromYMD = (s: string) => {
  const [y, m, d] = s.split('-').map(Number);
  return new Date(y ?? 1970, (m ?? 1) - 1, d ?? 1);
};

/// outcome 选项从 @pac/types EXECUTION_OUTCOME_META 派生(单一真理源,跟后端共享)
/// 改 enum / label / group / 状态机映射只在 packages/types 一处改,前后端同步生效
/// 2 级分组:按 group 归类(成功 / 不成功 / 保持),hiddenInForm 的历史值不展示
const OUTCOME_GROUPS = (
  Object.keys(EXECUTION_OUTCOME_GROUP_META) as ExecutionOutcomeGroup[]
)
  .sort((a, b) => EXECUTION_OUTCOME_GROUP_META[a].order - EXECUTION_OUTCOME_GROUP_META[b].order)
  .map((g) => ({
    key: g,
    label: EXECUTION_OUTCOME_GROUP_META[g].labelZh,
    options: (
      Object.entries(EXECUTION_OUTCOME_META) as Array<
        [ExecutionOutcome, (typeof EXECUTION_OUTCOME_META)[ExecutionOutcome]]
      >
    )
      .filter(([, meta]) => meta.group === g && !meta.hiddenInForm)
      .map(([value, meta]) => ({ value, label: meta.labelZh, tone: meta.tone, drives: meta.drivesStatus })),
  }))
  .filter((grp) => grp.options.length > 0);

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; status?: string };
  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 curMeta = outcome ? EXECUTION_OUTCOME_META[outcome as ExecutionOutcome] : null;
  const cur = curMeta ? { tone: curMeta.tone, drives: curMeta.drivesStatus } : null;
  const needsScheduledNext = outcome === 'scheduled_next';
  const needsAbandonReasons = !!outcome && outcome === 'refused';
  // 终态(已结案/已放弃/已被替代)不可再写 execution(后端也会拒);提交按钮置灰 + 顶部提示
  const isTerminal = ['completed', 'abandoned', 'superseded'].includes(plan.status ?? '');
  const canSubmit = !!outcome && !!channel && !submitted && !isTerminal;
  // 下次回访时间拆成 日期('yyyy-MM-dd')+ 时间('HH:mm')两部分,日历选日期、时间框选时间,合成回 scheduledNextAt
  const schedDate = scheduledNextAt.split('T')[0] ?? '';
  const schedTime = scheduledNextAt.split('T')[1] ?? '';

  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">
      {isTerminal && (
        <div className="flex-none rounded bg-slate-100 border border-slate-200 px-2.5 py-1.5 text-[11px] text-slate-500 leading-snug">
          本任务已{plan.status === 'abandoned' ? '放弃' : plan.status === 'superseded' ? '被新版本替代' : '结案'},不可再提交执行;如需重新跟进,等召回重新生成。
        </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-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="space-y-2">
          {OUTCOME_GROUPS.map((grp) => (
            <div key={grp.key}>
              <div className="text-[9.5px] font-semibold text-slate-400 mb-1 pl-0.5">{grp.label}</div>
              <div className="grid grid-cols-2 gap-1">
                {grp.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>
            </div>
          ))}
        </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>
          <div className="flex gap-1.5">
            <div className="flex-1 min-w-0">
              <DatePicker
                value={schedDate ? fromYMD(schedDate) : undefined}
                // 选日期时,时间缺省给 10:00(没填时间也能合成有效 datetime)
                onChange={(d) => setScheduledNextAt(d ? `${toYMD(d)}T${schedTime || '10:00'}` : '')}
                min={new Date(new Date().setHours(0, 0, 0, 0))}
                placeholder="选择回访日期"
              />
            </div>
            <Input
              type="time"
              value={schedTime}
              disabled={!schedDate}
              onChange={(e) => schedDate && setScheduledNextAt(`${schedDate}T${e.target.value}`)}
              className="w-[96px] flex-none text-[12.5px] appearance-none bg-white [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"
            />
          </div>
        </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>
      )}

      {/* 召回反馈已移出执行表单 → 详情页标题栏拇指(RecallFeedbackControl);此处不再收集 */}

      <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">
          {/* 新建预约按钮常显(不再仅"成功"时出现)— 客服任何时候都能手动建预约 */}
          <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>
  );
}
