"use client";

/**
 * Home board — activity KPIs (no Sale), queues, performance, DWE, lead bank.
 */

import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { api } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { downloadAuthenticated } from "@/lib/download";

type Tile = { key: string; label: string; count: number; color: string; href: string };
type PerfRow = { region: string; target: number; achieved: number; achievement: number; position: number | string };
type DweRow = { user_id: number; name: string; work_plan: string; efficiency: number; export_url: string };
type TypeRow = { key: string; label: string; total: number; color: string };

type Summary = {
  greeting_name: string;
  role: string | null;
  quarter?: { name: string; date_from: string; date_to: string } | null;
  activity_tiles: Tile[];
  quick_links: Tile[];
  performance: PerfRow[];
  daily_work_efficiency: DweRow[];
  lead_bank: { total: number; leads: number; whatsapp: number; today: number };
  total_leads: { total: number; by_type: TypeRow[] };
};

function formatDay(value?: string | null) {
  if (!value) return "";
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return String(value).slice(0, 10);
  return d.toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
}

export default function DashboardPage() {
  const { user } = useAuth();
  const [data, setData] = useState<Summary | null>(null);
  const [branchId, setBranchId] = useState("");
  const [error, setError] = useState("");
  const [dweLimit, setDweLimit] = useState(8);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await api<{ data: Summary }>("/dashboard/summary", {
          params: branchId ? { branch_id: branchId } : undefined,
        });
        if (!cancelled) setData(res.data);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : "Failed to load");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [branchId]);

  const showTeamWidgets = user?.role !== "sales-person";

  // Sale tile removed — filter any leftover payload just in case
  const activityTiles = useMemo(
    () => (data?.activity_tiles || []).filter((t) => t.key !== "sale"),
    [data?.activity_tiles],
  );
  const queueTiles = data?.quick_links || [];

  const quarterLabel = data?.quarter
    ? `${data.quarter.name} · ${formatDay(data.quarter.date_from)} → ${formatDay(data.quarter.date_to)}`
    : "Lead operations dashboard";

  return (
    <AppShell>
      <div className="ps-page dash-home rise">
        <header className="ps-page-header">
          <div>
            <div className="dash-greeting">{user?.role_label || user?.role || "Workspace"}</div>
            <h1 className="ps-page-title">{data?.greeting_name || user?.name}</h1>
            <p className="ps-page-sub">{quarterLabel}</p>
          </div>
          <div style={{ display: "flex", gap: "0.55rem", flexWrap: "wrap", alignItems: "center" }}>
            {user?.capabilities.can_filter_branch ? (
              <select className="ps-select" style={{ maxWidth: 220 }} value={branchId} onChange={(e) => setBranchId(e.target.value)}>
                <option value="">All allowed branches</option>
                {user.headed_branches.map((b) => (
                  <option key={b.id} value={b.id}>
                    {b.name}
                  </option>
                ))}
              </select>
            ) : null}
            <Link className="ps-btn ps-btn-primary" href="/leads/new">
              Add Lead
            </Link>
            <Link className="ps-btn ps-btn-ghost" href="/reports">
              Reports
            </Link>
          </div>
        </header>

        {error ? <div className="alloc-alert alloc-alert-err">{error}</div> : null}

        {/* Activity KPIs */}
        <div>
          <p className="dash-section-label">Activity</p>
          <section className="dash-tiles rise-stagger">
            {activityTiles.map((t, i) => (
              <Link
                key={t.key}
                href={t.href}
                className="dash-tile"
                style={{ ["--tile-accent" as string]: t.color, animationDelay: `${i * 50}ms` }}
              >
                <div className="dash-tile-count">{t.count}</div>
                <div className="dash-tile-label">{t.label}</div>
              </Link>
            ))}
          </section>
        </div>

        {/* Queue / action tiles */}
        <div>
          <p className="dash-section-label">Queues</p>
          <section className="dash-tiles rise-stagger">
            {queueTiles.map((t, i) => (
              <Link
                key={t.key}
                href={t.href}
                className="dash-tile"
                style={{
                  ["--tile-accent" as string]: t.color,
                  animationDelay: `${(activityTiles.length + i) * 45}ms`,
                }}
              >
                <div className="dash-tile-count">{t.count}</div>
                <div className="dash-tile-label">{t.label}</div>
              </Link>
            ))}
          </section>
        </div>

        {/* 3-column board */}
        <section className="dash-grid">
          {showTeamWidgets ? (
            <div className="ps-card ps-card-static dash-panel" style={{ animationDelay: "0.12s" }}>
              <h3 className="dash-panel-title">Performance Comparison</h3>
              <div style={{ overflowX: "auto" }}>
                <table className="ps-table dash-table">
                  <thead>
                    <tr>
                      <th>Region</th>
                      <th className="center">Target</th>
                      <th className="center">Achieved</th>
                      <th className="center">Achievement</th>
                      <th className="center">Position</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data?.performance || []).map((row) => (
                      <tr key={row.region} className={row.region === "Total" ? "dash-total-row" : undefined}>
                        <td>{row.region}</td>
                        <td className="center">{row.target}</td>
                        <td className="center">{row.achieved}</td>
                        <td className="center">{Number(row.achievement).toFixed(2)}%</td>
                        <td className="center">{row.position || "—"}</td>
                      </tr>
                    ))}
                    {!data?.performance?.length ? (
                      <tr>
                        <td colSpan={5} style={{ color: "var(--muted)", textAlign: "center" }}>
                          No performance data
                        </td>
                      </tr>
                    ) : null}
                  </tbody>
                </table>
              </div>
            </div>
          ) : null}

          {showTeamWidgets ? (
            <div className="ps-card ps-card-static dash-panel" style={{ animationDelay: "0.18s" }}>
              <h3 className="dash-panel-title">Daily Work Efficiency</h3>
              <div style={{ overflowX: "auto" }}>
                <table className="ps-table dash-table">
                  <thead>
                    <tr>
                      <th>Sales Person</th>
                      <th className="center">Work Plan</th>
                      <th className="center">Efficiency</th>
                      <th className="center">Report</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(data?.daily_work_efficiency || []).slice(0, dweLimit).map((row) => (
                      <tr key={row.user_id}>
                        <td>
                          <div className="dash-person">
                            <span className="dash-avatar">{row.name.slice(0, 1).toUpperCase()}</span>
                            <span>{row.name}</span>
                          </div>
                        </td>
                        <td className="center" style={{ color: row.work_plan === "Submitted" ? "var(--brand-mid)" : "var(--muted)" }}>
                          {row.work_plan}
                        </td>
                        <td className="center">
                          <strong style={{ color: "#16a34a" }}>{row.efficiency}%</strong>
                        </td>
                        <td className="center">
                          <button
                            type="button"
                            className="dash-export-btn"
                            title="Download report"
                            onClick={() => downloadAuthenticated(row.export_url, `dwe-${row.user_id}.csv`)}
                          >
                            ↓
                          </button>
                        </td>
                      </tr>
                    ))}
                    {!data?.daily_work_efficiency?.length ? (
                      <tr>
                        <td colSpan={4} style={{ color: "var(--muted)", textAlign: "center" }}>
                          No sales persons in scope
                        </td>
                      </tr>
                    ) : null}
                  </tbody>
                </table>
              </div>
              {(data?.daily_work_efficiency?.length || 0) > dweLimit ? (
                <button type="button" className="dash-more" onClick={() => setDweLimit((n) => n + 10)}>
                  View More ▾
                </button>
              ) : null}
            </div>
          ) : null}

          <div className="dash-right-col">
            <div className="ps-card ps-card-static dash-panel" style={{ animationDelay: "0.22s" }}>
              <h3 className="dash-panel-title">Lead Bank</h3>
              <div className="dash-bank-total">
                {data?.lead_bank.total ?? "—"}
                <span className="dash-bank-today">+{data?.lead_bank.today ?? 0} today</span>
              </div>
              <div className="dash-bank-actions">
                <Link href="/lead-bank" className="dash-bank-btn dash-bank-btn-blue">
                  Leads ({data?.lead_bank.leads ?? 0})
                </Link>
                <Link href="/lead-bank?channel=whatsapp" className="dash-bank-btn dash-bank-btn-green">
                  WhatsApp ({data?.lead_bank.whatsapp ?? 0})
                </Link>
              </div>
            </div>

            <div className="ps-card ps-card-static dash-panel" style={{ animationDelay: "0.28s" }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: "0.5rem" }}>
                <h3 className="dash-panel-title" style={{ margin: 0, border: 0, padding: 0 }}>
                  Total Leads
                </h3>
                <Link href="/leads" className="dash-total-badge">
                  {data?.total_leads.total ?? 0} Total
                </Link>
              </div>
              <ul className="dash-type-list">
                {(data?.total_leads.by_type || []).map((row) => (
                  <li key={row.key}>
                    <Link
                      href={`/leads?project_type=${row.key}`}
                      className="dash-type-row"
                      style={{ ["--type-accent" as string]: row.color }}
                    >
                      <span>{row.label}</span>
                      <strong>{row.total}</strong>
                    </Link>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </section>
      </div>
    </AppShell>
  );
}
