"use client";
import Link from "next/link";
import { useState } from "react";
import { CheckCircle2, CheckSquare } from "lucide-react";
import { Badge, Card, Empty, PageHeader, Segmented, Select, Spinner, api, cx, useUI } from "@/components/ui";
import { fmtDate, useApi, useIndustry } from "@/components/hooks";

export default function TasksPage() {
  const ind = useIndustry();
  const team = useApi<{ data: { id: string; name: string }[]; perms: Record<string, string>; me: string; timezone: string }>("/team");
  const [who, setWho] = useState("me");
  const [view, setView] = useState<"open" | "done">("open");
  const qs = new URLSearchParams({ limit: "200", ...(view === "open" ? { "filter[open]": "true" } : {}), ...(who !== "all" ? { "filter[user_id]": who } : {}) }).toString();
  const tasks = useApi<{ data: any[] }>(`/activities?${qs}`, [qs]);
  const { push } = useUI();
  const now = Date.now();
  const list = (tasks.data?.data ?? []).filter((t) => (view === "done" ? t.completedAt && t.dueAt : true));
  const groups: [string, any[]][] = view === "open" ? [
    ["Overdue", list.filter((t) => new Date(t.dueAt).getTime() < now)],
    ["Today", list.filter((t) => { const d = new Date(t.dueAt).getTime(); return d >= now && d < now + 86400000; })],
    ["Upcoming", list.filter((t) => new Date(t.dueAt).getTime() >= now + 86400000)],
  ] : [["Completed", list]];
  const complete = async (id: string, outcome?: string) => { await api(`/activities/${id}`, { method: "PATCH", body: { completed: true, outcome } }); push("ok", "Task completed"); tasks.reload(); };

  return (
    <>
      <PageHeader title="Tasks & reminders" subtitle={`Calls, meetings and ${ind.visitPlural.toLowerCase()} · reminders 15 minutes before · synced to Google Calendar`}
        actions={<>
          <Segmented value={view} onChange={setView} options={[{ value: "open", label: "Open" }, { value: "done", label: "Done" }]} />
          {team.data?.perms?.contacts === "C" && <Select value={who} onChange={(e) => setWho(e.target.value)} className="w-[170px]"><option value="me">My tasks</option><option value="all">Everyone</option>{team.data.data.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</Select>}
        </>} />
      {tasks.loading && !tasks.data ? <div className="flex justify-center py-16"><Spinner /></div> : !list.length ? <Card><Empty title="No tasks" icon={<CheckSquare className="h-5 w-5" />}>Create tasks from a contact’s profile or let journeys create them.</Empty></Card> : (
        <div className="space-y-4">
          {groups.filter(([, arr]) => arr.length).map(([label, arr]) => (
            <Card key={label} title={<span className={label === "Overdue" ? "text-bad" : ""}>{label} · {arr.length}</span>} bodyClass="p-0">
              <ul className="divide-y divide-line/60">
                {arr.map((t) => (
                  <li key={t.id} className="flex flex-wrap items-center gap-3 px-4 py-2.5">
                    {view === "open" ? <button aria-label="Complete" onClick={() => complete(t.id, t.type === "visit" ? "visited" : t.type === "call" ? "connected" : "done")} className="grid h-5 w-5 shrink-0 place-items-center rounded-full border border-ink/30 hover:border-ok hover:bg-ok/10" /> : <CheckCircle2 className="h-5 w-5 text-ok" />}
                    <Badge tone={t.type === "visit" ? "violet" : t.type === "call" ? "blue" : "gray"}>{t.type}</Badge>
                    <div className="min-w-0 flex-1"><div className={cx("truncate text-[13px]", view === "done" && "text-ink-3 line-through")}>{t.title}</div>{t.contact && <Link href={`/contacts/${t.contact.id}`} className="text-[11.5px] text-ink-3 hover:text-brand">{t.contact.name}{t.contact.phone ? ` · ${t.contact.phone}` : ""}</Link>}</div>
                    {who === "all" && <span className="text-[11.5px] text-ink-3">{team.data?.data.find((u) => u.id === t.userId)?.name}</span>}
                    {t.calendarEventId && <Badge tone="green">calendar</Badge>}
                    <span className={cx("w-[150px] text-right text-[12px]", label === "Overdue" ? "text-bad" : "text-ink-3")}>{fmtDate(t.dueAt, team.data?.timezone)}</span>
                  </li>
                ))}
              </ul>
            </Card>
          ))}
        </div>
      )}
    </>
  );
}
