import { useState } from 'react';
import {
  X, MapPin, AlertTriangle, CheckCircle, Send, ArrowRight,
} from 'lucide-react';
import { motion } from 'motion/react';
import { sendNotify } from './api';
import type { SchedulingSuggestion, CandidateVehicle } from './types';
import Blur from '../../components/Blur';

interface Props {
  suggestion: SchedulingSuggestion;
  onClose: () => void;
  onNotifySuccess: () => void;
}

function fmtKm(value: number): string {
  if (value >= 10000) return (value / 10000).toFixed(1) + '万';
  return value.toLocaleString();
}

export default function SuggestionDetail({ suggestion: s, onClose, onNotifySuccess }: Props) {
  const [sending, setSending] = useState(false);
  const [sentPlates, setSentPlates] = useState<Set<string>>(new Set());

  const v = s.currentVehicle;
  const isRescue = s.type === 'rescue_hopeless';

  const handleNotify = async (candidate: CandidateVehicle) => {
    if (sending || sentPlates.has(candidate.plateNumber)) return;
    setSending(true);
    try {
      const result = await sendNotify({
        suggestionId: s.id,
        currentPlate: v.plateNumber,
        candidatePlate: candidate.plateNumber,
      });
      if (result.success) {
        setSentPlates(prev => new Set(prev).add(candidate.plateNumber));
        onNotifySuccess();
      } else {
        alert(result.message || '发送失败');
      }
    } catch {
      alert('网络错误，请重试');
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[60] flex items-end sm:items-center justify-center">
      <motion.div
        initial={{ y: 40, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        className="bg-white rounded-t-2xl sm:rounded-2xl shadow-2xl w-full sm:max-w-lg overflow-hidden flex flex-col max-h-[92vh] sm:max-h-[85vh] sm:mx-4"
      >
        {/* Header */}
        <div className={`${isRescue ? 'bg-rose-600' : 'bg-amber-500'} px-4 py-3 flex items-center justify-between flex-shrink-0`}>
          <span className="text-white font-bold text-sm">
            {isRescue ? '抢救低里程车辆' : '释放已达标车辆'}
          </span>
          <button onClick={onClose} className="text-white/70 hover:text-white transition-colors p-1">
            <X size={18} />
          </button>
        </div>

        {/* Body */}
        <div className="overflow-y-auto flex-1 no-scrollbar">

          {/* Current Vehicle — compact header */}
          <div className={`px-4 py-3 ${isRescue ? 'bg-rose-50' : 'bg-amber-50'}`}>
            <div className="flex items-center justify-between mb-2">
              <div className="flex items-center gap-2">
                <span className="text-base font-black text-slate-900 font-mono"><Blur>{v.plateNumber}</Blur></span>
                <span className="text-[10px] px-1.5 py-0.5 rounded bg-white/80 text-slate-500 font-bold border border-slate-200">{v.vehicleType}</span>
              </div>
              <div className="text-right">
                <span className={`text-lg font-black ${v.completionRate >= 1 ? 'text-emerald-600' : v.completionRate >= 0.5 ? 'text-amber-600' : 'text-rose-600'}`}>
                  {(v.completionRate * 100).toFixed(1)}%
                </span>
              </div>
            </div>

            {/* Key metrics in a single compact row */}
            <div className="flex items-center gap-3 text-[10px] text-slate-500 flex-wrap">
              <span>{v.targetName}</span>
              <span className="text-slate-300">|</span>
              <span>本年已跑 <span className="text-slate-700 font-bold">{fmtKm(v.currentYearMileage)}</span> km</span>
              <span>本年考核 <span className="text-slate-700 font-bold">{fmtKm(v.yearTarget)}</span> km</span>
              <span><MapPin size={9} className="inline -mt-px" /> {v.region}</span>
            </div>
            <div className="flex items-center gap-3 text-[10px] text-slate-500 mt-1">
              <span>客户 <span className="text-slate-700 font-medium"><Blur>{v.customer || '-'}</Blur></span></span>
              <span>日均 <span className="text-slate-700 font-bold">{Math.round(v.customerAvgDaily)}</span> km</span>
            </div>
          </div>

          {/* Reason — one line */}
          <div className="px-4 py-2 bg-blue-50 border-y border-blue-100 text-[11px] text-blue-700 leading-relaxed">
            {s.reason}
          </div>

          {/* Candidates */}
          <div className="px-4 py-3">
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-bold text-slate-700">推荐替换车辆</span>
              <span className="text-[10px] text-slate-400">{s.candidates.length} 辆可选</span>
            </div>

            <div className="space-y-2">
              {s.candidates.map(c => {
                const sent = sentPlates.has(c.plateNumber);
                return (
                  <div key={c.plateNumber} className="border border-slate-150 rounded-xl overflow-hidden">
                    {/* Candidate header row */}
                    <div className="flex items-center justify-between px-3 py-2 bg-slate-50/50">
                      <div className="flex items-center gap-2">
                        <span className="text-xs font-black text-slate-900 font-mono"><Blur>{c.plateNumber}</Blur></span>
                        <span className="text-[9px] text-slate-400">{c.vehicleType}</span>
                        <span className="text-[9px] text-slate-300">{c.targetName || '库存'}</span>
                      </div>
                      {c.canQualifyAfterSwap ? (
                        <span className="text-[9px] font-bold text-emerald-600 flex items-center gap-0.5">
                          <CheckCircle size={10} /> 换后可达标
                        </span>
                      ) : (
                        <span className="text-[9px] font-bold text-amber-500 flex items-center gap-0.5">
                          <AlertTriangle size={10} /> 需关注
                        </span>
                      )}
                    </div>

                    {/* Metrics row — compact inline */}
                    <div className="px-3 py-2 flex items-center gap-0 text-[10px] flex-wrap">
                      <div className="flex-1 min-w-[60px]">
                        <div className="text-slate-400">当前</div>
                        <div className="font-bold text-slate-700">{fmtKm(c.totalMileage)}</div>
                      </div>
                      <div className="flex-1 min-w-[60px]">
                        <div className="text-blue-400">考核</div>
                        <div className="font-bold text-blue-700">{c.yearTarget ? fmtKm(c.yearTarget) : '-'}</div>
                      </div>
                      <div className="flex-1 min-w-[60px]">
                        <div className="text-rose-400">缺口</div>
                        <div className="font-bold text-rose-600">{fmtKm(c.mileageGap)}</div>
                      </div>
                      <div className="flex-1 min-w-[40px]">
                        <div className="text-slate-400">区域</div>
                        <div className="font-bold text-slate-700">{c.region}</div>
                      </div>
                      <div className="flex-1 min-w-[60px]">
                        <div className="text-slate-400">换后</div>
                        <div className={`font-bold ${c.canQualifyAfterSwap ? 'text-emerald-600' : 'text-amber-600'}`}>{fmtKm(c.predictedAfterSwap)}</div>
                      </div>
                    </div>

                    {/* Action */}
                    <div className="px-3 pb-2">
                      <button
                        onClick={() => handleNotify(c)}
                        disabled={sending || sent}
                        className={`w-full flex items-center justify-center gap-1 text-[11px] font-bold py-2 rounded-lg transition-all cursor-pointer ${
                          sent
                            ? 'bg-slate-50 text-slate-400'
                            : 'bg-blue-600 hover:bg-blue-700 text-white active:scale-[0.98]'
                        }`}
                      >
                        {sent ? <><CheckCircle size={12} /> 已发送</> : <><Send size={12} /> 发送替换通知</>}
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="border-t border-slate-100 px-4 py-2.5 flex-shrink-0">
          <button
            onClick={onClose}
            className="w-full py-2 text-xs font-bold text-slate-500 bg-slate-50 hover:bg-slate-100 rounded-lg transition-colors cursor-pointer"
          >
            关闭
          </button>
        </div>
      </motion.div>
    </div>
  );
}
