import { useState } from "react";
import { Link } from "react-router-dom";
import type { Opportunity, OpportunityRemovalReason } from "../../domain/types";
import { Badge, Button, Select, Textarea } from "../ui";
import { formatTimeAgo } from "../../lib/time";

const reasonLabels: Record<Exclude<OpportunityRemovalReason, "legacy_unknown">, string> = {
  pain_mismatch: "不符合產品痛點",
  provider_or_ad: "供應商／廣告貼文",
  stale: "需求已過期",
  already_solved: "對方已解決",
  duplicate: "重複商機",
  other: "其他原因",
};

type Props = {
  opportunity: Opportunity;
  onOpen: (opportunity: Opportunity) => void;
  onAccept: (opportunity: Opportunity) => void;
  onComplete: (opportunity: Opportunity) => void;
  onRemove: (opportunity: Opportunity, input: { reason: OpportunityRemovalReason; note?: string }) => void;
  onRestore: (opportunity: Opportunity) => void;
  busy?: boolean;
};

export function OpportunityInboxCard({ opportunity, onOpen, onAccept, onComplete, onRemove, onRestore, busy = false }: Props) {
  const [removeOpen, setRemoveOpen] = useState(false);
  const [reason, setReason] = useState<OpportunityRemovalReason>("pain_mismatch");
  const [note, setNote] = useState("");
  const reviewState = opportunity.review_state ?? (opportunity.status === "accepted" ? "completed" : opportunity.status === "dismissed" ? "removed" : "pending");
  const pending = reviewState === "pending";
  const score = opportunity.priority_score ?? opportunity.intent_score;
  const evidence = opportunity.demand_evidence?.[0] ?? opportunity.product_matches?.[0]?.reasons?.[0]?.reason;
  const accepted = opportunity.status === "accepted" || Boolean(opportunity.contact_id);
  const priorityLabel = opportunity.priority_band === "high"
    ? "優先跟進"
    : opportunity.priority_band === "review"
      ? "值得確認"
      : opportunity.priority_band === "low"
        ? "低順位"
        : opportunity.intent_band === "high"
          ? "高意向"
          : opportunity.intent_band === "mid"
            ? "中意向"
            : "低意向";

  function submitRemove() {
    if (reason === "other" && !note.trim()) return;
    onRemove(opportunity, { reason, note: note.trim() || undefined });
    setRemoveOpen(false);
    setNote("");
  }

  return (
    <article className={`hb-opp-card hb-opp-card--${opportunity.intent_band}`} data-testid={`opportunity-card-${opportunity.id}`}>
      <div className="hb-opp-card__meta">
        <Badge tone={opportunity.priority_band === "high" || opportunity.intent_band === "high" ? "success" : opportunity.priority_band === "review" || opportunity.intent_band === "mid" ? "warning" : "neutral"}>
          {priorityLabel} · {score}
        </Badge>
        {opportunity.primary_product_label ? <Badge tone="brand">適合產品 · {opportunity.primary_product_label}</Badge> : <Badge tone="neutral">尚未配對產品</Badge>}
        <span>需求意向 {opportunity.intent_score} · {formatTimeAgo(opportunity.posted_at)}</span>
      </div>
      <p className="hb-opp-card__text">{opportunity.text}</p>
      {evidence ? <p className="hb-opp-card__evidence"><strong>為什麼推薦：</strong>{evidence}</p> : null}
      <div className="hb-opp-card__source">
        <span>@{opportunity.author_handle || "未知作者"}</span>
        <a href={opportunity.permalink} target="_blank" rel="noreferrer">查看 Threads 原文</a>
      </div>
      <div className="hb-opp-card__actions" aria-label="商機操作">
        {(pending || reviewState === "completed") && !accepted ? (
          <Button type="button" variant="primary" disabled={busy} onClick={() => onAccept(opportunity)}>
            {busy ? "處理中…" : "加入名單並追蹤"}
          </Button>
        ) : null}
        {pending ? <Button type="button" variant="secondary" disabled={busy} onClick={() => onComplete(opportunity)}>只標示已處理</Button> : null}
        {pending ? <Button type="button" variant="danger" disabled={busy} onClick={() => setRemoveOpen((value) => !value)}>不適合</Button> : null}
        <Button type="button" variant="ghost" onClick={() => onOpen(opportunity)}>看完整判定</Button>
        {reviewState === "removed" ? <Button type="button" variant="secondary" disabled={busy} onClick={() => onRestore(opportunity)}>還原到待處理</Button> : null}
        {reviewState === "completed" && accepted && opportunity.contact_id ? (
          <Link className="hb-btn hb-btn--secondary" to={`/app/crm?contact=${encodeURIComponent(opportunity.contact_id)}`}>前往名單</Link>
        ) : null}
        {reviewState === "completed" ? <Badge tone="success">{accepted ? "已加入名單" : "已處理"}</Badge> : null}
      </div>
      {removeOpen ? (
        <div className="hb-opp-card__remove-form" aria-label="標示為不適合">
          <strong>為什麼不適合？</strong>
          <p className="hb-field__hint">選原因後，這筆會移到「已移除」且不會再次出現在待處理。這個動作不扣點。</p>
          <Select name={`remove-reason-${opportunity.id}`} label="原因" value={reason} onChange={(event) => setReason(event.target.value as OpportunityRemovalReason)}>
            {(Object.keys(reasonLabels) as Array<Exclude<OpportunityRemovalReason, "legacy_unknown">>).map((key) => <option key={key} value={key}>{reasonLabels[key]}</option>)}
          </Select>
          {reason === "other" ? <Textarea name={`remove-note-${opportunity.id}`} label="補充說明" value={note} onChange={(event) => setNote(event.target.value)} /> : null}
          {reason === "duplicate" ? <p className="hb-field__hint">詳情中可指定要保留的原始商機。</p> : null}
          <div className="hb-opp-card__actions">
            <Button type="button" variant="danger" disabled={busy || (reason === "other" && !note.trim())} onClick={submitRemove}>確認不適合</Button>
            <Button type="button" variant="ghost" onClick={() => setRemoveOpen(false)}>取消</Button>
          </div>
        </div>
      ) : null}
    </article>
  );
}
