import type {
  CarListing,
  CarListingStatus,
  CarMedia,
  ListingType,
  Media,
} from "@prisma/client";

import {
  deleteCarListingAction,
  saveCarListingAction,
} from "@/app/(admin)/admin/automobili/actions";
import { AdminDeleteButton } from "@/components/admin/common/AdminDeleteButton";
import { AdminSaveNotice } from "@/components/admin/common/AdminSaveNotice";
import { UnsavedChangesWatcher } from "@/components/admin/common/UnsavedChangesWatcher";
import { CarTechnicalFields } from "@/components/admin/forms/CarTechnicalFields";
import { CarOwnerCompanyField } from "@/components/admin/forms/CarOwnerCompanyField";
import { VideoEmbedField } from "@/components/admin/forms/VideoEmbedField";
import { RegionPicker } from "@/components/common/RegionPicker";
import { CarGalleryManager } from "@/components/admin/media/CarGalleryManager";
import { getCarStatusLabel } from "@/lib/module-formatters";
import { SubmitButton } from "@/components/common/SubmitButton";

type CarDetails = CarListing & {
  company?: { id: string; name: string; slug: string; type: ListingType } | null;
  gallery?: Array<CarMedia & { media: Media }>;
};

const CAR_STATUS_OPTIONS: CarListingStatus[] = [
  "PENDING",
  "PUBLISHED",
  "SOLD",
  "EXPIRED",
  "REJECTED",
];

const statusColors: Record<CarListingStatus, string> = {
  PENDING: "bg-amber-100 text-amber-800 border-amber-200",
  PUBLISHED: "bg-emerald-100 text-emerald-800 border-emerald-200",
  SOLD: "bg-blue-100 text-blue-800 border-blue-200",
  EXPIRED: "bg-gray-100 text-gray-600 border-gray-200",
  REJECTED: "bg-red-100 text-red-700 border-red-200",
};

function FormSection({
  title,
  icon,
  children,
}: {
  title: string;
  icon: React.ReactNode;
  children: React.ReactNode;
}) {
  return (
    <section className="relative rounded-2xl border border-border bg-white shadow-sm">
      <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>
  );
}

function Field({
  label,
  hint,
  children,
}: {
  label: string;
  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";

export function CarListingForm({
  listing,
}: {
  listing?: CarDetails | null;
}) {
  const isEdit = Boolean(listing?.id);

  return (
    <div className="space-y-5">
      <form action={saveCarListingAction} className="space-y-5">
        <UnsavedChangesWatcher />
        <input type="hidden" name="id" value={listing?.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 vozila" : "Novo vozilo"}
            </p>
            <p className="mt-0.5 text-sm font-semibold text-foreground">
              {isEdit ? (listing?.title ?? "—") : "Popunite podatke o vozilu"}
            </p>
          </div>
          <div className="flex items-center gap-3">
            {listing?.id ? (
              <AdminDeleteButton
                action={deleteCarListingAction}
                title="Obrisati vozilo?"
                description="Oglas za vozilo biće uklonjen iz admina i javnog listinga."
                triggerLabel="Obriši"
                inputs={[{ name: "id", value: listing.id }]}
              />
            ) : null}
            <SubmitButton className="primary-button h-10 px-5 text-sm">
              Sačuvaj vozilo
            </SubmitButton>
          </div>
        </div>
        <AdminSaveNotice message="Vozilo je sačuvano." />

        <div className="grid gap-5 2xl:grid-cols-[minmax(0,1fr)_320px]">
          <div className="space-y-5">

            <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="Vlasnik vozila (kompanija)" hint="Opciono. Za fizičko lice ostavite prazno i unesite kontakt prodavca ispod.">
                  <CarOwnerCompanyField
                    initialCompany={listing?.company ? {
                      id: listing.company.id,
                      name: listing.company.name,
                      type: listing.company.type,
                    } : null}
                  />
                </Field>

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

                <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_200px]">
                  <Field label="Naslov oglasa">
                    <input required name="title" defaultValue={listing?.title ?? ""} className={inputCls} placeholder="npr. Volkswagen Golf 7 1.6 TDI" />
                  </Field>
                  <Field label="Slug">
                    <input name="slug" defaultValue={listing?.slug ?? ""} className={inputCls} placeholder="vw-golf-7-tdi" />
                  </Field>
                </div>

                <Field label="Opis">
                  <textarea name="description" defaultValue={listing?.description ?? ""} className={textareaCls} placeholder="Opis vozila i opreme, stanje, servisne knjižice..." />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Tehnički podaci"
              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="3" /><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
                </svg>
              }
            >
              <div className="space-y-5">
                <CarTechnicalFields
                  initial={{
                    make: listing?.make,
                    model: listing?.model,
                    variant: listing?.variant,
                    bodyType: listing?.bodyType,
                    condition: listing?.condition,
                    year: listing?.year,
                    mileageKm: listing?.mileageKm,
                    fuelType: listing?.fuelType,
                    transmission: listing?.transmission,
                    power: listing?.power,
                    powerKw: listing?.powerKw,
                    powerHp: listing?.powerHp,
                    engineDisplacementCc: listing?.engineDisplacementCc,
                    engineCode: listing?.engineCode,
                    cylinders: listing?.cylinders,
                    drivetrain: listing?.drivetrain,
                    doors: listing?.doors,
                    seats: listing?.seats,
                    color: listing?.color,
                    metallicColor: listing?.metallicColor,
                    emissionClass: listing?.emissionClass,
                    vin: listing?.vin,
                    registeredUntil: listing?.registeredUntil?.toISOString().slice(0, 10),
                    ownersCount: listing?.ownersCount,
                    serviceHistory: listing?.serviceHistory,
                    equipment: listing?.equipment,
                  }}
                />
                <div className="grid gap-4 sm:grid-cols-2">
                  <Field label="Cena">
                    <input name="price" type="number" min="0" defaultValue={listing?.price ?? ""} className={inputCls} placeholder="0" />
                  </Field>
                  <Field label="Valuta">
                    <select name="currency" defaultValue={listing?.currency ?? "EUR"} className={selectCls}>
                      <option value="EUR">EUR €</option>
                      <option value="RSD">RSD din</option>
                    </select>
                  </Field>
                </div>
              </div>
            </FormSection>

            <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">
                <Field label="Adresa">
                  <input name="address" defaultValue={listing?.address ?? ""} className={inputCls} placeholder="npr. Knez Mihailova 10" />
                </Field>
                <RegionPicker
                  cityValue={listing?.cityId ?? ""}
                  municipalityValue={listing?.municipalityId ?? ""}
                  neighborhoodValue={listing?.neighborhoodId ?? ""}
                />
                <div className="grid gap-4 sm:grid-cols-2">
                  <Field label="Latitude" hint="Opciono — tačne GPS koordinate.">
                    <input name="lat" defaultValue={listing?.lat ?? ""} className={inputCls} placeholder="44.8145" />
                  </Field>
                  <Field label="Longitude">
                    <input name="lng" defaultValue={listing?.lng ?? ""} className={inputCls} placeholder="20.4661" />
                  </Field>
                </div>
              </div>
            </FormSection>

            {/* Promo video — YouTube / Vimeo / upload MP4 direktno na R2 */}
            <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={listing?.videoUrl ?? ""}
                defaultTitle={listing?.videoTitle ?? ""}
                uploadDirectory={`automobili/${listing?.id ?? "draft"}/video`}
                hint="Posetioci će videti video na javnoj strani vozila. Podržano: YouTube, Vimeo, MP4 link, ili upload MP4/WebM/MOV fajla."
              />
            </FormSection>
          </div>

          <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" hint="Marka i model se čuvaju samo ako odgovaraju aktivnoj taksonomiji iz šifrarnika.">
                  <select name="status" defaultValue={listing?.status ?? "PENDING"} className={selectCls}>
                    {CAR_STATUS_OPTIONS.map((s) => (
                      <option key={s} value={s}>{getCarStatusLabel(s)}</option>
                    ))}
                  </select>
                </Field>

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

                <label className="flex cursor-pointer items-center gap-3 rounded-xl border border-border bg-muted/40 px-4 py-3 transition hover:border-primary/30 hover:bg-primary/5">
                  <input
                    type="checkbox"
                    name="isFeatured"
                    defaultChecked={listing?.isFeatured ?? false}
                    className="h-4 w-4 rounded border-border accent-primary"
                  />
                  <div>
                    <p className="text-sm font-semibold text-foreground">Istaknuto</p>
                    <p className="text-xs text-muted-foreground">Prikazuje se na vrhu listinga</p>
                  </div>
                </label>

                {listing?.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">{listing.company.name}</p>
                    <p className="text-xs text-muted-foreground">{listing.company.type === "PLACE" ? "Mesto" : "Kompanija"}</p>
                  </div>
                ) : listing?.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 prodavac</p>
                    <p className="mt-1 text-sm font-semibold text-foreground">{listing.ownerName}</p>
                    <p className="text-xs text-muted-foreground">{listing.ownerPhone || listing.ownerEmail || "Kontakt nije dodat"}</p>
                  </div>
                ) : null}
              </div>
            </FormSection>

            {listing?.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(listing.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(listing.updatedAt).toLocaleDateString("sr-RS")}</span>
                  </div>
                  {listing.id ? (
                    <div className="flex justify-between gap-2">
                      <span>ID</span>
                      <span className="font-mono text-[0.68rem] text-muted-foreground">{listing.id.slice(-8)}</span>
                    </div>
                  ) : null}
                </div>
              </div>
            ) : null}
          </div>
        </div>

        <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 vozilo
          </SubmitButton>
        </div>
      </form>

      {/* Galerija */}
      {listing?.id ? (
        <section className="overflow-hidden rounded-2xl border border-border bg-white shadow-sm">
          <div className="flex items-center gap-3 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">
              <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>
            </div>
            <h3 className="text-sm font-bold uppercase tracking-[0.12em] text-foreground">Galerija vozila</h3>
          </div>
          <div className="p-5">
            <CarGalleryManager
              carListingId={listing.id}
              title={listing.title}
              initialItems={
                listing.gallery?.map((item) => ({
                  id: item.id,
                  mediaId: item.mediaId,
                  sortOrder: item.sortOrder,
                  media: { url: item.media.url, alt: item.media.alt },
                })) ?? []
              }
            />
          </div>
        </section>
      ) : (
        <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čuvajte vozilo prvi put da biste aktivirali galeriju fotografija.
          </p>
        </div>
      )}
    </div>
  );
}
