"use client";

/**
 * Hi-leads Lead Allocation board parity:
 * tabs (Unallocated / Lead Bank / Re-Allocation) + filters + checkbox table
 * + right rail "Allocate To" bulk action.
 */

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

type QueueKey = "unallocated" | "lead_bank" | "reallocation";

type LeadRow = {
  id: number;
  enquirer_name: string;
  email?: string;
  phone_code?: string;
  mobile: string;
  lead_date?: string;
  source?: string;
  preferred_project?: string;
  attended_by_name?: string;
  branch?: string;
};

type Opt = { id: number; name?: string; project_name?: string };
type Person = { id: number; name: string };

const QUEUES: { key: QueueKey; label: string }[] = [
  { key: "unallocated", label: "Unallocated" },
  { key: "lead_bank", label: "Lead Bank Allocation" },
  { key: "reallocation", label: "Re-Allocation" },
];

const emptyFilters = {
  s_project: "",
  s_source: "",
  s_from: "",
  s_to: "",
  phone_code: "",
  search: "",
};

export default function AllocationPage() {
  const { user } = useAuth();
  const [queue, setQueue] = useState<QueueKey>("unallocated");
  const [rows, setRows] = useState<LeadRow[]>([]);
  const [meta, setMeta] = useState({ total: 0, current_page: 1, last_page: 1 });
  const [page, setPage] = useState(1);
  const [draft, setDraft] = useState(emptyFilters);
  const [applied, setApplied] = useState(emptyFilters);
  const [projects, setProjects] = useState<Opt[]>([]);
  const [sources, setSources] = useState<Opt[]>([]);
  const [people, setPeople] = useState<Person[]>([]);
  const [checked, setChecked] = useState<number[]>([]);
  const [allocateTo, setAllocateTo] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);

  const canAllocate = useMemo(
    () =>
      !!user &&
      ["super-admin", "sales-head", "branch-head", "team-leader"].includes(user.role || ""),
    [user],
  );

  useEffect(() => {
    Promise.all([
      api<{ data: Opt[] }>("/masters/preferred-projects"),
      api<{ data: Opt[] }>("/masters/sources"),
      api<{ data: { sales_persons: Person[]; team_leaders?: Person[] } }>("/users/filter-options"),
    ])
      .then(([p, s, u]) => {
        setProjects(p.data);
        setSources(s.data);
        // Allocate-to: sales persons (TL can assign their team; heads see branch roster)
        setPeople(u.data.sales_persons || []);
      })
      .catch(() => undefined);
  }, []);

  const load = useCallback(async () => {
    setError("");
    try {
      const res = await api<{ data: LeadRow[]; meta: typeof meta }>("/allocation", {
        params: {
          queue,
          page,
          per_page: 25,
          s_project: applied.s_project || undefined,
          s_source: applied.s_source || undefined,
          s_from: applied.s_from || undefined,
          s_to: applied.s_to || undefined,
          phone_code: applied.phone_code || undefined,
          search: applied.search || undefined,
        },
      });
      setRows(res.data);
      setMeta(res.meta);
      setChecked([]);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load allocation queue");
    }
  }, [queue, page, applied]);

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

  function setDraftField<K extends keyof typeof emptyFilters>(key: K, value: (typeof emptyFilters)[K]) {
    setDraft((d) => ({ ...d, [key]: value }));
  }

  function applyFilters() {
    setPage(1);
    setApplied({ ...draft });
  }

  function clearFilters() {
    setDraft(emptyFilters);
    setApplied(emptyFilters);
    setPage(1);
  }

  function toggleAll(on: boolean) {
    setChecked(on ? rows.map((r) => r.id) : []);
  }

  function toggleOne(id: number) {
    setChecked((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]));
  }

  async function bulkAllocate() {
    if (!allocateTo) {
      setError("Please select Allocate To");
      return;
    }
    if (!checked.length) {
      setError("Please select at least one lead");
      return;
    }
    setBusy(true);
    setError("");
    setMessage("");
    try {
      const res = await api<{ message: string; allocated: number }>("/allocation/bulk", {
        method: "POST",
        body: { lead_ids: checked, attended_by: Number(allocateTo) },
      });
      setMessage(res.message || `Allocated ${res.allocated} lead(s)`);
      await load();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Allocate failed");
    } finally {
      setBusy(false);
    }
  }

  if (user && !canAllocate) {
    return (
      <AppShell>
        <div className="ps-card" style={{ padding: "1.2rem" }}>
          <h1 style={{ marginTop: 0, fontFamily: "var(--font-display)" }}>Allocation</h1>
          <p style={{ color: "var(--muted)" }}>Your role cannot allocate leads. Ask your team leader / branch head.</p>
        </div>
      </AppShell>
    );
  }

  return (
    <AppShell>
      <div className="rise alloc-page" style={{ display: "grid", gap: "1rem" }}>
        <div style={{ display: "flex", justifyContent: "space-between", gap: "1rem", flexWrap: "wrap", alignItems: "end" }}>
          <div>
            <h1 style={{ margin: 0, fontFamily: "var(--font-display)" }}>Lead Allocation</h1>
            <p style={{ margin: "0.3rem 0 0", color: "var(--muted)" }}>
              Same flow as hi-leads · select leads → Allocate To → Allocate
            </p>
          </div>
          <span style={{ color: "var(--muted)", fontSize: "0.9rem" }}>{meta.total} in queue</span>
        </div>

        {/* Queue tabs */}
        <div style={{ display: "flex", flexWrap: "wrap", gap: "0.5rem" }}>
          {QUEUES.map((q) => (
            <button
              key={q.key}
              type="button"
              className={`ps-btn ${queue === q.key ? "ps-btn-primary" : "ps-btn-ghost"}`}
              onClick={() => {
                setQueue(q.key);
                setPage(1);
                setChecked([]);
              }}
            >
              {q.label}
            </button>
          ))}
        </div>

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

        <div className="alloc-layout">
          {/* Main list */}
          <div className="ps-card" style={{ padding: "1rem", display: "grid", gap: "0.85rem", minWidth: 0 }}>
            {/* Filters — project / source / dates */}
            <div className="alloc-filters">
              <select className="ps-select" value={draft.s_project} onChange={(e) => setDraftField("s_project", e.target.value)}>
                <option value="">Project</option>
                {projects.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.project_name || p.name}
                  </option>
                ))}
              </select>
              <select className="ps-select" value={draft.s_source} onChange={(e) => setDraftField("s_source", e.target.value)}>
                <option value="">Source</option>
                {sources.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.name}
                  </option>
                ))}
              </select>
              {user?.role === "sales-head" || user?.role === "super-admin" ? (
                <input
                  className="ps-input"
                  placeholder="Country code"
                  value={draft.phone_code}
                  onChange={(e) => setDraftField("phone_code", e.target.value)}
                />
              ) : null}
              <input className="ps-input" type="date" value={draft.s_from} onChange={(e) => setDraftField("s_from", e.target.value)} />
              <input className="ps-input" type="date" value={draft.s_to} onChange={(e) => setDraftField("s_to", e.target.value)} />
              <input
                className="ps-input"
                placeholder="Search name / mobile"
                value={draft.search}
                onChange={(e) => setDraftField("search", e.target.value)}
              />
              <button type="button" className="ps-btn ps-btn-primary" onClick={applyFilters}>
                Search
              </button>
              <button type="button" className="ps-btn ps-btn-ghost" onClick={clearFilters}>
                Clear
              </button>
            </div>

            <div style={{ overflowX: "auto" }}>
              <table className="ps-table">
                <thead>
                  <tr>
                    <th style={{ width: 42 }}>
                      <input
                        type="checkbox"
                        checked={rows.length > 0 && checked.length === rows.length}
                        onChange={(e) => toggleAll(e.target.checked)}
                        aria-label="Select all"
                      />
                    </th>
                    <th>Name of Lead</th>
                    <th>Project</th>
                    <th>Email ID</th>
                    <th>Mobile No.</th>
                    <th>Source</th>
                    {queue === "reallocation" ? <th>Current SP</th> : null}
                    <th>Action</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((r) => (
                    <tr key={r.id}>
                      <td>
                        <input
                          type="checkbox"
                          checked={checked.includes(r.id)}
                          onChange={() => toggleOne(r.id)}
                          aria-label={`Select ${r.enquirer_name}`}
                        />
                      </td>
                      <td>
                        <div style={{ fontWeight: 600 }}>{r.enquirer_name}</div>
                        <div style={{ fontSize: "0.8rem", color: "var(--muted)" }}>{r.lead_date || "—"}</div>
                      </td>
                      <td>{r.preferred_project || "—"}</td>
                      <td>{r.email || "—"}</td>
                      <td>
                        {r.phone_code ? `+${r.phone_code} ` : ""}
                        {r.mobile}
                      </td>
                      <td>{r.source || "—"}</td>
                      {queue === "reallocation" ? <td>{r.attended_by_name || "—"}</td> : null}
                      <td>
                        <Link className="ps-btn ps-btn-ghost" href={`/leads/${r.id}`} style={{ padding: "0.35rem 0.65rem" }}>
                          View
                        </Link>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {!rows.length ? (
                <p style={{ padding: "1.2rem", color: "var(--muted)", textAlign: "center" }}>
                  No leads in this allocation queue.
                </p>
              ) : null}
            </div>

            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: "0.5rem" }}>
              <span style={{ color: "var(--muted)", fontSize: "0.9rem" }}>
                {checked.length} selected · page {meta.current_page}/{meta.last_page}
              </span>
              <div style={{ display: "flex", gap: "0.5rem" }}>
                <button className="ps-btn ps-btn-ghost" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
                  Prev
                </button>
                <button
                  className="ps-btn ps-btn-ghost"
                  disabled={page >= meta.last_page}
                  onClick={() => setPage((p) => p + 1)}
                >
                  Next
                </button>
              </div>
            </div>
          </div>

          {/* Right rail — Allocate To */}
          <aside className="ps-card alloc-rail">
            <h3 style={{ margin: "0 0 0.85rem", fontSize: "1rem" }}>Allocate To</h3>
            <label style={{ display: "grid", gap: "0.35rem", marginBottom: "0.85rem" }}>
              <span style={{ fontSize: "0.85rem", color: "var(--muted)" }}>Sales person</span>
              <select className="ps-select" value={allocateTo} onChange={(e) => setAllocateTo(e.target.value)}>
                <option value="">Choose your option</option>
                {people.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.name}
                  </option>
                ))}
              </select>
            </label>
            <button
              type="button"
              className="ps-btn alloc-btn"
              disabled={busy || !allocateTo || !checked.length}
              onClick={bulkAllocate}
            >
              {busy ? "Allocating…" : `Allocate (${checked.length})`}
            </button>
            <p style={{ margin: "0.85rem 0 0", fontSize: "0.82rem", color: "var(--muted)", lineHeight: 1.45 }}>
              Tick leads on the left, pick a sales person, then Allocate — same as hi-leads salesperson allocation.
            </p>
          </aside>
        </div>
      </div>
    </AppShell>
  );
}
