import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { Card, DateText, Mono, PageHeader, PhoneText, Stat } from "@/components/pbps/page";
import {
  DetailSkeleton,
  EmptyState,
  ErrorState,
  KpiGridSkeleton,
  TableSkeleton,
} from "@/components/pbps/states";
import { StatusBadge } from "@/components/pbps/status-badge";
import { KpiCard, ProgressRing, TargetBar } from "@/components/pbps/kpi";
import { DataTable } from "@/components/pbps/data-table";
import { JobProgress } from "@/components/pbps/job-progress";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { fmtDate, fmtInt, fmtPct, relativeTime } from "@/lib/format";
import { useAccess, useCan } from "@/lib/access";
import { cn } from "@/lib/utils";

import { ActionButton, type ActionField } from "@/components/pbps/action";
import {
  assignGrievance,
  getGrievance,
  listAssignees,
  replyGrievance,
  saveCorrectiveAction,
  setGrievanceStatus,
} from "@/api/ops";
import { Lock } from "lucide-react";
import { Textarea } from "@/components/ui/textarea";
import { fmtDateTime } from "@/lib/format";
import type { GrievanceCase } from "@/api/types";
/** The steps the server accepts from each status. "Resolved" is missing on purpose: answering resolves the case. */
const NEXT: Record<GrievanceCase["status"], GrievanceCase["status"][]> = {
  new: ["acknowledged", "in_progress", "escalated"],
  acknowledged: ["in_progress", "escalated"],
  in_progress: ["escalated"],
  responded: ["closed", "reopened"],
  escalated: ["in_progress"],
  resolved: ["closed", "reopened"],
  closed: ["reopened"],
  reopened: ["in_progress", "escalated"],
};
const ACTION_FIELDS: ActionField[] = [
  { key: "description", label: "What will be done", type: "area", required: true },
  { key: "owner", label: "Responsible person" },
  { key: "dueDate", label: "Due date", type: "date" },
  {
    key: "status",
    label: "Status",
    type: "select",
    options: [
      ["open", "Open"],
      ["done", "Done"],
      ["cancelled", "Cancelled"],
    ],
  },
];
const filled = (v: Record<string, string>) =>
  Object.fromEntries(Object.entries(v).filter(([, x]) => x.trim()));
export const Route = createFileRoute("/p/$pid/grievances/$id")({ component: Page });
function Page() {
  const { id } = Route.useParams();
  const qc = useQueryClient();
  const { access } = useAccess();
  const canReply = useCan("grievance.respond");
  const manage = useCan("grievance.manage");
  const resolve = useCan("grievance.resolve");
  const people = useQuery({
    queryKey: ["grievances", id, "assignees"],
    queryFn: () => listAssignees(id),
    enabled: manage,
  });
  const [body, setBody] = useState("");
  const [kind, setKind] = useState<"public_reply" | "internal_note">("public_reply");
  const q = useQuery({ queryKey: ["grievances", id], queryFn: () => getGrievance(id) });
  const inv = () => void qc.invalidateQueries({ queryKey: ["grievances"] });
  const reply = useMutation({
    mutationFn: replyGrievance,
    onSuccess: (g) => {
      toast.success(kind === "public_reply" ? "Answer sent, case resolved" : "Internal note added");
      setBody("");
      inv();
    },
    onError: (e) => toast.error(e.message),
  });
  const status = useMutation({
    mutationFn: (s: GrievanceCase["status"]) => setGrievanceStatus(id, s),
    onSuccess: () => {
      toast.success("Status updated");
      inv();
    },
    onError: (e) => toast.error(e.message),
  });
  if (q.isPending) return <DetailSkeleton />;
  if (q.isError) return <ErrorState error={q.error} />;
  const g = q.data;
  return (
    <>
      <PageHeader
        title={g.subject}
        description={`${g.ref} · ${g.category} · ${g.providerName}`}
        actions={<StatusBadge status={g.status} size="md" />}
      />
      <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
        <div className="space-y-3">
          {g.messages.map((m) => (
            <div
              key={m.id}
              className={cn(
                "rounded-xl border p-4",
                m.kind === "internal_note"
                  ? "border-dashed bg-amber-soft/60"
                  : m.kind === "public_reply"
                    ? "bg-primary-soft/60"
                    : "bg-card",
              )}
            >
              <p className="flex items-center gap-1.5 text-[12px] text-muted-foreground">
                {m.kind === "internal_note" && <Lock className="h-3 w-3" />}
                <b className="text-foreground">{m.author}</b> ·{" "}
                {m.kind === "internal_note"
                  ? "Internal note"
                  : m.kind === "public_reply"
                    ? "Answer"
                    : "Submitter"}{" "}
                · {fmtDateTime(m.at)}
              </p>
              <p className="mt-1.5 whitespace-pre-wrap">{m.body}</p>
            </div>
          ))}
          {canReply && (
            <Card>
              <div className="mb-2 flex gap-1 rounded-md border p-0.5 w-fit">
                {(["public_reply", "internal_note"] as const).map((k) => (
                  <button
                    key={k}
                    type="button"
                    onClick={() => setKind(k)}
                    className={cn(
                      "rounded px-3 py-1 text-[13px]",
                      kind === k && "bg-primary text-primary-foreground",
                    )}
                  >
                    {k === "public_reply" ? "Answer" : "Internal note"}
                  </button>
                ))}
              </div>
              <Textarea
                rows={4}
                value={body}
                onChange={(e) => setBody(e.target.value)}
                placeholder={
                  kind === "public_reply"
                    ? "Write the answer. Sending it resolves the case."
                    : "Only staff can see this note"
                }
              />
              {kind === "public_reply" && (
                <p className="mt-2 text-[12px] text-muted-foreground">
                  {g.replyTo ? (
                    <>Answers go to {g.replyTo}</>
                  ) : (
                    "The provider has no reply-to email yet"
                  )}
                </p>
              )}
              <div className="mt-3 flex justify-end">
                <Button
                  disabled={body.trim().length < 3 || reply.isPending}
                  onClick={() =>
                    reply.mutate({ id, body, kind, author: access?.userName ?? "Staff" })
                  }
                >
                  {reply.isPending
                    ? "Sending…"
                    : kind === "public_reply"
                      ? "Send answer and resolve"
                      : "Add note"}
                </Button>
              </div>
            </Card>
          )}
        </div>
        <div className="space-y-4">
          <Card title="Details">
            <dl className="space-y-2 text-[13px]">
              <div>
                <dt className="text-muted-foreground">Submitter</dt>
                <dd>
                  {[g.submitterName, g.submitterEmail, g.submitterPhone]
                    .filter(Boolean)
                    .join(" · ")}
                  {g.submitterName === "Confidential" && (
                    <span className="block text-[12px] text-muted-foreground">
                      Hidden from training providers.
                    </span>
                  )}
                </dd>
              </div>
              <div>
                <dt className="text-muted-foreground">Assigned to</dt>
                <dd className="flex flex-wrap items-center gap-2">
                  {g.assignedTo ?? "Nobody yet"}
                  {manage && (
                    <ActionButton
                      variant="ghost"
                      label="Change"
                      title="Assign this case"
                      fields={[
                        {
                          key: "u",
                          label: "Person",
                          type: "select",
                          required: true,
                          options: (people.data ?? []).map((x): [string, string] => [
                            x.id,
                            x.provider ? `${x.name} (${x.provider})` : x.name,
                          ]),
                        },
                      ]}
                      run={(v) => assignGrievance(id, v["u"] ?? "")}
                      success="Case assigned"
                      refresh={["grievances"]}
                      confirmLabel="Assign"
                    />
                  )}
                </dd>
              </div>
              <div>
                <dt className="text-muted-foreground">Region</dt>
                <dd>{g.region ?? "—"}</dd>
              </div>
              <div>
                <dt className="text-muted-foreground">Submitted</dt>
                <dd>{fmtDateTime(g.submittedAt)}</dd>
              </div>
              <div>
                <dt className="text-muted-foreground">Response due</dt>
                <dd className={cn(g.overdue && "font-semibold text-danger")}>
                  {fmtDateTime(g.dueAt)}
                  {g.overdue && " · overdue"}
                </dd>
              </div>
            </dl>
          </Card>
          {(canReply || manage || resolve) && (
            <Card title="Status">
              <div className="flex flex-wrap gap-2">
                {NEXT[g.status].map((s) => (
                  <Button
                    key={s}
                    size="sm"
                    variant="outline"
                    disabled={status.isPending}
                    onClick={() => status.mutate(s)}
                    className="capitalize"
                  >
                    {s.replace("_", " ")}
                  </Button>
                ))}
              </div>
            </Card>
          )}
          <Card
            title="Corrective actions"
            actions={
              (manage || resolve) && (
                <ActionButton
                  label="Add"
                  title="Add a corrective action"
                  fields={ACTION_FIELDS}
                  run={(v) => saveCorrectiveAction(id, filled(v))}
                  success="Action saved"
                  refresh={["grievances"]}
                />
              )
            }
          >
            {!g.actions?.length ? (
              <p className="text-[13px] text-muted-foreground">No corrective actions yet.</p>
            ) : (
              <ul className="space-y-3 text-[13px]">
                {g.actions.map((a) => (
                  <li key={a.id}>
                    <p className="font-medium">{a.description}</p>
                    <p className="text-muted-foreground">
                      {[a.owner, a.dueDate && `due ${fmtDate(a.dueDate)}`]
                        .filter(Boolean)
                        .join(" · ")}
                    </p>
                    <div className="mt-1 flex items-center gap-2">
                      <StatusBadge
                        status={a.status === "done" ? "resolved" : a.status}
                        label={a.status === "done" ? "Done" : a.status}
                      />
                      {(manage || resolve) && (
                        <ActionButton
                          variant="ghost"
                          label="Edit"
                          title="Edit the corrective action"
                          fields={ACTION_FIELDS}
                          initial={{
                            description: a.description,
                            owner: a.owner ?? "",
                            dueDate: a.dueDate ?? "",
                            status: a.status,
                          }}
                          run={(v) => saveCorrectiveAction(id, { id: a.id, ...filled(v) })}
                          success="Action saved"
                          refresh={["grievances"]}
                        />
                      )}
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </Card>
        </div>
      </div>
    </>
  );
}
