import { createFileRoute, Link } from "@tanstack/react-router";
import { useMutation, useQuery } from "@tanstack/react-query";
import { AlertTriangle, Copy, Heart, HelpCircle, Lightbulb } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
import { Wordmark } from "@/components/pbps/brand";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { getPublicProviders, submitPublicGrievance } from "@/api/public";
import type { GrievanceCase } from "@/api/types";
import { fmtDate } from "@/lib/dates";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/feedback/new")({
  head: () => ({
    meta: [
      { title: "Submit feedback — PBPS MIS" },
      {
        name: "description",
        content:
          "Send a complaint, suggestion, question or appreciation about a training provider.",
      },
      { property: "og:title", content: "Submit feedback — PBPS MIS" },
      { property: "og:description", content: "No account needed." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
  }),
  component: Page,
});
const CATS = [
  { k: "complaint", l: "Complaint", I: AlertTriangle },
  { k: "suggestion", l: "Suggestion", I: Lightbulb },
  { k: "question", l: "Question", I: HelpCircle },
  { k: "appreciation", l: "Appreciation", I: Heart },
] as const;

function Page() {
  const prov = useQuery({ queryKey: ["public", "providers"], queryFn: getPublicProviders });
  const [step, setStep] = useState(1);
  const [f, setF] = useState({
    providerId: "",
    category: "" as GrievanceCase["category"] | "",
    subject: "",
    description: "",
    name: "",
    email: "",
    phone: "",
  });
  const m = useMutation({
    mutationFn: submitPublicGrievance,
    onError: (e) => toast.error(e.message),
  });
  const set = (k: keyof typeof f) => (e: { target: { value: string } }) =>
    setF((s) => ({ ...s, [k]: e.target.value }));
  const ok1 = f.providerId && f.category;
  const ok2 = f.subject.trim().length >= 3 && f.description.trim().length >= 3;
  const ok3 = f.name.trim() && /^\S+@\S+\.\S+$/.test(f.email);
  return (
    <div className="min-h-screen px-4 py-8">
      <div className="mx-auto max-w-[720px]">
        <Link to="/">
          <Wordmark />
        </Link>
        <div className="mt-6 rounded-xl border bg-card p-6">
          {m.data ? (
            <div className="text-center">
              <p className="text-muted-foreground">Your reference number</p>
              <p className="mt-2 flex items-center justify-center gap-2 font-mono text-2xl font-bold">
                {m.data.ref}
                <button
                  type="button"
                  aria-label="Copy reference"
                  onClick={() => {
                    void navigator.clipboard.writeText(m.data.ref);
                    toast.success("Copied");
                  }}
                >
                  <Copy className="h-4 w-4" />
                </button>
              </p>
              <p className="mt-3">
                Expect a response by <b>{fmtDate(m.data.dueAt)}</b>. We sent an acknowledgement to
                your email.
              </p>
            </div>
          ) : (
            <>
              <h1 className="font-display text-2xl font-bold">Submit feedback or a complaint</h1>
              <ol className="mt-4 flex gap-2 text-[13px]">
                {["About", "Details", "Contact"].map((s, i) => (
                  <li
                    key={s}
                    className={cn(
                      "flex-1 rounded-full py-1 text-center",
                      step === i + 1
                        ? "bg-primary text-primary-foreground"
                        : step > i + 1
                          ? "bg-primary-soft text-primary"
                          : "bg-surface-2 text-muted-foreground",
                    )}
                  >
                    {i + 1}. {s}
                  </li>
                ))}
              </ol>
              <div className="mt-6 space-y-4">
                {step === 1 && (
                  <>
                    <label className="block">
                      <span className="font-medium">Training provider</span>
                      <select
                        className="mt-1 h-10 w-full rounded-md border bg-card px-2"
                        value={f.providerId}
                        onChange={set("providerId")}
                      >
                        <option value="">Choose a provider</option>
                        {prov.data?.map((p) => (
                          <option key={p.id} value={p.id}>
                            {p.name}
                          </option>
                        ))}
                      </select>
                    </label>
                    <div>
                      <span className="font-medium">Category</span>
                      <div className="mt-1 grid grid-cols-2 gap-2 sm:grid-cols-4">
                        {CATS.map(({ k, l, I }) => (
                          <button
                            key={k}
                            type="button"
                            onClick={() => setF((s) => ({ ...s, category: k }))}
                            className={cn(
                              "flex flex-col items-center gap-2 rounded-lg border p-4",
                              f.category === k && "border-primary bg-primary-soft text-primary",
                            )}
                          >
                            <I className="h-6 w-6" />
                            {l}
                          </button>
                        ))}
                      </div>
                    </div>
                  </>
                )}
                {step === 2 && (
                  <>
                    <label className="block">
                      <span className="font-medium">Subject</span>
                      <Input
                        className="mt-1"
                        maxLength={200}
                        value={f.subject}
                        onChange={set("subject")}
                      />
                      <span className="text-[12px] text-muted-foreground">
                        {f.subject.length}/200
                      </span>
                    </label>
                    <label className="block">
                      <span className="font-medium">Description</span>
                      <Textarea
                        className="mt-1"
                        rows={6}
                        maxLength={4000}
                        value={f.description}
                        onChange={set("description")}
                      />
                      <span className="text-[12px] text-muted-foreground">
                        {f.description.length}/4,000
                      </span>
                    </label>
                  </>
                )}
                {step === 3 && (
                  <>
                    <label className="block">
                      <span className="font-medium">Your name</span>
                      <Input className="mt-1" value={f.name} onChange={set("name")} />
                    </label>
                    <label className="block">
                      <span className="font-medium">Email</span>
                      <Input
                        className="mt-1"
                        type="email"
                        value={f.email}
                        onChange={set("email")}
                      />
                      <span className="text-[12px] text-muted-foreground">
                        Replies are sent here.
                      </span>
                    </label>
                    <label className="block">
                      <span className="font-medium">Phone (optional)</span>
                      <Input className="mt-1" value={f.phone} onChange={set("phone")} />
                    </label>
                  </>
                )}
              </div>
              <div className="mt-6 flex justify-between">
                {step > 1 ? (
                  <Button variant="outline" onClick={() => setStep(step - 1)}>
                    Back
                  </Button>
                ) : (
                  <span />
                )}
                {step < 3 ? (
                  <Button disabled={step === 1 ? !ok1 : !ok2} onClick={() => setStep(step + 1)}>
                    Next
                  </Button>
                ) : (
                  <Button
                    disabled={!ok3 || m.isPending}
                    onClick={() =>
                      f.category &&
                      m.mutate({
                        providerId: f.providerId,
                        category: f.category,
                        subject: f.subject,
                        description: f.description,
                        name: f.name,
                        email: f.email,
                        ...(f.phone ? { phone: f.phone } : {}),
                      })
                    }
                  >
                    {m.isPending ? "Submitting…" : "Submit"}
                  </Button>
                )}
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
