import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import {
  ArrowRight,
  CheckCircle2,
  ChevronRight,
  FileStack,
  HelpCircle,
  Loader2,
  Upload,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { DocumentUploadDialog } from "@/components/ledger/DocumentUploadDialog";
import { ActivityTimeline } from "@/components/ledger/ActivityTimeline";
import { EmptyState, KpiCard, PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { ClientStatusBadge, toClientStatus } from "@app/components/ClientStatusBadge";
import { useAuthSession } from "@/hooks/useAuthSession";
import { useClientId } from "@/hooks/useClientId";
import { eur, useLedger } from "@/lib/ledger-store";

export const Route = createFileRoute("/")({
  head: () => ({
    meta: [
      { title: "Dashboard — Amanah Client" },
      { name: "description", content: "See what's happening with your documents." },
      { property: "og:title", content: "Dashboard — Amanah Client" },
      { property: "og:description", content: "Your Amanah client workspace overview." },
    ],
  }),
  component: ClientDashboard,
});

function firstName(name: string): string {
  return name.trim().split(/\s+/)[0] || name;
}

function timeGreeting(): string {
  const h = new Date().getHours();
  if (h < 12) return "Good morning";
  if (h < 18) return "Good afternoon";
  return "Good evening";
}

function isThisMonth(dateStr: string): boolean {
  const d = new Date(dateStr);
  if (Number.isNaN(d.getTime())) return true;
  const now = new Date();
  return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
}

function ClientDashboard() {
  const navigate = useNavigate();
  const session = useAuthSession("client");
  const clientId = useClientId();
  const { invoices, queries, activity, getInvoice, clients, uploadDocumentFile } = useLedger();
  const [uploadOpen, setUploadOpen] = useState(false);

  const rows = clientId
    ? invoices
        .filter((i) => i.clientId === clientId)
        .slice()
        .sort((a, b) => b.uploadedAt.localeCompare(a.uploadedAt))
    : [];

  const openQuestions = clientId
    ? queries.filter((q) => q.clientId === clientId && q.status === "Delivered")
    : [];
  const docsThisMonth = rows.filter((d) => isThisMonth(d.uploadedAt)).length;
  const processing = rows.filter((d) => {
    const s = toClientStatus(d.status);
    return s === "processing" || s === "review";
  }).length;
  const name = firstName(session?.name ?? "there");
  const recentActivity = activity.slice(0, 7);
  const primaryQuestion = openQuestions[0];
  const relatedInvoice = primaryQuestion?.invoiceId
    ? getInvoice(primaryQuestion.invoiceId)
    : undefined;

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Client overview"
        title={`${timeGreeting()}, ${name}`}
        subtitle="Here’s what’s happening with your documents."
        actions={
          <>
            <Button variant="outline" onClick={() => navigate({ to: "/documents" })}>
              <FileStack size={16} /> View documents
            </Button>
            <Button variant="brand" onClick={() => setUploadOpen(true)}>
              <Upload size={16} /> Send document <ArrowRight size={16} />
            </Button>
          </>
        }
      />

      <div className="grid gap-3 sm:grid-cols-3">
        <KpiCard
          label="Documents"
          value={docsThisMonth}
          hint="Submitted this month"
          icon={FileStack}
          tone="neutral"
          onClick={() => navigate({ to: "/documents" })}
        />
        <KpiCard
          label="Processing"
          value={processing}
          hint="Currently being processed"
          icon={Loader2}
          tone="green"
          onClick={() => navigate({ to: "/documents" })}
        />
        <KpiCard
          label="Questions"
          value={openQuestions.length}
          hint="Waiting for your response"
          icon={HelpCircle}
          tone={openQuestions.length > 0 ? "amber" : "neutral"}
          onClick={() => navigate({ to: "/queries" })}
        />
      </div>

      <SectionCard
        title="Send a document"
        description="Upload an invoice, receipt or other document — we’ll take care of the rest."
        action={
          <Button variant="brand" size="sm" onClick={() => setUploadOpen(true)}>
            <Upload size={15} /> Send document
          </Button>
        }
        bodyClassName="px-5 py-4"
      >
        <p className="text-[13.5px] leading-6 text-muted-foreground">
          Drag &amp; drop or choose a file on the upload page. Supported formats: PDF, JPG, PNG, WEBP.
        </p>
      </SectionCard>

      <div className="grid gap-4 lg:grid-cols-[1.85fr_1fr]">
        <SectionCard
          title="Recent documents"
          description="Your latest uploads and their status"
          action={
            <Link
              to="/documents"
              className="text-[13px] font-semibold text-brand-foreground transition-colors hover:text-brand"
            >
              View all →
            </Link>
          }
        >
          {rows.length === 0 ? (
            <EmptyState
              icon={FileStack}
              title="No documents yet"
              description="Send your first invoice or receipt and we’ll take care of the rest."
              action={
                <Button variant="brand" asChild>
                  <Link to="/upload">
                    <Upload size={16} /> Send document
                  </Link>
                </Button>
              }
            />
          ) : (
            <ul className="divide-y divide-border">
              {rows.slice(0, 6).map((invoice) => (
                <li key={invoice.id}>
                  <Link
                    to="/documents/$id"
                    params={{ id: invoice.id }}
                    className="flex min-h-[56px] items-center gap-3 px-5 py-3.5 transition-colors hover:bg-brand-soft/40"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="truncate text-[13.5px] font-medium">{invoice.supplier}</p>
                      <p className="truncate text-[12px] text-muted-foreground">
                        {invoice.number} · Uploaded {invoice.uploadedAt}
                      </p>
                    </div>
                    <span className="num hidden w-24 text-right text-[13.5px] font-semibold sm:block">
                      {eur(invoice.total)}
                    </span>
                    <ClientStatusBadge status={invoice.status} />
                    <ChevronRight size={16} className="text-muted-foreground" aria-hidden="true" />
                  </Link>
                </li>
              ))}
            </ul>
          )}
        </SectionCard>

        <div className="space-y-4">
          <SectionCard
            title="Open questions"
            description={
              openQuestions.length > 0
                ? `${openQuestions.length} question${openQuestions.length === 1 ? "" : "s"} require${openQuestions.length === 1 ? "s" : ""} your attention`
                : "Nothing waiting for you"
            }
          >
            {primaryQuestion ? (
              <div className="space-y-3 px-5 py-4">
                <p className="text-[12px] font-medium text-muted-foreground">
                  Your accountant has a question about:
                </p>
                <p className="text-[13.5px] font-semibold text-foreground">
                  {relatedInvoice?.supplier ?? "Your document"}
                </p>
                <p className="text-[13.5px] leading-6 text-muted-foreground">
                  “{primaryQuestion.question}”
                </p>
                <Button variant="brand" size="sm" className="w-full sm:w-auto" asChild>
                  <Link to="/queries/$id" params={{ id: primaryQuestion.id }}>
                    Answer question <ArrowRight size={15} />
                  </Link>
                </Button>
              </div>
            ) : (
              <div className="flex items-start gap-3 px-5 py-5">
                <span className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-success-soft text-success">
                  <CheckCircle2 size={18} aria-hidden="true" />
                </span>
                <div>
                  <p className="text-[13.5px] font-medium text-foreground">You’re all caught up</p>
                  <p className="mt-0.5 text-[12.5px] leading-5 text-muted-foreground">
                    No questions from your accountant right now.
                  </p>
                </div>
              </div>
            )}
          </SectionCard>

          <SectionCard title="Recent activity" description="What happened with your documents">
            {recentActivity.length === 0 ? (
              <EmptyState
                icon={CheckCircle2}
                title="No activity yet"
                description="Activity will appear here after you send your first document."
              />
            ) : (
              <ActivityTimeline events={recentActivity} showLinks variant="client" />
            )}
          </SectionCard>
        </div>
      </div>

      <DocumentUploadDialog
        open={uploadOpen}
        onOpenChange={setUploadOpen}
        platform="client"
        clients={clients}
        actor={session?.name ?? "Client"}
        email={session?.email ?? ""}
        onUpload={(file, options) =>
          uploadDocumentFile(file, {
            platform: "client",
            email: session?.email ?? "",
            clientId: session?.clientId,
            actor: session?.name ?? "Client",
            onProgress: options.onProgress,
          })
        }
      />
    </div>
  );
}
