"use client";

import Link from "next/link";
import { useState } from "react";
import { useRooSports } from "@/components/app-provider";
import type { SportName } from "@/lib/demo-data";

const sportOptions: SportName[] = ["Soccer", "Basketball", "Touch Rugby"];

export default function CoachVerificationPage() {
  const {
    coachStatus,
    coachApplication,
    coachApplicationLoading,
    submitCoachApplication,
  } = useRooSports();
  const [wwccNumber, setWwccNumber] = useState("");
  const [expiryDate, setExpiryDate] = useState("");
  const [suburb, setSuburb] = useState("");
  const [preferredSports, setPreferredSports] = useState<SportName[]>([]);
  const [availability, setAvailability] = useState("");
  const [experience, setExperience] = useState("");
  const [evidenceName, setEvidenceName] = useState("");
  const [consent, setConsent] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState("");

  if (coachApplicationLoading) {
    return (
      <div className="grid min-h-[32rem] place-items-center text-sm font-bold text-[#617078]">
        Loading your volunteer application...
      </div>
    );
  }

  if (coachStatus === "pending" || coachStatus === "approved") {
    const isApproved = coachStatus === "approved";
    return (
      <div className="pb-10 pt-4 text-[#0b0f12] sm:pt-10">
        <section className="grid min-h-[34rem] items-center gap-12 lg:grid-cols-[0.9fr_1.1fr]">
          <div>
            <p className="flex items-center gap-3 text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#617078]">
              <span className={`h-2.5 w-2.5 rounded-full ${isApproved ? "bg-[#4c9c76]" : "bg-[#ef7d00]"}`} />
              Volunteer coach application
            </p>
            <h1 className="mt-5 max-w-xl text-[clamp(3rem,5vw,4.75rem)] font-extrabold leading-[0.94] tracking-[-0.065em]">
              {isApproved ? "You are ready to help." : "Your application is with us."}
            </h1>
            <p className="mt-7 max-w-xl text-base leading-7 text-[#617078] sm:text-lg">
              {isApproved
                ? "Choose a suitable session, register your interest and wait for the RooSports team to confirm the assignment."
                : "RooSports will review your Working With Children Check before any player or safety information becomes available."}
            </p>
            <div className="mt-9 flex flex-wrap gap-4">
              <Link
                href={isApproved ? "/coach" : "/profile"}
                className="inline-flex items-center gap-3 rounded-full bg-[#0b0f12] px-6 py-3.5 text-sm font-extrabold text-white transition hover:bg-[#ff9a2f] hover:text-[#0b0f12]"
              >
                {isApproved ? "Open coach workspace" : "View profile status"}
                <span className="material-symbols-outlined text-xl">arrow_forward</span>
              </Link>
              <Link href="/dashboard" className="inline-flex items-center px-3 py-3 text-sm font-extrabold">
                Return home
              </Link>
            </div>
          </div>

          <aside className="relative overflow-hidden rounded-[2.5rem] bg-[#dbe9f0] p-8 sm:p-11">
            <span className="absolute -right-14 -top-16 h-52 w-52 rounded-full bg-[#ffd47e]" />
            <span className="absolute right-5 top-8 h-28 w-28 rounded-full border-[18px] border-white/45" />
            <div className="relative">
              <span className="inline-flex rounded-full bg-[#0b0f12] px-4 py-2 text-[10px] font-extrabold uppercase tracking-[0.16em] text-white">
                {isApproved ? "Approved" : "Under review"}
              </span>
              <h2 className="mt-8 text-3xl font-extrabold tracking-[-0.05em]">Application summary</h2>
              <dl className="mt-8 space-y-6 text-sm">
                <div className="flex items-center justify-between gap-5">
                  <dt className="text-[#617078]">WWCC</dt>
                  <dd className="font-extrabold">Ending in {coachApplication?.wwccLastFour || "----"}</dd>
                </div>
                <div className="flex items-center justify-between gap-5">
                  <dt className="text-[#617078]">Expiry</dt>
                  <dd className="font-extrabold">{coachApplication?.expiryDate || "Pending"}</dd>
                </div>
                <div className="flex items-start justify-between gap-5">
                  <dt className="text-[#617078]">Preferred sports</dt>
                  <dd className="max-w-[65%] text-right font-extrabold">
                    {coachApplication?.preferredSports.join(", ") || "Not specified"}
                  </dd>
                </div>
              </dl>
              {!isApproved && (
                <p className="mt-10 flex gap-3 rounded-2xl bg-white/50 p-4 text-xs leading-5 text-[#53636c] backdrop-blur">
                  <span className="material-symbols-outlined text-xl text-[#0b0f12]">lock</span>
                  Your parent account and family tools continue to work normally while the review is underway.
                </p>
              )}
            </div>
          </aside>
        </section>
      </div>
    );
  }

  const toggleSport = (sport: SportName) => {
    setPreferredSports((current) =>
      current.includes(sport) ? current.filter((item) => item !== sport) : [...current, sport],
    );
  };

  return (
    <div className="pb-12 pt-4 text-[#0b0f12] sm:pt-10">
      <section className="grid gap-12 lg:grid-cols-[0.78fr_1.22fr] lg:gap-20">
        <div className="lg:sticky lg:top-28 lg:self-start">
          <p className="flex items-center gap-3 text-[11px] font-extrabold uppercase tracking-[0.18em] text-[#617078]">
            <span className="h-2.5 w-2.5 rounded-full bg-[#ef7d00]" />
            Help your local game
          </p>
          <h1 className="mt-5 text-[clamp(3rem,5vw,4.75rem)] font-extrabold leading-[0.94] tracking-[-0.065em]">
            Apply to volunteer as a coach.
          </h1>
          <p className="mt-7 max-w-lg text-base leading-7 text-[#617078] sm:text-lg">
            Tell us when and where you can help. Approval adds a separate coach workspace without changing your parent account.
          </p>
          <div className="mt-10 space-y-5 text-sm font-bold">
            {[
              ["looks_one", "Submit your WWCC and preferences"],
              ["looks_two", "RooSports reviews your application"],
              ["looks_3", "Request a session and await assignment"],
            ].map(([icon, copy]) => (
              <div key={copy} className="flex items-center gap-4">
                <span className="material-symbols-outlined grid h-10 w-10 place-items-center rounded-full bg-white/50 text-[#ef7d00] shadow-[0_10px_30px_rgba(25,45,58,0.06)]">
                  {icon}
                </span>
                {copy}
              </div>
            ))}
          </div>
        </div>

        <form
          onSubmit={async (event) => {
            event.preventDefault();
            setIsSubmitting(true);
            setSubmitError("");
            try {
              await submitCoachApplication({
                wwccNumber,
                expiryDate,
                suburb,
                preferredSports,
                availability,
                experience,
              });
            } catch (error) {
              setSubmitError(error instanceof Error ? error.message : "Unable to submit application.");
              setIsSubmitting(false);
            }
          }}
          className="rounded-[2.5rem] bg-white/50 p-6 shadow-[0_24px_70px_rgba(25,45,58,0.08)] ring-1 ring-white/80 backdrop-blur-xl sm:p-10"
        >
          <div>
            <span className="inline-flex rounded-full bg-[#dbe9f0] px-4 py-2 text-[10px] font-extrabold uppercase tracking-[0.16em]">
              About you
            </span>
            <h2 className="mt-5 text-3xl font-extrabold tracking-[-0.05em]">Safety and availability</h2>
            <p className="mt-3 text-sm leading-6 text-[#68747c]">Fields marked required help us make a safe, practical match.</p>
            {(coachStatus === "rejected" || coachStatus === "expired") && (
              <p className="mt-4 rounded-2xl bg-[#f8e2df] px-4 py-3 text-sm font-bold text-[#8a433a]">
                {coachStatus === "expired"
                  ? "Your WWCC has expired. Enter the renewed details below and resubmit for review."
                  : "Your previous application was not approved. Update the details below and resubmit for review."}
              </p>
            )}
          </div>

          <div className="mt-9 grid gap-6 sm:grid-cols-2">
            <label className="text-sm font-extrabold">
              WWCC number
              <input
                required
                minLength={6}
                value={wwccNumber}
                onChange={(event) => setWwccNumber(event.target.value)}
                placeholder="WWC1234567E"
                className="mt-2 w-full rounded-2xl bg-white/70 px-4 py-3.5 font-medium outline-none ring-1 ring-[#bfd0d8]/60 transition focus:ring-2 focus:ring-[#ef7d00]"
              />
            </label>
            <label className="text-sm font-extrabold">
              Expiry date
              <input
                required
                type="date"
                min={new Date().toISOString().slice(0, 10)}
                value={expiryDate}
                onChange={(event) => setExpiryDate(event.target.value)}
                className="mt-2 w-full rounded-2xl bg-white/70 px-4 py-3.5 font-medium outline-none ring-1 ring-[#bfd0d8]/60 transition focus:ring-2 focus:ring-[#ef7d00]"
              />
            </label>
            <label className="text-sm font-extrabold">
              Home suburb
              <input
                required
                value={suburb}
                onChange={(event) => setSuburb(event.target.value)}
                placeholder="e.g. Surry Hills"
                className="mt-2 w-full rounded-2xl bg-white/70 px-4 py-3.5 font-medium outline-none ring-1 ring-[#bfd0d8]/60 transition focus:ring-2 focus:ring-[#ef7d00]"
              />
            </label>
            <label className="text-sm font-extrabold">
              Usual availability
              <select
                required
                value={availability}
                onChange={(event) => setAvailability(event.target.value)}
                className="mt-2 w-full rounded-2xl bg-white/70 px-4 py-3.5 font-medium outline-none ring-1 ring-[#bfd0d8]/60 transition focus:ring-2 focus:ring-[#ef7d00]"
              >
                <option value="">Choose a time</option>
                <option>Weekday evenings</option>
                <option>Saturday mornings</option>
                <option>Saturday afternoons</option>
                <option>Sunday mornings</option>
                <option>Flexible weekends</option>
              </select>
            </label>
          </div>

          <fieldset className="mt-7">
            <legend className="text-sm font-extrabold">Sports you can support</legend>
            <div className="mt-3 flex flex-wrap gap-3">
              {sportOptions.map((sport) => {
                const selected = preferredSports.includes(sport);
                return (
                  <button
                    key={sport}
                    type="button"
                    aria-pressed={selected}
                    onClick={() => toggleSport(sport)}
                    className={`rounded-full px-4 py-2.5 text-sm font-extrabold transition ${
                      selected ? "bg-[#0b0f12] text-white" : "bg-white/65 text-[#53636c] hover:bg-white"
                    }`}
                  >
                    {sport}
                  </button>
                );
              })}
            </div>
            {preferredSports.length === 0 && <p className="mt-2 text-xs text-[#7a6a5b]">Choose at least one sport.</p>}
          </fieldset>

          <label className="mt-7 block text-sm font-extrabold">
            Relevant experience
            <textarea
              required
              rows={4}
              value={experience}
              onChange={(event) => setExperience(event.target.value)}
              placeholder="Coaching, playing, first aid or community experience"
              className="mt-2 w-full resize-none rounded-2xl bg-white/70 px-4 py-3.5 font-medium outline-none ring-1 ring-[#bfd0d8]/60 transition focus:ring-2 focus:ring-[#ef7d00]"
            />
          </label>

          <label className="mt-7 flex cursor-pointer items-center justify-between gap-4 rounded-2xl bg-[#dbe9f0]/70 p-4 text-sm font-extrabold">
            <span className="flex items-center gap-3">
              <span className="material-symbols-outlined text-[#ef7d00]">upload_file</span>
              {evidenceName || "Attach WWCC evidence (optional)"}
            </span>
            <span className="rounded-full bg-white px-4 py-2 text-xs">Choose file</span>
            <input
              type="file"
              accept=".pdf,.jpg,.jpeg,.png"
              className="sr-only"
              onChange={(event) => setEvidenceName(event.target.files?.[0]?.name || "")}
            />
          </label>

          <label className="mt-7 flex items-start gap-3 text-sm leading-6 text-[#53636c]">
            <input
              required
              type="checkbox"
              checked={consent}
              onChange={(event) => setConsent(event.target.checked)}
              className="mt-1 h-4 w-4 accent-[#ef7d00]"
            />
            I consent to RooSports reviewing these details for volunteer coaching eligibility.
          </label>

          <button
            type="submit"
            disabled={!consent || preferredSports.length === 0 || isSubmitting}
            className="mt-8 flex w-full items-center justify-between rounded-full bg-[#ff9a2f] py-2 pl-6 pr-2 text-sm font-extrabold transition hover:bg-[#0b0f12] hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
          >
            {isSubmitting ? "Submitting..." : "Submit application"}
            <span className="grid h-12 w-12 place-items-center rounded-full bg-white text-[#0b0f12]">
              <span className="material-symbols-outlined">arrow_forward</span>
            </span>
          </button>
          {submitError && <p className="mt-3 text-sm font-bold text-[#9a4338]">{submitError}</p>}
        </form>
      </section>
    </div>
  );
}
