import type { Event, EventMedia, EventStatus, ListingType, Media } from "@prisma/client";

import { deleteEventAction, duplicateEventAction, saveEventAction } from "@/app/(admin)/admin/dogadjaji/actions";
import { AdminDeleteButton } from "@/components/admin/common/AdminDeleteButton";
import { AdminSaveNotice } from "@/components/admin/common/AdminSaveNotice";
import { UnsavedChangesWatcher } from "@/components/admin/common/UnsavedChangesWatcher";
import { AdminDateTimeField } from "@/components/admin/forms/AdminDateTimeField";
import { RegionPicker } from "@/components/common/RegionPicker";
import { MediaFieldPicker } from "@/components/admin/media/MediaFieldPicker";
import { AiCopyAssist } from "@/components/portal/forms/AiCopyAssist";
import { VideoEmbedField } from "@/components/admin/forms/VideoEmbedField";
import { EventGalleryManager } from "@/components/admin/media/EventGalleryManager";
import { formatDateTimeLocalInput } from "@/lib/module-formatters";
import { SubmitButton } from "@/components/common/SubmitButton";

type CompanyOption = {
  id: string;
  name: string;
  type: ListingType;
  city: { nameSr: string } | null;
};

type EventDetails = Event & {
  company?: { id: string; name: string; slug: string; type: ListingType } | null;
  coverMedia?: Media | null;
  gallery?: Array<EventMedia & { media: Media }>;
};

const EVENT_STATUS_OPTIONS: Array<{ value: EventStatus; label: string }> = [
  { value: "UPCOMING", label: "Predstojeći" },
  { value: "HELD", label: "Održan" },
  { value: "CANCELED", label: "Otkazan" },
];

const statusColors: Record<EventStatus, string> = {
  UPCOMING: "bg-emerald-100 text-emerald-800 border-emerald-200",
  HELD: "bg-blue-100 text-blue-800 border-blue-200",
  CANCELED: "bg-red-100 text-red-700 border-red-200",
};

// ─── Section wrapper ──────────────────────────────────────────────────────────

function FormSection({
  title,
  icon,
  children,
  elevated = false,
}: {
  title: string;
  icon: React.ReactNode;
  children: React.ReactNode;
  /** When true, raises z-index so that absolute-positioned child popovers
   * (datetime pickers, dropdowns) stack above sibling sections that come
   * after this one in DOM order. */
  elevated?: boolean;
}) {
  return (
    <section
      className={`relative rounded-2xl border border-border bg-white shadow-sm ${elevated ? "z-30" : ""}`}
    >
      <div className="flex items-center gap-3 rounded-t-2xl border-b border-border/60 bg-muted/40 px-5 py-4">
        <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-white text-primary shadow-sm border border-border/60">
          {icon}
        </div>
        <h3 className="text-sm font-bold uppercase tracking-[0.12em] text-foreground">{title}</h3>
      </div>
      <div className="p-5">{children}</div>
    </section>
  );
}

// ─── Field helper ─────────────────────────────────────────────────────────────

function Field({
  label,
  hint,
  children,
}: {
  label: React.ReactNode;
  hint?: string;
  children: React.ReactNode;
}) {
  return (
    <div className="space-y-1.5">
      <label className="block text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">
        {label}
      </label>
      {children}
      {hint ? <p className="text-xs leading-5 text-muted-foreground/70">{hint}</p> : null}
    </div>
  );
}

const inputCls = "adminx-input";
const selectCls = "adminx-select";
const textareaCls = "adminx-textarea";

// ─── Main component ───────────────────────────────────────────────────────────

export function EventForm({
  event,
  companies,
}: {
  event?: EventDetails | null;
  companies: CompanyOption[];
}) {
  const isEdit = Boolean(event?.id);

  return (
    <div className="space-y-5">
      <form action={saveEventAction} className="space-y-5">
        <UnsavedChangesWatcher />
        <input type="hidden" name="id" value={event?.id ?? ""} />

        {/* ── Top action bar ───────────────────────────────── */}
        <div className="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-border bg-white px-5 py-4 shadow-sm">
          <div>
            <p className="text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">
              {isEdit ? "Uređivanje događaja" : "Novi događaj"}
            </p>
            <p className="mt-0.5 text-sm font-semibold text-foreground">
              {isEdit ? (event?.title ?? "—") : "Popunite podatke o događaju"}
            </p>
          </div>
          <div className="flex items-center gap-3">
            {event?.id ? (
              <>
                {/* Dupliciraj — koristi formAction da override-uje parent
                    save action (isti pattern kao u MagazineArticleForm —
                    sprečava nested <form> hydration bug). Pravi novi
                    događaj sa istim sadržajem ali +365 dana datum. */}
                <SubmitButton
                  formAction={duplicateEventAction}
                  title="Dupliciraj kao novo izdanje (kopira sve, datum +365 dana)"
                  className="inline-flex h-9 items-center gap-1.5 rounded-full border border-border bg-white px-3 text-xs font-semibold text-foreground transition hover:border-primary/40 hover:bg-[#fff4f0]"
                >
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
                  </svg>
                  Dupliciraj
                </SubmitButton>
                <AdminDeleteButton
                  action={deleteEventAction}
                  title="Obrisati događaj?"
                  description="Događaj će biti uklonjen iz admina i javnog kalendara portala."
                  triggerLabel="Obriši"
                  inputs={[{ name: "id", value: event.id }]}
                />
              </>
            ) : null}
            <SubmitButton className="primary-button h-10 px-5 text-sm">
              Sačuvaj događaj
            </SubmitButton>
          </div>
        </div>
        <AdminSaveNotice message="Događaj je sačuvan." />

        {/* ── Two-column layout ────────────────────────────── */}
        <div className="grid gap-5 2xl:grid-cols-[minmax(0,1fr)_320px]">

          {/* Left column */}
          <div className="space-y-5">

            {/* Osnovni podaci */}
            <FormSection
              title="Osnovni podaci"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /><polyline points="14 2 14 8 20 8" /><line x1="16" y1="13" x2="8" y2="13" /><line x1="16" y1="17" x2="8" y2="17" />
                </svg>
              }
            >
              <div className="space-y-4">
                <Field label="Organizator (kompanija)" hint="Opciono. Ako događaj objavljuje fizičko lice, ostavite prazno i unesite kontakt ispod.">
                  <select name="companyId" defaultValue={event?.companyId ?? ""} className={selectCls}>
                    <option value="">— Fizičko lice / bez profila —</option>
                    {companies.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.name} · {c.type === "PLACE" ? "Mesto" : "Kompanija"}{c.city?.nameSr ? ` · ${c.city.nameSr}` : ""}
                      </option>
                    ))}
                  </select>
                </Field>

                <div className="grid gap-4 sm:grid-cols-3">
                  <Field label="Ime organizatora" hint="Obavezno samo ako događaj nije vezan za profil.">
                    <input name="ownerName" defaultValue={event?.ownerName ?? ""} className={inputCls} placeholder="npr. Marko Marković" />
                  </Field>
                  <Field label="Telefon">
                    <input name="ownerPhone" defaultValue={event?.ownerPhone ?? ""} className={inputCls} placeholder="+381..." />
                  </Field>
                  <Field label="E-mail">
                    <input name="ownerEmail" type="email" defaultValue={event?.ownerEmail ?? ""} className={inputCls} placeholder="ime@email.com" />
                  </Field>
                </div>

                <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_200px]">
                  <Field label="Naslov događaja">
                    <input required name="title" defaultValue={event?.title ?? ""} className={inputCls} placeholder="npr. Letnji festival muzike" />
                  </Field>
                  <Field label="Slug">
                    <input name="slug" defaultValue={event?.slug ?? ""} className={inputCls} placeholder="letnji-festival-muzike" />
                  </Field>
                </div>

                <Field
                  label={
                    <span className="flex w-full items-center justify-between gap-2">
                      <span>Opis</span>
                      <AiCopyAssist targetSelector="textarea[name='description']" category="event" />
                    </span>
                  }
                >
                  <textarea
                    name="description"
                    defaultValue={event?.description ?? ""}
                    className={textareaCls}
                    placeholder="Detaljni opis događaja — program, izvođači, satnica, posebnosti..."
                  />
                </Field>
              </div>
            </FormSection>

            {/* Termin — elevated z-index da bi date picker bio iznad Lokacije */}
            <FormSection
              title="Termin"
              elevated
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="4" width="18" height="18" rx="2" /><line x1="16" y1="2" x2="16" y2="6" /><line x1="8" y1="2" x2="8" y2="6" /><line x1="3" y1="10" x2="21" y2="10" />
                </svg>
              }
            >
              <div className="grid gap-4 sm:grid-cols-2">
                <AdminDateTimeField
                  name="startAt"
                  label="Datum početka"
                  defaultValue={formatDateTimeLocalInput(event?.startAt)}
                />
                <AdminDateTimeField
                  name="endAt"
                  label="Datum završetka"
                  defaultValue={formatDateTimeLocalInput(event?.endAt)}
                />
              </div>
            </FormSection>

            {/* Lokacija */}
            <FormSection
              title="Lokacija"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" /><circle cx="12" cy="10" r="3" />
                </svg>
              }
            >
              <div className="space-y-4">
                <div className="grid gap-4 sm:grid-cols-2">
                  <Field label="Prostor / lokacija">
                    <input name="venue" defaultValue={event?.venue ?? ""} className={inputCls} placeholder="npr. Dom omladine Beograd" />
                  </Field>
                  <Field label="Adresa">
                    <input name="address" defaultValue={event?.address ?? ""} className={inputCls} placeholder="npr. Makedonska 22" />
                  </Field>
                </div>

                <RegionPicker
                  cityValue={event?.cityId ?? ""}
                  municipalityValue={event?.municipalityId ?? ""}
                  neighborhoodValue={event?.neighborhoodId ?? ""}
                />

                <div className="grid gap-4 sm:grid-cols-2">
                  <Field label="Latitude" hint="Opciono — tačne GPS koordinate.">
                    <input name="lat" defaultValue={event?.lat ?? ""} className={inputCls} placeholder="44.8145" />
                  </Field>
                  <Field label="Longitude">
                    <input name="lng" defaultValue={event?.lng ?? ""} className={inputCls} placeholder="20.4661" />
                  </Field>
                </div>
              </div>
            </FormSection>

            {/* Cover */}
            <FormSection
              title="Cover slika"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="3" y="3" width="18" height="18" rx="2" /><circle cx="8.5" cy="8.5" r="1.5" /><polyline points="21 15 16 10 5 21" />
                </svg>
              }
            >
              <MediaFieldPicker
                name="coverMediaId"
                label=""
                directory={`events/${event?.id ?? "draft"}/cover`}
                initialId={event?.coverMediaId ?? undefined}
                initialUrl={event?.coverMedia?.url}
              />
            </FormSection>

            {/* Promo video */}
            <FormSection
              title="Promo video"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polygon points="23 7 16 12 23 17 23 7" /><rect x="1" y="5" width="15" height="14" rx="2" ry="2" />
                </svg>
              }
            >
              <VideoEmbedField
                urlName="videoUrl"
                titleName="videoTitle"
                defaultUrl={event?.videoUrl ?? ""}
                defaultTitle={event?.videoTitle ?? ""}
                hint="Posetioci će na javnoj strani događaja videti embed video ispod cover slike. Podržano: YouTube, Vimeo, MP4 link."
              />
            </FormSection>

            {/* Galerija — dostupna tek posle prvog snimanja, isti pattern
                kao na RealEstate / CarListing formama. */}
            {event?.id ? (
              <FormSection
                title="Galerija"
                icon={
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <rect x="3" y="3" width="18" height="18" rx="2" ry="2" /><circle cx="8.5" cy="8.5" r="1.5" /><polyline points="21 15 16 10 5 21" />
                  </svg>
                }
              >
                <EventGalleryManager
                  eventId={event.id}
                  title={event.title}
                  initialItems={
                    event.gallery?.map((item) => ({
                      id: item.id,
                      mediaId: item.mediaId,
                      sortOrder: item.sortOrder,
                      media: { url: item.media.url, alt: item.media.alt },
                    })) ?? []
                  }
                />
              </FormSection>
            ) : (
              <div className="flex items-center gap-3 rounded-2xl border border-dashed border-border bg-white/60 px-5 py-5">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="shrink-0 text-muted-foreground">
                  <rect x="3" y="3" width="18" height="18" rx="2" ry="2" /><circle cx="8.5" cy="8.5" r="1.5" /><polyline points="21 15 16 10 5 21" />
                </svg>
                <p className="text-sm text-muted-foreground">
                  Sačuvaj događaj prvi put da bi se aktivirala galerija fotografija.
                </p>
              </div>
            )}
          </div>

          {/* Right column — Objava */}
          <div className="space-y-5">
            <FormSection
              title="Objava"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" />
                </svg>
              }
            >
              <div className="space-y-4">
                <Field label="Status">
                  <select name="status" defaultValue={event?.status ?? "UPCOMING"} className={selectCls}>
                    {EVENT_STATUS_OPTIONS.map((s) => (
                      <option key={s.value} value={s.value}>{s.label}</option>
                    ))}
                  </select>
                </Field>

                {event?.status ? (
                  <div className={`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold ${statusColors[event.status]}`}>
                    <span className="h-1.5 w-1.5 rounded-full bg-current opacity-70" />
                    {EVENT_STATUS_OPTIONS.find((s) => s.value === event.status)?.label}
                  </div>
                ) : null}

                <div className="rounded-xl border border-border bg-muted/40 px-4 py-3 text-xs leading-5 text-muted-foreground">
                  Kada datum prođe, javni prikaz automatski prelazi u status{" "}
                  <span className="font-semibold text-foreground">Održan</span>.
                </div>

                {event?.company ? (
                  <div className="rounded-xl border border-border bg-muted/40 px-4 py-3">
                    <p className="text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Vezano za profil</p>
                    <p className="mt-1 text-sm font-semibold text-foreground">{event.company.name}</p>
                    <p className="text-xs text-muted-foreground">{event.company.type === "PLACE" ? "Mesto" : "Kompanija"}</p>
                  </div>
                ) : event?.ownerName ? (
                  <div className="rounded-xl border border-border bg-muted/40 px-4 py-3">
                    <p className="text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Privatni organizator</p>
                    <p className="mt-1 text-sm font-semibold text-foreground">{event.ownerName}</p>
                    <p className="text-xs text-muted-foreground">{event.ownerPhone || event.ownerEmail || "Kontakt nije dodat"}</p>
                  </div>
                ) : null}
              </div>
            </FormSection>

            {event?.createdAt ? (
              <div className="rounded-2xl border border-border bg-white p-4 shadow-sm">
                <p className="text-xs font-bold uppercase tracking-[0.12em] text-muted-foreground">Info</p>
                <div className="mt-3 space-y-2 text-xs text-muted-foreground">
                  <div className="flex justify-between gap-2">
                    <span>Kreiran</span>
                    <span className="font-medium text-foreground">
                      {new Date(event.createdAt).toLocaleDateString("sr-RS")}
                    </span>
                  </div>
                  <div className="flex justify-between gap-2">
                    <span>Ažuriran</span>
                    <span className="font-medium text-foreground">
                      {new Date(event.updatedAt).toLocaleDateString("sr-RS")}
                    </span>
                  </div>
                  {event.id ? (
                    <div className="flex justify-between gap-2">
                      <span>ID</span>
                      <span className="font-mono text-[0.68rem] text-muted-foreground">{event.id.slice(-8)}</span>
                    </div>
                  ) : null}
                </div>
              </div>
            ) : null}
          </div>
        </div>

        {/* Bottom save */}
        <div className="flex justify-end rounded-2xl border border-border bg-white px-5 py-4 shadow-sm">
          <SubmitButton className="primary-button h-10 px-6 text-sm">
            Sačuvaj događaj
          </SubmitButton>
        </div>
      </form>
    </div>
  );
}
