"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";

// Added: reusable Australian states/territories list
import { AUSTRALIAN_STATES } from "@/lib/australian-states";

const inputClass =
  "mt-2 h-11 w-full rounded-xl border border-slate-200/80 bg-white px-4 text-sm font-medium text-[#0D1B2A] outline-none transition focus:border-[#1D4ED8] focus:ring-2 focus:ring-[#1D4ED8]/20 disabled:cursor-not-allowed disabled:opacity-55";

type EventManagementFormProps = {
  event: {
    id: string;
    title: string;
    leagueId: string;
    venueId: string;
    eventType: string;
    startsAt: string;
    endsAt: string;
    capacity: number;
    minParticipants: number;
    registrations: number;
    priceCents: number;
    status: string;
    notes: string;
    cancellationReason: string;
    refundableBalanceCents: number;
  };
  leagues: Array<{ id: string; label: string; priceCents: number }>;
  // Added stateCode so the Edit Event venue list can be filtered by state/territory.
  venues: Array<{ id: string; label: string; stateCode: string }>;
};

export function EventManagementForm({ event, leagues, venues }: EventManagementFormProps) {
  const router = useRouter();
  const [isSaving, setIsSaving] = useState(false);
  const [isCancelling, setIsCancelling] = useState(false);
  const [isRetryingEmails, setIsRetryingEmails] = useState(false);
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");
  const isCancelled = event.status === "cancelled";

  // Added: use the event's current venue to determine its current state/territory.
  const currentVenue = venues.find((venue) => venue.id === event.venueId);

  const [selectedState, setSelectedState] = useState(
    currentVenue?.stateCode ?? "",
  );
  const [selectedVenueId, setSelectedVenueId] = useState(event.venueId);

  // Only show venues belonging to the selected state/territory.
  const filteredVenues = venues.filter(
    (venue) => venue.stateCode === selectedState,
  );

  // Used to disable states that currently have no active venues.
  const activeStateCodes = new Set(venues.map((venue) => venue.stateCode));

  const save = async (formEvent: React.FormEvent<HTMLFormElement>) => {
    formEvent.preventDefault();
    setIsSaving(true);
    setError("");
    setMessage("");
    const form = new FormData(formEvent.currentTarget);
    const submitter = (formEvent.nativeEvent as Event & {
      submitter?: HTMLButtonElement | null;
    }).submitter;
    if (submitter?.name === "lifecycleAction") {
      form.set("lifecycleAction", submitter.value);
    }
    const response = await fetch(`/api/admin/events/${event.id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(Object.fromEntries(form)),
    });
    const payload = (await response.json()) as { error?: string };
    if (!response.ok) {
      setError(payload.error || "Unable to update this event.");
    } else {
      setMessage("Event changes saved.");
      router.refresh();
    }
    setIsSaving(false);
  };

  const cancel = async (formEvent: React.FormEvent<HTMLFormElement>) => {
    formEvent.preventDefault();
    setIsCancelling(true);
    setError("");
    setMessage("");
    const form = new FormData(formEvent.currentTarget);
    const response = await fetch(`/api/admin/events/${event.id}/cancel`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(Object.fromEntries(form)),
    });
    const payload = (await response.json()) as { error?: string; refundRequiredCount?: number };
    if (!response.ok) {
      setError(payload.error || "Unable to cancel this event.");
    } else {
      setMessage(
        payload.refundRequiredCount
          ? `Event cancelled. ${payload.refundRequiredCount} payment(s) now require refund review.`
          : "Event cancelled. No paid orders require a refund.",
      );
      router.refresh();
    }
    setIsCancelling(false);
  };

  const retryEmails = async () => {
    setIsRetryingEmails(true);
    setError("");
    setMessage("");
    try {
      const response = await fetch(`/api/admin/events/${event.id}/notifications/retry`, { method: "POST" });
      const payload = (await response.json()) as { error?: string; sent?: number; failed?: number };
      if (!response.ok) throw new Error(payload.error || "Unable to retry event emails.");
      setMessage(payload.failed ? `${payload.sent || 0} email(s) sent; ${payload.failed} still need attention.` : `${payload.sent || 0} queued or failed event email(s) sent.`);
      router.refresh();
    } catch (retryError) {
      setError(retryError instanceof Error ? retryError.message : "Unable to retry event emails.");
    } finally {
      setIsRetryingEmails(false);
    }
  };

  return (
    <div className="mt-6 grid gap-5 xl:grid-cols-[1.2fr_0.8fr]">
      <form onSubmit={save} className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs sm:p-7">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#F97316]">Event settings</p>
          <span className="text-xs font-bold text-[#72838a]">{event.registrations} active registrations</span>
        </div>
        <fieldset disabled={isCancelled} className="mt-5 grid gap-5 sm:grid-cols-2">
          <label className="sm:col-span-2 text-xs font-extrabold text-[#405760]">
            Event title
            <input required minLength={3} maxLength={150} name="title" defaultValue={event.title} className={inputClass} />
          </label>
          <label className="sm:col-span-2 text-xs font-extrabold text-[#405760]">
            Program and age group
            <select required name="leagueId" defaultValue={event.leagueId} className={inputClass}>
              {leagues.map((league) => <option key={league.id} value={league.id}>{league.label}</option>)}
            </select>
          </label>
          {/* Added: State/Territory filter for the event venue */}
          <label className="text-xs font-extrabold text-[#405760]">
            State / Territory
            <select
              required
              value={selectedState}
              className={inputClass}
              onChange={(changeEvent) => {
                setSelectedState(changeEvent.target.value);

                // Reset the venue whenever the state changes.
                setSelectedVenueId("");
              }}
            >
              <option value="" disabled>
                Choose a state
              </option>

              {AUSTRALIAN_STATES.map((state) => (
                <option
                  key={state.value}
                  value={state.value}
                  disabled={!activeStateCodes.has(state.value)}
                >
                  {state.label}
                  {!activeStateCodes.has(state.value)
                    ? " (No active venues)"
                    : ""}
                </option>
              ))}
            </select>
          </label>

          {/* Updated: only show venues in the selected state/territory */}
          <label className="text-xs font-extrabold text-[#405760]">
            Venue
            <select
              required
              name="venueId"
              value={selectedVenueId}
              disabled={!selectedState}
              className={inputClass}
              onChange={(changeEvent) =>
                setSelectedVenueId(changeEvent.target.value)
              }
            >
              <option value="" disabled>
                {!selectedState
                  ? "Choose a state first"
                  : filteredVenues.length === 0
                    ? "No active venues in this state"
                    : "Choose an active venue"}
              </option>

              {filteredVenues.map((venue) => (
                <option key={venue.id} value={venue.id}>
                  {venue.label}
                </option>
              ))}
            </select>
          </label>
          <label className="text-xs font-extrabold text-[#405760]">
            Start date and time
            <input required type="datetime-local" name="startsAt" defaultValue={event.startsAt} className={inputClass} />
          </label>
          <label className="text-xs font-extrabold text-[#405760]">
            End date and time
            <input required type="datetime-local" name="endsAt" defaultValue={event.endsAt} className={inputClass} />
          </label>
          <label className="text-xs font-extrabold text-[#405760]">
            Event type
            <select name="eventType" defaultValue={event.eventType} className={inputClass}>
              <option value="combined_session">Combined session</option>
              <option value="practice">Practice</option>
              <option value="match">Match</option>
            </select>
          </label>
          <div className="text-xs font-extrabold text-[#405760]">
            Lifecycle status
            <div className={`${inputClass} flex items-center capitalize`}>
              {event.status.replaceAll("_", " ")}
            </div>
            <p className="mt-2 font-medium leading-5 text-[#718289]">
              Registration totals manage confirmation and full status automatically.
            </p>
          </div>
          <label className="text-xs font-extrabold text-[#405760]">
            Player capacity
            <input required type="number" name="capacity" min={Math.max(event.registrations, 1)} max={500} defaultValue={event.capacity} className={inputClass} />
          </label>
          <label className="text-xs font-extrabold text-[#405760]">
            Minimum participants
            <input required type="number" name="minParticipants" min={1} max={500} defaultValue={event.minParticipants} className={inputClass} />
          </label>
          <label className="text-xs font-extrabold text-[#405760]">
            Price per player (AUD)
            <input required type="number" name="price" min={0} max={10000} step="0.01" defaultValue={(event.priceCents / 100).toFixed(2)} className={inputClass} />
          </label>
          <label className="sm:col-span-2 text-xs font-extrabold text-[#405760]">
            Public arrival notes
            <textarea name="notes" rows={5} maxLength={3000} defaultValue={event.notes} className={`${inputClass} h-auto py-3`} />
          </label>
        </fieldset>
        {!isCancelled && (
          <div className="mt-6 flex flex-wrap items-center justify-between gap-3">
            <p className="max-w-xl text-xs leading-5 text-[#718289]">
              Price changes apply to future bookings only. Existing payment records retain the amount originally charged.
            </p>
            <div className="flex flex-wrap items-center gap-2">
              {event.status === "draft" && (
                <button
                  type="submit"
                  name="lifecycleAction"
                  value="publish"
                  disabled={isSaving || !selectedState || !selectedVenueId}
                  className="rounded-xl bg-[#F97316] px-5 py-2.5 text-xs font-semibold text-white shadow-xs transition hover:bg-[#ea580c] disabled:opacity-50"
                >
                  {isSaving ? "Saving..." : "Publish event"}
                </button>
              )}
              {event.status !== "draft" && (
                <button
                  type="submit"
                  name="lifecycleAction"
                  value="complete"
                  disabled={isSaving || !selectedState || !selectedVenueId}
                  className="rounded-xl border border-slate-200/80 bg-white px-5 py-2.5 text-xs font-semibold text-[#0D1B2A] shadow-xs transition hover:bg-slate-50 disabled:opacity-50"
                >
                  Mark completed
                </button>
              )}
              <button
                type="submit"
                disabled={isSaving || !selectedState || !selectedVenueId}
                className="rounded-xl bg-[#1D4ED8] px-5 py-2.5 text-xs font-semibold text-white shadow-xs transition hover:bg-[#1e40af] disabled:opacity-50"
              >
                {isSaving ? "Saving..." : "Save changes"}
              </button>
            </div>
          </div>
        )}
      </form>

      <aside className="space-y-5">
        <section className="rounded-2xl border border-slate-200/80 bg-white p-6 shadow-xs sm:p-7">
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#53717d]">Lifecycle guide</p>
          <div className="mt-5 space-y-4 text-xs leading-5 text-[#5f737c]">
            <p><strong className="text-[#263d47]">Draft:</strong> hidden from customers and unavailable for new bookings.</p>
            <p><strong className="text-[#263d47]">Pending threshold:</strong> published while waiting for the minimum participant count.</p>
            <p><strong className="text-[#263d47]">Confirmed / Full:</strong> managed automatically as registrations reach the event threshold and capacity.</p>
            <p><strong className="text-[#263d47]">Cancelled:</strong> registrations stop and paid orders move to Payments for a separate refund decision.</p>
          </div>
        </section>

        <section className="rounded-[1.75rem] bg-white/58 p-6 sm:p-7">
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#53717d]">Email delivery</p>
          <p className="mt-3 text-xs leading-5 text-[#65777e]">Retry any queued or failed event notices after fixing the email configuration. Delivered notices are never sent again.</p>
          <button type="button" onClick={retryEmails} disabled={isRetryingEmails} className="mt-4 w-full rounded-full border border-[#78939c]/30 bg-white px-5 py-3 text-xs font-extrabold text-[#263d47] transition hover:bg-[#edf4f6] disabled:opacity-50">
            {isRetryingEmails ? "Retrying emails..." : "Retry undelivered emails"}
          </button>
        </section>

        <section className="rounded-[1.75rem] bg-[#fff5e7]/72 p-6 sm:p-7">
          <p className="text-[10px] font-extrabold uppercase tracking-[0.16em] text-[#aa5b10]">Terminate event</p>
          {isCancelled ? (
            <div className="mt-4">
              <p className="text-sm font-extrabold text-[#6f3c16]">This event is cancelled.</p>
              <p className="mt-2 text-xs leading-5 text-[#805d43]">{event.cancellationReason}</p>
              {event.refundableBalanceCents > 0 && (
                <Link href="/admin/payments?status=refund-required" className="mt-4 inline-flex items-center gap-2 text-xs font-extrabold text-[#9d4d00]">
                  Review outstanding refunds
                  <span className="material-symbols-outlined text-[17px]">arrow_forward</span>
                </Link>
              )}
            </div>
          ) : (
            <form onSubmit={cancel} className="mt-4">
              <label className="text-xs font-extrabold text-[#6f4b2d]">
                Cancellation reason
                <textarea required minLength={5} maxLength={1000} name="reason" rows={4} placeholder="Explain what customers should be told" className={`${inputClass} h-auto py-3`} />
              </label>
              <button type="submit" disabled={isCancelling} className="mt-4 w-full rounded-full bg-[#9c3f32] px-5 py-3 text-xs font-extrabold text-white transition hover:bg-[#853429] disabled:opacity-50">
                {isCancelling ? "Cancelling..." : "Cancel event and registrations"}
              </button>
              <p className="mt-3 text-[11px] leading-5 text-[#8b6a51]">Refunds are not issued automatically. Paid orders are added to the refund-required queue.</p>
            </form>
          )}
        </section>
        {message && <p className="rounded-2xl bg-[#ddf3e8] px-4 py-3 text-xs font-bold text-[#28664b]">{message}</p>}
        {error && <p className="rounded-2xl bg-[#f8e2de] px-4 py-3 text-xs font-bold text-[#8e3d32]">{error}</p>}
      </aside>
    </div>
  );
}
