import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { ShieldCheck, Lock, EyeOff, Paperclip, CheckCircle2 } from "lucide-react";
import { Reveal } from "@/components/site/Reveal";
import { submitWhistleblowerReport } from "@/lib/whistleblower.functions";


export const Route = createFileRoute("/whistleblower")({
  head: () => ({
    meta: [
      { title: "Whistleblower Programme — Vigor Group of Companies" },
      {
        name: "description",
        content:
          "Report misconduct, fraud or unethical behaviour confidentially through the Vigor Group whistleblower programme. Anonymous reporting is welcome.",
      },
      { property: "og:title", content: "Whistleblower Programme — Vigor Group" },
      {
        property: "og:description",
        content: "Confidential, protected reporting of misconduct across Vigor Group of Companies.",
      },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
  }),
  component: Whistleblower,
});

const categories = [
  "Fraud or financial misconduct",
  "Bribery or corruption",
  "Health, safety or environment",
  "Harassment or discrimination",
  "Conflict of interest",
  "Data or confidentiality breach",
  "Other",
];

const assurances = [
  {
    Icon: Lock,
    title: "Strict confidentiality",
    body: "Reports are received by an independent review panel and handled on a need-to-know basis only.",
  },
  {
    Icon: EyeOff,
    title: "Anonymous reporting",
    body: "Name and email are optional. You may submit a report without identifying yourself at any point.",
  },
  {
    Icon: ShieldCheck,
    title: "Zero retaliation",
    body: "No employee, partner or supplier will face retaliation for raising a concern in good faith.",
  },
];

function fileToBase64(file: File): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(String(reader.result).split(",")[1] ?? "");
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(file);
  });
}

function Whistleblower() {
  const [sent, setSent] = useState(false);
  const [fileName, setFileName] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const sendReport = useServerFn(submitWhistleblowerReport);


  return (
    <>
      <section className="container-x pt-16 md:pt-20 pb-12 border-b border-border">
        <p className="eyebrow">Governance</p>
        <h1 className="mt-6 text-5xl md:text-7xl max-w-4xl leading-[1]">
          Speak up. We will <span className="italic text-primary">listen</span>.
        </h1>
        <p className="mt-8 max-w-2xl text-lg text-ink-soft leading-relaxed">
          Integrity is the foundation of everything Vigor Group has built since the 1980s. Our
          whistleblower programme gives employees, partners, suppliers and members of the public a
          safe and protected channel to report suspected misconduct.
        </p>
      </section>

      <section className="container-x py-16 md:py-20 grid lg:grid-cols-2 gap-14 lg:gap-20 items-start">
        <div className="space-y-10">
          <Reveal>
            <h2 className="text-3xl md:text-4xl leading-tight">
              A programme built on trust
            </h2>
            <p className="mt-5 text-base md:text-lg leading-relaxed text-ink-soft">
              We encourage every person connected to our group to report, in good faith, any conduct
              that conflicts with our values, our code of conduct or the law. Raising a concern early
              protects our people, our partners and the communities we serve.
            </p>
          </Reveal>

          <div className="space-y-8">
            {assurances.map(({ Icon, title, body }, i) => (
              <Reveal key={title} delay={80 * (i + 1)} className="flex gap-5">
                <div className="w-10 h-10 shrink-0 bg-primary text-white flex items-center justify-center">
                  <Icon size={18} />
                </div>
                <div>
                  <h3 className="text-lg">{title}</h3>
                  <p className="mt-2 font-sans text-base font-medium tracking-normal text-ink-soft">
                    {body}
                  </p>
                </div>
              </Reveal>
            ))}
          </div>
        </div>

        <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">Report received</h2>
              <p className="mt-3 text-ink-soft leading-relaxed">
                Thank you. Your report has been submitted successfully. Vigor Group treats all
                whistleblower reports with the highest level of confidentiality.
              </p>
              <button
                type="button"
                className="btn-ghost mt-7"
                onClick={() => {
                  setSent(false);
                  setFileName(null);
                }}
              >
                Submit another report
              </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 fd = new FormData(form);
                const file = fd.get("attachment");
                setError(null);
                setSubmitting(true);
                try {
                  let attachment: { filename: string; content: string } | null = null;
                  if (file instanceof File && file.size > 0) {
                    if (file.size > 5 * 1024 * 1024) {
                      throw new Error("Attachments must be 5 MB or smaller.");
                    }
                    attachment = { filename: file.name, content: await fileToBase64(file) };
                  }
                  await sendReport({
                    data: {
                      name: String(fd.get("name") ?? "") || undefined,
                      email: String(fd.get("email") ?? "") || undefined,
                      phone: String(fd.get("phone") ?? "") || undefined,
                      subject: String(fd.get("subject") ?? ""),
                      category: String(fd.get("category") ?? ""),
                      description: String(fd.get("description") ?? ""),
                      attachment,
                    },
                  });
                  form.reset();
                  setSent(true);
                } catch (err) {
                  setError(
                    err instanceof Error
                      ? err.message
                      : "Something went wrong. Please try again.",
                  );
                } finally {
                  setSubmitting(false);
                }
              }}
            >

              <h2 className="text-2xl">Submit a confidential report</h2>
              <p className="text-sm text-ink-soft leading-relaxed">
                Fields marked optional may be left blank to report anonymously.
              </p>

              <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">
                  Phone number <span className="text-ink-soft normal-case tracking-normal">(optional)</span>
                </span>
                <input
                  name="phone"
                  type="tel"
                  maxLength={40}
                  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">Subject</span>
                <input
                  name="subject"
                  required
                  maxLength={150}
                  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">Category</span>
                <select
                  name="category"
                  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 category
                  </option>
                  {categories.map((c) => (
                    <option key={c} value={c}>
                      {c}
                    </option>
                  ))}
                </select>
              </label>

              <label className="block">
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">Description</span>
                <textarea
                  name="description"
                  required
                  rows={6}
                  maxLength={5000}
                  placeholder="What happened, when, where and who was involved?"
                  className="mt-2 w-full bg-background border border-border px-4 py-3 focus:outline-none focus:border-primary"
                />
              </label>

              <div>
                <span className="text-xs uppercase tracking-[0.18em] font-semibold">
                  Attachment{" "}
                  <span className="text-ink-soft normal-case tracking-normal">(optional)</span>
                </span>
                <label className="mt-2 flex items-center gap-3 border border-dashed border-border bg-background px-4 py-3 cursor-pointer hover:border-primary transition-colors">
                  <Paperclip size={16} className="text-primary shrink-0" />
                  <span className="text-sm text-ink-soft truncate">
                    {fileName ?? "Attach a document, image or PDF"}
                  </span>
                  <input
                    type="file"
                    name="attachment"
                    className="sr-only"
                    onChange={(e) => setFileName(e.target.files?.[0]?.name ?? null)}
                  />
                </label>
              </div>

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

              <button type="submit" className="btn-primary" disabled={submitting}>
                {submitting ? "Submitting…" : "Submit report"}
              </button>

            </form>
          )}
        </Reveal>
      </section>
    </>
  );
}
