"use client";

import { useEffect, useState } from "react";
import { getWorkflowRequests } from "@/services/workflow";
import { getAudit } from "@/services/audit";
import { useApiStore } from "@/store/uiStore";
import { t } from "@/lib/locale";
import { useLocaleStore } from "@/store/uiStore";
import PageHeader from "@/components/ui/PageHeader";
import Spinner from "@/components/ui/Spinner";

type DashboardSummary = {
  pendingWorkflows: number;
  totalAudits: number;
  recentAuditCount: number;
};

export default function DashboardPage() {
  const [summary, setSummary] = useState<DashboardSummary | null>(null);
  const [loading, setLoading] = useState(false);
  const addToast = useApiStore((s) => s.addToast);
  const locale = useLocaleStore((s) => s.locale);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const [pending, audits] = await Promise.all([
          getWorkflowRequests({ status: "PENDING", limit: 200 }),
          getAudit(50)
        ]);
        setSummary({
          pendingWorkflows: pending.length,
          totalAudits: audits.length,
          recentAuditCount: audits.slice(0, 5).length
        });
      } catch (error) {
        addToast("Failed to load dashboard summary", "error");
      } finally {
        setLoading(false);
      }
    };
    load();
  }, [addToast]);

  return (
    <main className="vstack gap-3">
      <PageHeader
        title={t("dashboard", locale)}
        description={t("checkerWorkload", locale)}
        breadcrumb={[
          { label: t("dashboard", locale), href: "/dashboard" }
        ]}
      />
      {loading && <Spinner label={t("loading", locale)} />}
      <div className="row g-3">
        <section className="col-12 col-md-4">
          <div className="card page-card">
            <div className="card-body">
              <h3 className="card-title h5">{t("pendingWorkflows", locale)}</h3>
              <p className="display-6 fw-bold">{summary?.pendingWorkflows ?? "--"}</p>
            </div>
          </div>
        </section>
        <section className="col-12 col-md-4">
          <div className="card page-card">
            <div className="card-body">
              <h3 className="card-title h5">{t("auditSnapshots", locale)}</h3>
              <p className="display-6 fw-bold">{summary?.totalAudits ?? "--"}</p>
            </div>
          </div>
        </section>
        <section className="col-12 col-md-4">
          <div className="card page-card">
            <div className="card-body">
              <h3 className="card-title h5">{t("recentAudits", locale)}</h3>
              <p className="display-6 fw-bold">{summary?.recentAuditCount ?? "--"}</p>
            </div>
          </div>
        </section>
      </div>
    </main>
  );
}
