"use client";

import { Fragment, useEffect, useState } from "react";
import Link from "next/link";
import { ACTIONS, DECISION_QUADRANT, type ActionGroup } from "@/lib/actions";

const STATUS_LABEL: Record<string, string> = {
  PENDING: "Chưa bắt đầu",
  ELIGIBLE: "Đủ điều kiện / Chờ bạn",
  IN_PROGRESS: "Đang thực hiện",
  DONE: "Hoàn tất",
  BLOCKED: "Bị chặn",
};
const STATUS_STYLE: Record<string, string> = {
  PENDING: "bg-slate-100 text-slate-500",
  ELIGIBLE: "bg-sky-100 text-sky-700",
  IN_PROGRESS: "bg-amber-100 text-amber-700",
  DONE: "bg-emerald-100 text-emerald-700",
  BLOCKED: "bg-rose-100 text-rose-700",
};
// Chỉ 4 trạng thái này cho phép đặt thủ công — "Đủ điều kiện" là trạng thái hệ thống TỰ tính
// từ dữ liệu thật (xem lib/workflow.ts), không phải lựa chọn tay.
const MANUAL_STATUSES = ["PENDING", "IN_PROGRESS", "DONE", "BLOCKED"];
const GROUP_LABEL: Record<ActionGroup, string> = {
  INCREASE_INFLOW: "Tăng thu — đưa tiền về nhanh",
  REDUCE_OUTFLOW: "Giảm chi — giữ tiền lại ngay",
  OPTIMIZE: "Tối ưu — giữ dương bền hơn",
};

export default function ProcessPage() {
  const [phases, setPhases] = useState<any[]>([]);
  const [openStep, setOpenStep] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);

  async function load() {
    setLoading(true);
    const res = await fetch("/api/process");
    const json = await res.json();
    setPhases(json.phases);
    setLoading(false);
  }

  useEffect(() => {
    load();
  }, []);

  async function setStatus(stepNumber: number, status: string) {
    await fetch("/api/process", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ stepNumber, status }),
    });
    load();
  }

  return (
    <div>
      <div className="border-b border-slate-100 bg-white px-8 py-5">
        <h1 className="text-2xl font-extrabold text-slate-800">Quy trình quản lý dòng tiền</h1>
        <p className="text-sm text-slate-400">Ma trận 12 hành động — Tác động nhanh — Ít tốn sức | Mục tiêu: dòng tiền dương trong 60 ngày</p>
      </div>

      <div className="flex flex-col gap-8 p-8">
        <div className="card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-slate-50 text-xs uppercase text-slate-400">
              <tr>
                <th className="w-14 px-4 py-3 text-left">STT</th>
                <th className="w-40 px-4 py-3 text-left">Người làm</th>
                <th className="px-4 py-3 text-left">Công việc</th>
                <th className="w-40 px-4 py-3 text-left">Trạng thái</th>
              </tr>
            </thead>
            <tbody>
              {!loading &&
                phases.map((phase) => (
                  <Fragment key={`phase-${phase.phase}`}>
                    <tr className="bg-teal-50/60">
                      <td colSpan={4} className="px-4 py-2 text-xs font-bold text-teal-700">
                        GIAI ĐOẠN {phase.phase} — {phase.title.toUpperCase()} ({phase.dayRange})
                      </td>
                    </tr>
                    {phase.steps.map((step: any) => (
                      <Fragment key={step.stepNumber}>
                        <tr
                          className="cursor-pointer border-t border-slate-50 hover:bg-slate-50"
                          onClick={() => setOpenStep(openStep === step.stepNumber ? null : step.stepNumber)}
                        >
                          <td className="px-4 py-3 font-semibold text-slate-700">{step.stepNumber}</td>
                          <td className="px-4 py-3 text-slate-500">{step.owner}</td>
                          <td className="px-4 py-3 text-slate-700">
                            <div>{step.task}</div>
                            {step.note && <div className="mt-1 text-[11px] text-slate-400">{step.note}</div>}
                            {step.outputHref && step.status !== "PENDING" && (
                              <Link
                                href={step.outputHref}
                                onClick={(e) => e.stopPropagation()}
                                className="mt-1 inline-block text-[11px] font-medium text-teal-600 hover:underline"
                              >
                                {step.outputLabel ?? "Xem đầu ra"} →
                              </Link>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            <span className={`rounded-full px-2.5 py-1 text-[11px] font-medium ${STATUS_STYLE[step.status] ?? STATUS_STYLE.PENDING}`}>
                              {STATUS_LABEL[step.status] ?? step.status}
                            </span>
                          </td>
                        </tr>
                        {openStep === step.stepNumber && (
                          <tr className="border-t border-slate-50 bg-slate-50/60">
                            <td colSpan={4} className="px-4 py-4">
                              <div className="mb-2 text-xs text-slate-500">
                                <span className="font-semibold">Điều kiện chuyển giai đoạn:</span> {phase.exitCondition}
                              </div>
                              <div className="mb-3 text-[11px] text-slate-400">
                                Trạng thái &ldquo;Đủ điều kiện / Chờ bạn&rdquo; do hệ thống tự tính từ dữ liệu thật. Chỉ đặt thủ công khi bạn đã
                                thực sự thực hiện/duyệt bước này ngoài CRM.
                              </div>
                              <div className="flex flex-wrap gap-2">
                                {MANUAL_STATUSES.map((s) => (
                                  <button
                                    key={s}
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      setStatus(step.stepNumber, s);
                                    }}
                                    className={`rounded-lg border px-3 py-1.5 text-xs font-medium ${
                                      step.status === s ? "border-teal-400 bg-teal-500 text-white" : "border-slate-200 text-slate-500 hover:bg-white"
                                    }`}
                                  >
                                    {STATUS_LABEL[s]}
                                  </button>
                                ))}
                              </div>
                            </td>
                          </tr>
                        )}
                      </Fragment>
                    ))}
                  </Fragment>
                ))}
            </tbody>
          </table>
        </div>

        <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
          {(["INCREASE_INFLOW", "REDUCE_OUTFLOW", "OPTIMIZE"] as ActionGroup[]).map((group) => (
            <div key={group} className="card p-5">
              <div className="mb-3 font-bold text-slate-800">{GROUP_LABEL[group]}</div>
              <div className="flex flex-col gap-2">
                {ACTIONS.filter((a) => a.group === group).map((a) => (
                  <div key={a.key} className="rounded-lg border border-slate-100 px-3 py-2 text-xs">
                    <div className="font-semibold text-slate-700">
                      {a.key}. {a.title}
                    </div>
                    <div className="text-slate-400">{a.description}</div>
                    <div className="mt-1 text-[11px] text-teal-600">Agent: {a.agentType} · {a.speedDays} ngày · effort {a.effort}/5</div>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>

        <div className="card p-5">
          <div className="mb-3 font-bold text-slate-800">Ma trận ra quyết định (Tác động × Công sức)</div>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            {Object.entries(DECISION_QUADRANT).map(([key, q]) => (
              <div key={key} className="rounded-xl border border-slate-100 p-4">
                <div className="font-semibold text-slate-700">{q.label}</div>
                <div className="text-xs text-slate-400">Tác động: {q.impact} · Công sức: {q.effort}</div>
                <div className="mt-1 text-xs text-teal-600">
                  VD: {q.examples.map((k) => ACTIONS.find((a) => a.key === k)?.title).join(", ")}
                </div>
              </div>
            ))}
          </div>
          <div className="mt-4 rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-700">
            ⭐ Nguyên tắc vàng: ưu tiên việc đưa tiền về nhanh, giữ tiền lại ngay, và chỉ mở rộng chi khi dòng tiền đã an toàn.
          </div>
        </div>
      </div>
    </div>
  );
}
