import { useState } from "react";
import { createFileRoute } from "@tanstack/react-router";
import { CheckCircle2, Paperclip, Send } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { EmptyState, PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { Pill } from "@/components/ledger/StatusBadge";
import { CLIENT_PORTAL_CLIENT_ID, useLedger } from "@/lib/ledger-store";

export const Route = createFileRoute("/client/queries")({
  head: () => ({
    meta: [
      { title: "Questions from your accountant — Abdelouhab" },
      { name: "description", content: "Answer bookkeeping questions and attach proof for your accountant." },
      { property: "og:title", content: "Questions from your accountant — Abdelouhab" },
      { property: "og:description", content: "Reply to open bookkeeping questions in the client portal." },
    ],
  }),
  component: ClientQueries,
});

function ClientQueries() {
  const { queries, getInvoice, answerQuery } = useLedger();
  const rows = queries.filter((q) => q.clientId === CLIENT_PORTAL_CLIENT_ID);

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Client portal"
        title="Questions from your accountant"
        subtitle="Answer open questions so your bookkeeping can be completed."
      />

      {rows.length === 0 ? (
        <SectionCard>
          <EmptyState
            icon={CheckCircle2}
            title="No open questions"
            description="You’re all caught up with your accountant’s questions."
          />
        </SectionCard>
      ) : (
        <div className="space-y-3">
          {rows.map((q) => (
            <QueryCard
              key={q.id}
              question={q.question}
              createdAt={q.createdAt}
              status={q.status}
              answer={q.answer}
              proof={q.proof}
              invoiceNumber={q.invoiceId ? getInvoice(q.invoiceId)?.number : undefined}
              onAnswer={(text, proof) => answerQuery(q.id, text, proof)}
            />
          ))}
        </div>
      )}
    </div>
  );
}

function QueryCard({
  question,
  createdAt,
  status,
  answer,
  proof,
  invoiceNumber,
  onAnswer,
}: {
  question: string;
  createdAt: string;
  status: string;
  answer?: string | undefined;
  proof?: string | undefined;
  invoiceNumber?: string | undefined;
  onAnswer: (text: string, proof?: string) => void;
}) {
  const [text, setText] = useState("");
  const [attached, setAttached] = useState<string | undefined>(undefined);

  return (
    <article className="surface-card p-5">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="min-w-0">
          <p className="text-[12px] text-muted-foreground">
            {createdAt}
            {invoiceNumber ? ` · Invoice ${invoiceNumber}` : ""}
          </p>
          <p className="mt-1.5 max-w-2xl text-[14px] leading-6">{question}</p>
        </div>
        <Pill tone={status === "Approved" ? "green" : status === "Delivered" ? "amber" : "neutral"}>{status}</Pill>
      </div>

      {answer ? (
        <div className="mt-3 rounded-lg border border-border bg-muted/50 p-3">
          <p className="text-[12px] font-semibold">Your answer</p>
          <p className="mt-1 text-[13px] leading-6 text-muted-foreground">{answer}</p>
          {proof ? <p className="mt-1.5 text-[12px] text-primary">Attachment: {proof}</p> : null}
        </div>
      ) : null}

      {status === "Requested" ? (
        <div className="mt-4 space-y-2">
          <Label htmlFor={`answer-${createdAt}-${question.length}`} className="text-[12px] text-muted-foreground">
            Your answer
          </Label>
          <Textarea
            id={`answer-${createdAt}-${question.length}`}
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="Type your answer for your accountant"
            className="min-h-24 bg-surface"
          />
          {attached ? <p className="text-[12px] text-primary">Attached: {attached}</p> : null}
          <div className="flex flex-wrap gap-2">
            <Button
              disabled={!text.trim()}
              onClick={() => {
                onAnswer(text.trim(), attached);
                setText("");
              }}
            >
              <Send size={16} /> Send answer
            </Button>
            <Button variant="outline" onClick={() => setAttached("bewijsstuk.pdf")}>
              <Paperclip size={16} /> Upload proof
            </Button>
          </div>
        </div>
      ) : null}
    </article>
  );
}
