"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ConfirmDialog } from "@/components/admin/ConfirmDialog";
import { toast } from "@/components/admin/Toast";
import {
  ModuleItemsPanel,
  type PrebuiltModuleSchema,
} from "@/components/dashboard/ModuleItemsPanel";
import { AdvanceModulesPanel } from "@/components/dashboard/AdvanceModulesPanel";
import {
  EventOverviewCharts,
  type OverviewItem,
} from "@/components/dashboard/EventOverviewCharts";
import { ModuleIcon as ModuleSvgIcon } from "@/components/icons";
import {
  FetchError,
  apiDelete,
  apiGet,
  apiPatch,
  formatDate,
  formatDateShort,
  type PublicEvent,
} from "@/lib/client-api";

export function EventDetailView({
  event,
  modules,
  advanceFolderIds,
}: {
  event: PublicEvent;
  modules: PrebuiltModuleSchema[];
  advanceFolderIds?: string[];
}) {
  const router = useRouter();
  const [data, setData] = useState(event);
  const [editing, setEditing] = useState(false);
  const [title, setTitle] = useState(event.title);
  const [description, setDescription] = useState(event.description);
  const [eventDate, setEventDate] = useState(
    event.eventDate ? toLocalInput(event.eventDate) : "",
  );
  const [endDate, setEndDate] = useState(
    event.endDate ? toLocalInput(event.endDate) : "",
  );
  const [location, setLocation] = useState(event.location ?? "");
  const [saving, setSaving] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const [activeSlug, setActiveSlug] = useState<string | null>(
    modules[0]?.slug ?? null,
  );

  const reload = useCallback(async () => {
    try {
      const fresh = await apiGet<PublicEvent>(`/api/events/${data.id}`);
      setData(fresh);
    } catch {
      /* ignore */
    }
  }, [data.id]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    reload();
  }, [reload]);

  const onSave = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setSaving(true);
      const updated = await apiPatch<PublicEvent>(`/api/events/${data.id}`, {
        title,
        description,
        eventDate: eventDate ? new Date(eventDate).toISOString() : null,
        endDate: endDate ? new Date(endDate).toISOString() : null,
        location: location || null,
      });
      setData(updated);
      setEditing(false);
      toast("Event saved.", "success");
    } catch (err) {
      toast(
        err instanceof FetchError ? err.message : "Failed to save.",
        "error",
      );
    } finally {
      setSaving(false);
    }
  };

  const onDelete = async () => {
    try {
      await apiDelete(`/api/events/${data.id}`);
      toast("Event deleted.", "info");
      router.push("/events");
    } catch (err) {
      toast(
        err instanceof FetchError ? err.message : "Failed to delete.",
        "error",
      );
    }
  };

  const activeModule = useMemo(
    () => modules.find((m) => m.slug === activeSlug) ?? null,
    [modules, activeSlug],
  );

  const statusBadge = useMemo(() => {
    const color =
      data.status === "completed"
        ? "bg-emerald-100 text-emerald-700"
        : data.status === "cancelled"
          ? "bg-red-100 text-red-700"
          : "bg-blue-100 text-blue-700";
    return (
      <span
        className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium capitalize ${color}`}
      >
        {data.status}
      </span>
    );
  }, [data.status]);

  return (
    <div className="space-y-6">
      <header className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
        <div className="flex flex-wrap items-center gap-2 text-xs text-muted">
          <Link href="/events" className="hover:text-foreground">
            Events
          </Link>
          <span>/</span>
          <span className="text-foreground">{data.title || "Untitled"}</span>
        </div>
        <div className="mt-3 flex flex-wrap items-start justify-between gap-3">
          <div className="min-w-0 flex-1">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-2xl font-semibold tracking-tight">
                {data.title || "Untitled event"}
              </h1>
              {statusBadge}
            </div>
            {data.description ? (
              <p className="mt-1 text-sm text-muted">{data.description}</p>
            ) : null}
            <div className="mt-3 grid gap-2 text-xs sm:grid-cols-2 lg:grid-cols-4">
              <InfoCell label="Start" value={data.eventDate ? formatDateShort(data.eventDate) : "—"} />
              <InfoCell label="End" value={data.endDate ? formatDateShort(data.endDate) : "—"} />
              <InfoCell label="Location" value={data.location || "—"} />
              <InfoCell label="Updated" value={formatDate(data.updatedAt)} />
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Button
              variant="secondary"
              size="sm"
              onClick={() => setEditing((v) => !v)}
            >
              {editing ? "Cancel edit" : "Edit details"}
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setConfirmDelete(true)}
            >
              Delete event
            </Button>
          </div>
        </div>

        {editing ? (
          <form
            onSubmit={onSave}
            className="mt-5 grid gap-4 rounded-xl border border-border bg-surface-muted/30 p-4 sm:grid-cols-2"
          >
            <div className="sm:col-span-2">
              <FormLabel>Event title</FormLabel>
              <input
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                className="input"
                placeholder="e.g. Anika's Wedding Reception"
                required
              />
            </div>
            <div className="sm:col-span-2">
              <FormLabel>Description</FormLabel>
              <textarea
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="input min-h-[80px]"
                rows={3}
                placeholder="A short description for the dashboard"
              />
            </div>
            <div>
              <FormLabel>Start date & time</FormLabel>
              <input
                type="datetime-local"
                value={eventDate}
                onChange={(e) => setEventDate(e.target.value)}
                className="input"
              />
            </div>
            <div>
              <FormLabel>End date & time</FormLabel>
              <input
                type="datetime-local"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="input"
              />
            </div>
            <div className="sm:col-span-2">
              <FormLabel>Location</FormLabel>
              <input
                value={location}
                onChange={(e) => setLocation(e.target.value)}
                className="input"
                placeholder="Venue name or address"
              />
            </div>
            <div className="sm:col-span-2 flex justify-end gap-2">
              <Button
                type="button"
                variant="secondary"
                size="sm"
                onClick={() => setEditing(false)}
              >
                Cancel
              </Button>
              <Button type="submit" size="sm" isLoading={saving}>
                Save changes
              </Button>
            </div>
          </form>
        ) : null}
      </header>

      <EventOverviewSection eventId={data.id} />

      {modules.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-border bg-surface p-8 text-center">
          <p className="text-sm font-medium">No modules attached</p>
          <p className="mt-1 text-xs text-muted">
            This event doesn&apos;t have any modules yet.
          </p>
        </div>
      ) : (
        <section className="rounded-2xl border border-border bg-surface shadow-sm">
          <nav
            aria-label="Event modules"
            className="grid grid-cols-2 gap-2 border-b border-border bg-surface-muted/40 p-3 sm:grid-cols-3 lg:grid-cols-4"
          >
            {modules.map((m) => {
              const isActive = m.slug === activeSlug;
              return (
                <button
                  key={m.slug}
                  type="button"
                  onClick={() => setActiveSlug(m.slug)}
                  className={`group/module relative flex h-16 min-w-[180px] flex-1 items-center gap-3 overflow-hidden rounded-xl border transition-all ${
                    isActive
                      ? "border-rose-400 shadow-md shadow-rose-500/20"
                      : "border-border hover:border-rose-300"
                  }`}
                >
                  {m.image ? (
                    <>
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={m.image}
                        alt=""
                        aria-hidden
                        className="absolute inset-0 h-full w-full object-cover"
                      />
                      <div
                        className={`absolute inset-0 transition-opacity ${
                          isActive
                            ? "bg-gradient-to-r from-rose-50/85 via-rose-50/65 to-rose-100/40"
                            : "bg-gradient-to-r from-surface/80 via-surface/55 to-surface/15 group-hover/module:from-rose-50/75 group-hover/module:via-rose-50/55 group-hover/module:to-rose-100/25"
                        }`}
                      />
                    </>
                  ) : (
                    <span className="absolute inset-0 bg-gradient-to-br from-rose-50 via-pink-50 to-amber-50" />
                  )}
                  <span className="relative z-10 ml-3 grid h-10 w-10 shrink-0 place-items-center overflow-hidden rounded-lg bg-gradient-to-br from-rose-500 to-pink-600 text-white shadow-md shadow-rose-500/30 ring-2 ring-white/70">
                    {m.iconImage ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={m.iconImage}
                        alt=""
                        className="h-full w-full object-contain"
                      />
                    ) : (
                      <ModuleSvgIcon
                        name={m.icon}
                        className="h-5 w-5 text-white"
                      />
                    )}
                  </span>
                  <span className="relative z-10 truncate pr-3 text-sm font-semibold text-foreground drop-shadow-sm">
                    {m.name}
                  </span>
                </button>
              );
            })}
          </nav>

          <div className="p-5">
            {activeModule ? (
              <ModuleItemsPanel
                key={activeModule.slug}
                eventId={data.id}
                eventTitle={data.title}
                schema={activeModule}
                advanceFolderIds={advanceFolderIds}
              />
            ) : null}
          </div>
        </section>
      )}

      <AdvancePurchaseSection
        eventId={data.id}
        attachedFolderIds={advanceFolderIds ?? []}
      />

      <ConfirmDialog
        open={confirmDelete}
        title="Delete this event?"
        description="The event and all its module data will be permanently removed. This cannot be undone."
        confirmLabel="Delete event"
        tone="danger"
        pending={false}
        onConfirm={onDelete}
        onCancel={() => setConfirmDelete(false)}
      />

      <style jsx>{`
        :global(.input) {
          width: 100%;
          border-radius: 0.5rem;
          border: 1px solid var(--border);
          background: var(--surface);
          padding: 0.5rem 0.75rem;
          font-size: 0.875rem;
          color: var(--foreground);
          transition: border-color 0.15s ease;
        }
        :global(.input::placeholder) {
          color: var(--muted);
        }
        :global(.input:focus) {
          outline: none;
          border-color: var(--primary);
          box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary) 15%, transparent);
        }
      `}</style>
    </div>
  );
}

interface ModuleItemLite {
  moduleSlug: string;
  data: Record<string, unknown>;
}

function EventOverviewSection({ eventId }: { eventId: string }) {
  const [items, setItems] = useState<OverviewItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);

  const reload = useCallback(async () => {
    try {
      setLoading(true);
      const res = await apiGet<{ items: ModuleItemLite[] }>(
        `/api/events/${eventId}/items`,
      );
      setItems((res.items ?? []) as OverviewItem[]);
      setLoadError(null);
    } catch (err) {
      setLoadError(err instanceof Error ? err.message : "Failed to load overview.");
    } finally {
      setLoading(false);
    }
  }, [eventId]);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    reload();
  }, [reload]);

  return (
    <EventOverviewCharts
      items={items}
      loading={loading}
      error={loadError}
    />
  );
}

function toLocalInput(iso: string): string {
  const d = new Date(iso);
  const pad = (n: number) => `${n}`.padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

function InfoCell({ label, value }: { label: string; value: string }) {
  return (
    <div className="rounded-lg border border-border bg-surface px-3 py-2">
      <p className="text-[10px] font-medium uppercase tracking-wide text-muted">
        {label}
      </p>
      <p className="mt-0.5 text-sm font-medium text-foreground">{value}</p>
    </div>
  );
}

function FormLabel({ children }: { children: React.ReactNode }) {
  return (
    <label className="mb-1 block text-xs font-medium text-muted">
      {children}
    </label>
  );
}

interface AdvanceFolder {
  folderId: string;
  name: string;
  description: string;
}

interface AdvanceProduct {
  advanceModuleId: string;
  folderId: string;
  slug: string;
  name: string;
  image: string | null;
  description: string;
}

function AdvancePurchaseSection({
  eventId,
  attachedFolderIds,
}: {
  eventId: string;
  attachedFolderIds: string[];
}) {
  const attachedKey = attachedFolderIds.join(",");
  const [folders, setFolders] = useState<AdvanceFolder[]>([]);
  const [products, setProducts] = useState<AdvanceProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        setLoading(true);
        setError(null);
        const folderRes = await apiGet<Array<{ id: string; name: string; description: string; status: string }>>(
          `/api/advance-folders`,
        );
        if (cancelled) return;
        const allowed = new Set(attachedFolderIds);
        const allActive: AdvanceFolder[] = (folderRes ?? [])
          .filter((f) => (f.status ?? "active") === "active")
          .map((f) => ({
            folderId: f.id,
            name: f.name,
            description: f.description ?? "",
          }));
        const scopedFolders =
          allowed.size > 0
            ? allActive.filter((f) => allowed.has(f.folderId))
            : allActive;
        setFolders(scopedFolders);
        if (scopedFolders.length === 0) {
          setProducts([]);
          return;
        }
        const qs = scopedFolders
          .map((f) => `folderIds=${encodeURIComponent(f.folderId)}`)
          .join("&");
        const productRes = await apiGet<{
          items: Array<{
            id: string;
            folderId: string;
            name: string;
            slug: string;
            image: string | null;
            description: string;
            status: string;
          }>;
        }>(`/api/advance-modules?${qs}`);
        if (cancelled) return;
        setProducts(
          (productRes.items ?? [])
            .filter((m) => (m.status ?? "active") === "active")
            .map((m) => ({
              advanceModuleId: m.id,
              folderId: m.folderId,
              name: m.name,
              slug: m.slug,
              image: m.image ?? null,
              description: m.description ?? "",
            })),
        );
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof FetchError ? err.message : "Failed to load advance modules.");
          setFolders([]);
          setProducts([]);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [attachedKey, eventId]);

  if (loading) {
    return (
      <section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
        <p className="text-center text-sm text-muted">Loading advance modules…</p>
      </section>
    );
  }
  if (error) {
    return (
      <section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
        <p className="text-center text-sm text-red-600">{error}</p>
      </section>
    );
  }
  if (folders.length === 0 || products.length === 0) {
    return (
      <section className="space-y-2 rounded-2xl border border-dashed border-border bg-surface p-6 text-center shadow-sm">
        <h2 className="text-sm font-semibold text-foreground">
          Advance modules by category
        </h2>
        <p className="text-xs text-muted">
          No advance products yet. Add folders and products in Admin → Advance Modules, then come back here.
        </p>
      </section>
    );
  }
  return (
    <section className="space-y-3 rounded-2xl border border-border bg-surface p-5 shadow-sm">
      <header>
        <h2 className="text-sm font-semibold text-foreground">
          Advance modules by category
        </h2>
        <p className="mt-1 text-xs text-muted">
          Browse products grouped by folder. Set quantities, mark purchased, edit, or remove items from your event checklist.
        </p>
      </header>
      <AdvanceModulesPanel
        eventId={eventId}
        advanceFolders={folders}
        advanceModules={products}
        enabled
      />
    </section>
  );
}

