"use client";

import { useCallback, useEffect, useState } from "react";
import { TopBar, type Mode } from "@/components/TopBar";
import { KpiCard } from "@/components/KpiCard";
import { QuickInputForm } from "@/components/QuickInputForm";
import { AllocationDonut } from "@/components/AllocationDonut";
import { CashFlowChart } from "@/components/CashFlowChart";
import { SuggestionsPanel } from "@/components/SuggestionsPanel";
import { AlertsPanel } from "@/components/AlertsPanel";
import { DebtCalendarPanel } from "@/components/DebtCalendarPanel";
import { TargetProgressPanel } from "@/components/TargetProgressPanel";
import { CashHealthBadge } from "@/components/CashHealthBadge";
import { ResultsPanel } from "@/components/ResultsPanel";
import { formatVNDCompact } from "@/lib/finance";
import { DEBT_SPECIFIC_LEVERS } from "@/lib/actions";
import { ICONS } from "@/lib/icons";
import Link from "next/link";

function currentPeriod() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`;
}

export default function DashboardPage() {
  const [mode, setMode] = useState<Mode>("CONSOLIDATED");
  const [period, setPeriod] = useState(currentPeriod());
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [toast, setToast] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch(`/api/dashboard?mode=${mode}&period=${period}`);
    const json = await res.json();
    setData(json);
    setLoading(false);
  }, [mode, period]);

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

  async function launchAction(key: number) {
    if (DEBT_SPECIFIC_LEVERS[key]) {
      // Đòn bẩy gắn với từng khoản nợ thật -> sinh 1 việc/khoản nợ (tên, số tiền thật), không gộp.
      const res = await fetch("/api/actions/generate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ actionKey: key, scope: mode }),
      });
      const json = await res.json();
      setToast(json.message);
    } else {
      // Lấy đúng expectedAmount/confidence rule-based đã tính cho gợi ý này — tránh lỗi cũ: tạo
      // ActionItem với expectedAmount=0 dù hệ thống đã tính được tác động tài chính thật.
      const suggestion = data?.suggestions?.find((s: any) => s.key === key);
      await fetch("/api/actions", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ actionKey: key, scope: mode, expectedAmount: suggestion?.cashImpact, confidence: suggestion?.confidence }),
      });
      setToast("Đã tạo nhiệm vụ — xem chi tiết tại Hành động & Agent.");
    }
    setTimeout(() => setToast(null), 3500);
  }

  const quickInputScope = mode === "BUSINESS" ? "BUSINESS" : "PERSONAL";

  function ZoneLabel({ letter, title }: { letter: string; title: string }) {
    return (
      <div className="mb-1 flex items-center gap-2">
        <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded bg-slate-700 text-[10px] font-bold text-white">{letter}</span>
        <span className="text-xs font-semibold uppercase tracking-wide text-slate-400">{title}</span>
      </div>
    );
  }

  return (
    <div>
      <TopBar
        mode={mode}
        onModeChange={setMode}
        period={period}
        onPeriodChange={setPeriod}
        title="CRM Dòng Tiền — Tổng quan"
        subtitle="Chỉ cần nhập số — Tự động phân bổ — Tổng quan dòng tiền"
      />
      {toast && <div className="mx-8 mt-4 rounded-lg bg-teal-500 px-4 py-2 text-sm text-white shadow">{toast}</div>}

      <div className="p-8">
        {loading || !data ? (
          <div className="text-sm text-slate-400">Đang tải dữ liệu...</div>
        ) : (
          <div className="flex flex-col gap-8">
            <section>
              <ZoneLabel letter="A" title="Trạng thái dòng tiền tổng quan" />
              <div className="flex flex-col gap-4">
                <CashHealthBadge health={data.cashHealth} />
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
                  <KpiCard icon={ICONS.inflow} label="Tổng thu thực nhận" value={data.kpis.totalInflow} changePct={data.kpis.totalInflowChangePct} tone={data.kpis.totalInflowChangePct >= 0 ? "up" : "down"} />
                  <KpiCard icon={ICONS.outflow} label="Tổng chi thực chi" value={data.kpis.totalOutflow} changePct={data.kpis.totalOutflowChangePct} tone={data.kpis.totalOutflowChangePct <= 0 ? "up" : "down"} />
                  <KpiCard icon={ICONS.wallet} label="Dòng tiền ròng" value={data.kpis.netCashFlow} changePct={data.kpis.netCashFlowChangePct} tone={data.kpis.netCashFlow >= 0 ? "up" : "down"} signed />
                  <KpiCard icon={ICONS.bank} label="Số dư khả dụng" value={data.kpis.balance} valueOverride={data.hasBaseline ? undefined : "Chưa đủ dữ liệu"} />
                  <KpiCard icon={ICONS.receivable} label="Công nợ phải thu" value={data.kpis.receivableTotal} />
                  <KpiCard icon={ICONS.payable} label="Công nợ phải trả" value={data.kpis.payableTotal} />
                  <KpiCard
                    icon={ICONS.runway}
                    label="Runway (ngày hoạt động)"
                    value={0}
                    valueOverride={!data.hasBaseline ? "Chưa đủ dữ liệu" : data.kpis.runwayDays === null ? "Không giới hạn" : `${data.kpis.runwayDays} ngày`}
                  />
                  <KpiCard icon={ICONS.forecast} label="Dự báo 30 ngày tới" value={data.kpis.forecast30} signed valueOverride={data.hasBaseline ? undefined : "Chưa đủ dữ liệu"} />
                </div>
              </div>
            </section>

            <section>
              <ZoneLabel letter="B" title="Nhập số & phân bổ thông minh" />
              <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                <div className="lg:col-span-2">
                  <QuickInputForm scope={quickInputScope} period={period} onSaved={load} />
                </div>
                <div className="card p-5">
                  <div className="mb-1 flex items-center gap-2 font-bold text-slate-800">
                    <ICONS.allocation size={18} strokeWidth={1.75} className="text-slate-400" /> Phân bổ thông minh
                  </div>
                  <AllocationDonut data={data.allocation} centerLabel={formatVNDCompact(data.allocationTotal)} />
                </div>
              </div>
            </section>

            <section>
              <ZoneLabel letter="C" title="Biểu đồ dòng tiền" />
              <div className="card p-5">
                <div className="mb-1 flex items-center gap-2 font-bold text-slate-800">
                  <ICONS.chart size={18} strokeWidth={1.75} className="text-slate-400" /> Biểu đồ dòng tiền (6 tháng gần nhất)
                </div>
                <CashFlowChart history={data.history} />
              </div>
            </section>

            <section>
              <ZoneLabel letter="D" title="Gợi ý hành động AI (rule-based)" />
              <SuggestionsPanel suggestions={data.suggestions} onLaunch={launchAction} />
            </section>

            <section>
              <ZoneLabel letter="E" title="Cảnh báo, công nợ & mục tiêu" />
              <div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
                <AlertsPanel alerts={data.alerts} />
                <DebtCalendarPanel debts={data.upcomingDebts} />
                <TargetProgressPanel pct={data.kpis.targetProgressPct} daysLeft={data.kpis.targetDaysLeft} />
              </div>
            </section>

            <section>
              <ZoneLabel letter="F" title="Kết quả thực tế đã xác minh" />
              <ResultsPanel data={data.results} onSaved={load} />
            </section>

            <Link href="/quy-trinh" className="card flex items-center justify-between p-5 hover:border-teal-200">
              <div className="flex items-center gap-2 font-bold text-slate-800">
                <ICONS.process size={18} strokeWidth={1.75} className="text-slate-400" /> Quy trình 6 giai đoạn đang chạy — bước tiếp theo: #{data.nextProcessStep ?? "Hoàn tất"}
              </div>
              <span className="flex items-center gap-1 text-sm font-medium text-teal-600">
                Xem chi tiết <ICONS.chevronRight size={16} strokeWidth={1.75} />
              </span>
            </Link>
          </div>
        )}
      </div>
    </div>
  );
}
