import { useCallback, useEffect, useState } from "react";
import { createFileRoute, Link } from "@tanstack/react-router";
import { ArrowRight, CheckCircle2, MessageCircleQuestion } from "lucide-react";
import { Button } from "@/components/ui/button";
import { EmptyState, PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { useAuthSession } from "@/hooks/useAuthSession";
import { fetchQueriesApi } from "@/lib/api";
import { eur, useLedger } from "@/lib/ledger-store";
import type { ClientQuery } from "@/lib/ledger-types";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/queries/")({
  head: () => ({
    meta: [{ title: "Questions — Amanah Client" }],
  }),
  component: ClientQueries,
});

function ClientQueries() {
  const session = useAuthSession("client");
  const { getInvoice } = useLedger();
  const [rows, setRows] = useState<ClientQuery[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!session?.email) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetchQueriesApi({ platform: "client", email: session.email });
      setRows(Array.isArray(res?.items) ? res.items : []);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Could not load questions.");
    } finally {
      setLoading(false);
    }
  }, [session?.email]);

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

  const open = rows.filter((q) => q.status === "Delivered");
  const answered = rows.filter((q) => q.status === "Answered");
  const resolved = rows.filter((q) => q.status === "Resolved" || q.status === "Cancelled");

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Workspace"
        title="Questions"
        subtitle={
          open.length > 0
            ? `${open.length} question${open.length === 1 ? "" : "s"} waiting for you`
            : "When your accountant needs extra information, it will appear here."
        }
      />

      <SectionCard
        title="Open"
        description={open.length > 0 ? "Your accountant needs your help" : "Nothing requires your attention"}
      >
        {loading ? (
          <p className="px-5 py-4 text-[13px] text-muted-foreground">Loading questions…</p>
        ) : error ? (
          <EmptyState
            icon={MessageCircleQuestion}
            title="Could not load questions"
            description={error}
            action={
              <Button variant="outline" onClick={() => void load()}>
                Try again
              </Button>
            }
          />
        ) : open.length === 0 ? (
          <EmptyState
            icon={CheckCircle2}
            title="No questions"
            description="You're all caught up. Your accountant hasn't sent any questions."
          />
        ) : (
          <ul className="divide-y divide-border">
            {open.map((q) => (
              <QueryListItem key={q.id} query={q} getInvoice={getInvoice} tone="open" />
            ))}
          </ul>
        )}
      </SectionCard>

      {answered.length > 0 ? (
        <SectionCard title="Answered" description="Waiting for your accountant to review">
          <ul className="divide-y divide-border">
            {answered.map((q) => (
              <QueryListItem key={q.id} query={q} getInvoice={getInvoice} tone="answered" />
            ))}
          </ul>
        </SectionCard>
      ) : null}

      {resolved.length > 0 ? (
        <SectionCard title="Resolved" description="Previous questions">
          <ul className="divide-y divide-border">
            {resolved.map((q) => (
              <QueryListItem key={q.id} query={q} getInvoice={getInvoice} tone="resolved" />
            ))}
          </ul>
        </SectionCard>
      ) : null}
    </div>
  );
}

function QueryListItem({
  query,
  getInvoice,
  tone,
}: {
  query: ClientQuery;
  getInvoice: (id: string) => ReturnType<ReturnType<typeof useLedger>["getInvoice"]>;
  tone: "open" | "answered" | "resolved";
}) {
  const invoice = query.invoiceId ? getInvoice(query.invoiceId) : undefined;
  const preview = query.messages?.[0]?.message ?? query.question;

  return (
    <li className="px-5 py-4">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="flex items-center gap-2 text-[12px] text-muted-foreground">
            <MessageCircleQuestion size={14} aria-hidden="true" />
            <span>{query.createdAt}</span>
          </div>
          <p className="mt-1.5 text-[14px] font-semibold text-foreground">
            {invoice?.supplier || "Your accountant has a question"}
          </p>
          <p className="mt-1 max-w-2xl text-[13.5px] leading-6 text-muted-foreground">{preview}</p>
          {invoice ? (
            <p className="mt-1 text-[12px] text-muted-foreground">
              Related invoice · {invoice.number || invoice.file}
              {invoice.total ? ` · ${eur(invoice.total)}` : ""}
            </p>
          ) : null}
        </div>
        <span
          className={cn(
            "inline-flex items-center rounded-full border px-2.5 py-1 text-[11px] font-medium",
            tone === "open"
              ? "border-attention/25 bg-attention-soft text-attention"
              : tone === "resolved"
                ? "border-success/20 bg-success-soft text-success"
                : "border-primary/20 bg-primary-soft text-primary",
          )}
        >
          {tone === "open" ? "Needs your answer" : tone === "resolved" ? "Resolved" : "Answered"}
        </span>
      </div>
      <Button size="sm" variant={tone === "open" ? "brand" : "outline"} className="mt-3" asChild>
        <Link to="/queries/$id" params={{ id: query.id }}>
          {tone === "open" ? "Answer question" : "View conversation"} <ArrowRight size={14} />
        </Link>
      </Button>
    </li>
  );
}
