"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Search } from "lucide-react";
import { Input, PageHeader, Panel, Select, Skeleton } from "@/components/ui/kit";
import { FilterTabs, Pager } from "@/components/admin/common";
import { PriorityBadge, TicketStatus, type Ticket } from "@/components/support/common";
import { qs } from "@/lib/api";
import { formatDateTime } from "@/lib/format";
import { useApi } from "@/lib/use-api";

type Status = "active" | "open" | "pending" | "resolved" | "closed" | "all";

export default function AdminTicketsPage() {
  const [status, setStatus] = useState<Status>("active");
  const [assigned, setAssigned] = useState<"any" | "me" | "unassigned">("any");
  const [priority, setPriority] = useState("");
  const [term, setTerm] = useState("");
  const [q, setQ] = useState("");
  const [page, setPage] = useState(1);
  useEffect(() => {
    const t = setTimeout(() => setQ(term.trim()), 300);
    return () => clearTimeout(t);
  }, [term]);
  const { data } = useApi<{ data: Ticket[]; meta: { total: number; last_page: number; counts: Record<string, number> } }>(`/admin/tickets${qs({ status, assigned, priority: priority || undefined, q, page })}`);
  const c = data?.meta.counts ?? {};
  return (
    <>
      <PageHeader title="Support tickets" description={`Urgent first, then whoever has waited longest. ${c.open ?? 0} need a reply, ${c.pending ?? 0} are waiting for the customer.`} />
      <div className="mb-3 flex flex-wrap items-center gap-3">
        <FilterTabs label="Status" value={status} onChange={(v) => (setStatus(v), setPage(1))} options={[["active", "Active"], ["open", "Needs reply"], ["pending", "Waiting for customer"], ["resolved", "Resolved"], ["closed", "Closed"], ["all", "All"]]} />
        <Select aria-label="Assigned" className="w-40" value={assigned} onChange={(e) => (setAssigned(e.target.value as typeof assigned), setPage(1))}>
          <option value="any">Anyone</option>
          <option value="me">Assigned to me</option>
          <option value="unassigned">Unassigned</option>
        </Select>
        <Select aria-label="Priority" className="w-36" value={priority} onChange={(e) => (setPriority(e.target.value), setPage(1))}>
          <option value="">Any priority</option>
          <option value="urgent">Urgent</option>
          <option value="high">High</option>
          <option value="normal">Normal</option>
          <option value="low">Low</option>
        </Select>
        <div className="relative ml-auto w-full sm:w-72">
          <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted" />
          <Input aria-label="Search tickets" placeholder="Subject, customer or #number" className="w-full pl-9" value={term} onChange={(e) => (setTerm(e.target.value), setPage(1))} />
        </div>
      </div>
      <Panel>
        {!data ? (
          <Skeleton className="m-5 h-40" />
        ) : data.data.length === 0 ? (
          <p className="px-5 py-10 text-center text-sm text-muted">No tickets match.</p>
        ) : (
          <>
            <ul className="divide-y divide-line">
              {data.data.map((t) => (
                <li key={t.id}>
                  <Link href={`/admin/tickets/${t.id}`} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-5 py-3.5 hover:bg-paper">
                    <span className="tabular w-12 text-[13px] text-muted">{t.number}</span>
                    <span className="min-w-0 flex-1 basis-56">
                      <span className="block truncate font-medium">{t.subject}</span>
                      <span className="text-[13px] text-muted">
                        {t.organization?.name}, {t.assigned_to ? `assigned to ${t.assigned_to.name}` : "unassigned"}
                      </span>
                    </span>
                    <PriorityBadge priority={t.priority} />
                    <TicketStatus status={t.status} side="support" />
                    <span className="w-36 text-right text-[13px] text-muted">{formatDateTime(t.last_message_at)}</span>
                  </Link>
                </li>
              ))}
            </ul>
            <Pager page={page} last={data.meta.last_page} total={data.meta.total} onPage={setPage} />
          </>
        )}
      </Panel>
    </>
  );
}
