import { createFileRoute, Link } from "@tanstack/react-router";
import { useMutation } from "@tanstack/react-query";
import { Heart, Star } from "lucide-react";
import { useState } from "react";
import { Wordmark } from "@/components/pbps/brand";
import { AuthError } from "@/components/pbps/auth-layout";
import { TextArea } from "@/components/pbps/form";
import { Button } from "@/components/ui/button";
import { rateGrievance } from "@/api/public";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/feedback/rate")({
  validateSearch: (s: Record<string, unknown>) => ({
    ref: String(s["ref"] ?? ""),
    token: String(s["token"] ?? ""),
  }),
  head: () => ({ meta: [{ title: "Rate the response — PBPS MIS" }] }),
  component: Rate,
});

function Rate() {
  const { ref, token } = Route.useSearch();
  const [score, setScore] = useState(0);
  const [comment, setComment] = useState("");
  const m = useMutation({
    mutationFn: () => rateGrievance(ref, token, score, comment.trim() || undefined),
  });
  return (
    <div className="mx-auto max-w-lg px-4 py-10">
      <Link to="/">
        <Wordmark />
      </Link>
      {m.isSuccess ? (
        <div className="mt-10 text-center">
          <Heart className="mx-auto h-10 w-10 text-primary" />
          <h1 className="mt-4 font-display text-2xl font-bold">Thank you!</h1>
          <p className="mt-1 text-muted-foreground">
            Your rating helps providers improve how they respond.
          </p>
        </div>
      ) : (
        <>
          <h1 className="mt-8 font-display text-2xl font-bold">
            How satisfied are you with the response?
          </h1>
          <p className="mt-1 font-mono text-[13px] text-muted-foreground">{ref}</p>
          <form
            className="mt-6 space-y-4"
            onSubmit={(e) => {
              e.preventDefault();
              if (score) m.mutate();
            }}
          >
            <AuthError message={m.error?.message} />
            <div role="radiogroup" aria-label="Rating" className="flex gap-2">
              {[1, 2, 3, 4, 5].map((s) => (
                <button
                  key={s}
                  type="button"
                  role="radio"
                  aria-checked={score === s}
                  aria-label={`${s} star${s > 1 ? "s" : ""}`}
                  onClick={() => setScore(s)}
                  className="rounded-lg p-1.5 hover:bg-surface-2"
                >
                  <Star
                    className={cn(
                      "h-10 w-10",
                      s <= score ? "fill-amber text-amber" : "text-subtle",
                    )}
                  />
                </button>
              ))}
            </div>
            <TextArea
              value={comment}
              onChange={setComment}
              rows={4}
              maxLength={1000}
              placeholder="Anything you want to add? (optional)"
            />
            <Button type="submit" size="lg" disabled={!score || m.isPending}>
              {m.isPending ? "Sending…" : "Send rating"}
            </Button>
          </form>
        </>
      )}
    </div>
  );
}
