import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { MessageSquare, Star, CheckCircle2 } from "lucide-react";
import { Reveal } from "@/components/site/Reveal";
import { submitFeedback } from "@/lib/feedback.functions";

export const Route = createFileRoute("/feedback")({
  head: () => ({
    meta: [
      { title: "Share Your Feedback — Vigor Group of Companies" },
      {
        name: "description",
        content:
          "Tell Vigor Group of Companies what we do well and where we can improve. Share a suggestion, complaint, compliment or general feedback.",
      },
      { property: "og:title", content: "Share Your Feedback — Vigor Group" },
      {
        property: "og:description",
        content: "Your suggestions, compliments and complaints help us serve Tanzania better.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: Feedback,
});

const types = ["Suggestion", "Complaint", "Compliment", "General Feedback"];

function Feedback() {
  const [sent, setSent] = useState(false);
  const [rating, setRating] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const sendFeedback = useServerFn(submitFeedback);

  return (
    <>
      <section className="container-x pt-16 md:pt-20 pb-12 border-b border-border">
        <p className="eyebrow">Feedback</p>
        <h1 className="mt-6 text-5xl md:text-7xl max-w-4xl leading-[1]">
          Your voice makes us <span className="italic text-primary">better</span>.
        </h1>
        <p className="mt-8 max-w-2xl text-lg text-ink-soft leading-relaxed">
          Whether you are a guest, patient, tenant, customer, partner or colleague — we want to hear
          from you. Every submission is read by our group service team.
        </p>
      </section>

      <section className="container-x py-16 md:py-20 grid lg:grid-cols-2 gap-14 lg:gap-20 items-start">
        <Reveal className="space-y-6">
          <div className="w-10 h-10 bg-primary text-white flex items-center justify-center">
            <MessageSquare size={18} />
          </div>
          <h2 className="text-3xl md:text-4xl leading-tight">
            Tell us what we do well — and where we can improve
          </h2>
          <p className="text-base md:text-lg leading-relaxed text-ink-soft">
            Compliments are shared with the teams who earned them. Complaints are routed to the
            responsible business unit and followed up. Suggestions shape how we plan and invest.
          </p>
          <p className="text-base md:text-lg leading-relaxed text-ink-soft">
            Name and email are optional — leave them blank if you prefer to stay anonymous. If you
            would like a response, please include an email address.
          </p>
        </Reveal>

        <Reveal delay={120}>
          {sent ? (
            <div
              role="status"
              className="bg-secondary/50 border border-border p-8 md:p-10 text-center"
            >
              <CheckCircle2 className="mx-auto text-primary" size={40} />
              <h2 className="mt-5 text-2xl">Thank you</h2>
              <p className="mt-3 text-ink-soft leading-relaxed">
                Your feedback has been received and will be shared with the relevant team.
              </p>
              <button
                type="button"
                className="btn-ghost mt-7"
                onClick={() => {
                  setSent(false);
                  setRating(0);
                }}
              >
                Send more feedback
              </button>
            </div>
          ) : (
            <form
              className="bg-secondary/50 border border-border p-8 md:p-10 space-y-5"
              onSubmit={async (e) => {
                e.preventDefault();
                const form = e.currentTarget;
                const data = new FormData(form);
                setError(null);
                setSubmitting(true);

                try {
                  await sendFeedback({
                    data: {
                      name: String(data.get("name") ?? "") || undefined,
                      email: String(data.get("email") ?? "") || undefined,
                      type: String(data.get("type") ?? "") as
                        | "Suggestion"
                        | "Complaint"
                        | "Compliment"
                        | "General Feedback",
                      message: String(data.get("message") ?? ""),
                      rating: rating || undefined,
                    },
                  });
                  form.reset();
                  setRating(0);
                  setSent(true);
                } catch (err) {
                  setError(
                    err instanceof Error
                      ? err.message
                      : "Something went wrong. Please try again.",
                  );
                } finally {
                  setSubmitting(false);
                }
              }}
            >
              <h2 className="text-2xl">Share your feedback</h2>

              <div className="grid sm:grid-cols-2 gap-5">
                <label className="block">
                  <span className="text-xs uppercase tracking-[0.18em] font-semibold">
                    Name <span className="text-ink-soft normal-case tracking-normal">(optional)</span>
                  </span>
                  <input
                    name="name"
                    maxLength={100}
                    className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary"
                  />
                </label>
                <label className="block">
                  <span className="text-xs uppercase tracking-[0.18em] font-semibold">
                    Email <span className="text-ink-soft normal-case tracking-normal">(optional)</span>
                  </span>
                  <input
                    name="email"
                    type="email"
                    maxLength={255}
                    className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary"
                  />
                </label>
              </div>

              <label className="block">
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">
                  Feedback type
                </span>
                <select
                  name="type"
                  required
                  defaultValue=""
                  className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary"
                >
                  <option value="" disabled>
                    Select a type
                  </option>
                  {types.map((t) => (
                    <option key={t} value={t}>
                      {t}
                    </option>
                  ))}
                </select>
              </label>

              <label className="block">
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">Message</span>
                <textarea
                  name="message"
                  required
                  rows={6}
                  maxLength={2000}
                  className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary"
                />
              </label>

              <fieldset>
                <legend className="text-xs uppercase tracking-[0.18em] font-semibold">
                  Rating <span className="text-ink-soft normal-case tracking-normal">(optional)</span>
                </legend>
                <div className="mt-2 flex items-center gap-2">
                  {[1, 2, 3, 4, 5].map((n) => (
                    <button
                      key={n}
                      type="button"
                      aria-label={`Rate ${n} out of 5`}
                      aria-pressed={rating === n}
                      onClick={() => setRating(rating === n ? 0 : n)}
                      className="p-1 transition-transform duration-200 hover:scale-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
                    >
                      <Star
                        size={24}
                        className={n <= rating ? "text-primary" : "text-border"}
                        fill={n <= rating ? "currentColor" : "none"}
                      />
                    </button>
                  ))}
                  <input type="hidden" name="rating" value={rating} />
                </div>
              </fieldset>

              {error ? (
                <p role="alert" className="text-sm text-primary">
                  {error}
                </p>
              ) : null}

              <button type="submit" className="btn-primary" disabled={submitting}>
                {submitting ? "Submitting…" : "Submit feedback"}
              </button>
            </form>
          )}
        </Reveal>
      </section>
    </>
  );
}
