'use client';

import { Phone, PhoneOff, Mic, MicOff } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useTwilioCall } from './use-twilio-call';

const fmt = (s: number) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;

/**
 * CallWidget — 详情页网页点击拨号(Twilio Voice）。
 * 空闲显示"拨打";呼叫/通话中显示状态 + 计时 + 静音/挂断。
 */
export function CallWidget({ planId }: { planId: string }) {
  const { state, error, muted, seconds, dial, hangup, toggleMute, reset } = useTwilioCall();

  if (state === 'idle') {
    return (
      <button
        onClick={() => dial(planId)}
        className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-teal-600 text-white text-[12px] font-medium hover:bg-teal-700 transition-colors"
      >
        <Phone className="w-3.5 h-3.5" />
        拨打
      </button>
    );
  }

  if (state === 'error' || state === 'ended') {
    return (
      <div className="inline-flex items-center gap-2 text-[11px]">
        <span className={cn(state === 'error' ? 'text-rose-600' : 'text-slate-500')}>
          {state === 'error' ? (error ?? '呼叫失败') : `已结束 ${fmt(seconds)}`}
        </span>
        <button
          onClick={() => reset()}
          className="inline-flex items-center gap-1 px-2.5 py-1 rounded-md border border-teal-300 text-teal-700 text-[11px] hover:bg-teal-50"
        >
          <Phone className="w-3 h-3" />
          重拨
        </button>
      </div>
    );
  }

  // connecting / ringing / in_call
  const label = state === 'in_call' ? fmt(seconds) : state === 'ringing' ? '响铃中…' : '呼叫中…';
  return (
    <div className="inline-flex items-center gap-1.5">
      <span className="inline-flex items-center gap-1.5 px-2 py-1 rounded-md bg-emerald-50 text-emerald-700 text-[11px] font-medium tabular-nums">
        <span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
        {label}
      </span>
      {state === 'in_call' && (
        <button
          onClick={toggleMute}
          title={muted ? '取消静音' : '静音'}
          className={cn(
            'inline-flex items-center justify-center w-7 h-7 rounded-md border transition-colors',
            muted ? 'border-amber-300 text-amber-600 bg-amber-50' : 'border-slate-200 text-slate-500 hover:bg-slate-50',
          )}
        >
          {muted ? <MicOff className="w-3.5 h-3.5" /> : <Mic className="w-3.5 h-3.5" />}
        </button>
      )}
      <button
        onClick={hangup}
        title="挂断"
        className="inline-flex items-center justify-center w-7 h-7 rounded-md bg-rose-600 text-white hover:bg-rose-700 transition-colors"
      >
        <PhoneOff className="w-3.5 h-3.5" />
      </button>
    </div>
  );
}
