import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import {
  Bar,
  BarChart,
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from "recharts";
import { Card, PageHeader } from "@/components/pbps/page";
import { Tbl, View } from "@/components/pbps/blocks";
import { Button } from "@/components/ui/button";
import { getGrievanceInsights } from "@/api/ops";

export const Route = createFileRoute("/p/$pid/grievances/insights")({ component: Page });
function Bars({ rows }: { rows: { label: string; value: number }[] }) {
  const max = Math.max(1, ...rows.map((r) => r.value));
  return (
    <ul className="space-y-2">
      {rows.map((r) => (
        <li key={r.label} className="grid grid-cols-[90px_1fr_36px] items-center gap-3 text-[13px]">
          <span>{r.label}</span>
          <span className="h-2 rounded bg-surface-2">
            <span
              className="block h-full rounded bg-primary"
              style={{ width: `${(r.value / max) * 100}%` }}
            />
          </span>
          <b className="text-right tabular">{r.value}</b>
        </li>
      ))}
    </ul>
  );
}
function Page() {
  const { pid } = Route.useParams();
  const q = useQuery({ queryKey: ["grievances", "insights"], queryFn: getGrievanceInsights });
  return (
    <>
      <PageHeader
        title="Grievance insights"
        actions={
          <Button variant="outline" asChild>
            <Link to="/p/$pid/grievances" params={{ pid }}>
              Cases
            </Link>
          </Button>
        }
      />
      <View q={q}>
        {(d) => (
          <div className="grid gap-5 lg:grid-cols-2">
            <Card title="Cases by category" className="lg:col-span-2">
              <div className="h-64">
                <ResponsiveContainer>
                  <BarChart data={d.byMonth}>
                    <CartesianGrid vertical={false} stroke="var(--border)" />
                    <XAxis dataKey="month" fontSize={11} />
                    <YAxis allowDecimals={false} fontSize={11} />
                    <Tooltip />
                    <Legend />
                    {["complaint", "suggestion", "question", "appreciation"].map((c, i) => (
                      <Bar
                        key={c}
                        dataKey={c}
                        stackId="a"
                        maxBarSize={48}
                        fill={`var(--chart-${i + 1})`}
                      />
                    ))}
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </Card>
            <Card title="Time to first response">
              <Bars rows={d.responseDays} />
            </Card>
            <Card title="Satisfaction">
              <Bars
                rows={d.satisfaction.map((s) => ({ label: `${s.score} of 5`, value: s.count }))}
              />
            </Card>
            <Card title="By provider" padded={false}>
              <Tbl head={["Provider", ">Open", ">Total"]}>
                {d.byProvider.map((p) => (
                  <tr key={p.code}>
                    <td>{p.code}</td>
                    <td className="text-right">{p.open}</td>
                    <td className="text-right">{p.total}</td>
                  </tr>
                ))}
              </Tbl>
            </Card>
            <Card title="Recurring words">
              <p className="flex flex-wrap gap-2">
                {d.topics.map((t) => (
                  <span key={t.word} className="rounded bg-surface-2 px-2 py-1 text-[13px]">
                    {t.word} <b className="tabular">{t.count}</b>
                  </span>
                ))}
              </p>
            </Card>
          </div>
        )}
      </View>
    </>
  );
}
