import type { ListingType, Media, ProductStatus, StoreProduct } from "@prisma/client";

import { deleteStoreProductAction, saveStoreProductAction } from "@/app/(admin)/admin/prodavnica/actions";
import { AdminDeleteButton } from "@/components/admin/common/AdminDeleteButton";
import { AdminSaveNotice } from "@/components/admin/common/AdminSaveNotice";
import { UnsavedChangesWatcher } from "@/components/admin/common/UnsavedChangesWatcher";
import { VideoEmbedField } from "@/components/admin/forms/VideoEmbedField";
import { MediaFieldPicker } from "@/components/admin/media/MediaFieldPicker";
import { SubmitButton } from "@/components/common/SubmitButton";

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

type StoreProductDetails = StoreProduct & {
  company?: { id: string; name: string; slug: string; type: ListingType } | null;
  coverMedia?: Media | null;
};

const STATUS_OPTIONS: Array<{ value: ProductStatus; label: string }> = [
  { value: "DRAFT", label: "Nacrt" },
  { value: "PUBLISHED", label: "Objavljeno" },
  { value: "OUT_OF_STOCK", label: "Nema na stanju" },
  { value: "SOLD_OUT", label: "Rasprodato" },
  { value: "ARCHIVED", label: "Arhivirano" },
];

const statusColors: Record<ProductStatus, string> = {
  DRAFT: "bg-gray-100 text-gray-600 border-gray-200",
  PUBLISHED: "bg-emerald-100 text-emerald-800 border-emerald-200",
  OUT_OF_STOCK: "bg-amber-100 text-amber-800 border-amber-200",
  SOLD_OUT: "bg-blue-100 text-blue-800 border-blue-200",
  ARCHIVED: "bg-gray-100 text-gray-500 border-gray-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 StoreProductForm({
  item,
  companies,
}: {
  item?: StoreProductDetails | null;
  companies: CompanyOption[];
}) {
  const isEdit = Boolean(item?.id);

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

        <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 proizvoda" : "Novi proizvod"}
            </p>
            <p className="mt-0.5 text-sm font-semibold text-foreground">
              {isEdit ? (item?.title ?? "—") : "Popunite podatke o proizvodu"}
            </p>
          </div>
          <div className="flex items-center gap-3">
            {item?.id ? (
              <AdminDeleteButton
                action={deleteStoreProductAction}
                title="Obrisati proizvod?"
                description="Proizvod ili usluga biće uklonjeni iz admina i javnog prikaza prodavnice."
                triggerLabel="Obriši"
                inputs={[{ name: "id", value: item.id }]}
              />
            ) : null}
            <SubmitButton className="primary-button h-10 px-5 text-sm">
              Sačuvaj proizvod
            </SubmitButton>
          </div>
        </div>
        <AdminSaveNotice message="Proizvod je sačuvan." />

        <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="Prodavac (kompanija)" hint="Opciono. Ako proizvod prodaje fizičko lice, ostavite prazno i unesite kontakt ispod.">
                  <select name="companyId" defaultValue={item?.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 prodavca" hint="Obavezno samo ako proizvod nije vezan za profil.">
                    <input name="ownerName" defaultValue={item?.ownerName ?? ""} className={inputCls} placeholder="npr. Marko Marković" />
                  </Field>
                  <Field label="Telefon">
                    <input name="ownerPhone" defaultValue={item?.ownerPhone ?? ""} className={inputCls} placeholder="+381..." />
                  </Field>
                  <Field label="E-mail">
                    <input type="email" name="ownerEmail" defaultValue={item?.ownerEmail ?? ""} className={inputCls} placeholder="ime@email.com" />
                  </Field>
                </div>

                <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_200px]">
                  <Field label="Naziv proizvoda">
                    <input required name="title" defaultValue={item?.title ?? ""} className={inputCls} placeholder="npr. Hrastov plakar 200×60" />
                  </Field>
                  <Field label="Slug">
                    <input name="slug" defaultValue={item?.slug ?? ""} className={inputCls} placeholder="hrastov-plakar" />
                  </Field>
                </div>

                <Field label="Kategorija">
                  <input name="categoryName" defaultValue={item?.categoryName ?? ""} className={inputCls} placeholder="npr. Nameštaj · Plakari" />
                </Field>

                <Field label="Kratak opis" hint="Sažetak proizvoda (max 200 karaktera).">
                  <input name="shortDescription" defaultValue={item?.shortDescription ?? ""} className={inputCls} placeholder="Kratak opis proizvoda" />
                </Field>

                <Field label="Detaljni opis">
                  <textarea name="description" defaultValue={item?.description ?? ""} className={textareaCls} placeholder="Detaljni opis proizvoda, materijal, dimenzije, isporuka..." />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Cena i zalihe"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="12" y1="1" x2="12" y2="23" /><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
                </svg>
              }
            >
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                <Field label="Cena">
                  <input name="price" defaultValue={item?.price ?? ""} className={inputCls} placeholder="0" />
                </Field>
                <Field label="Stara cena" hint="Za prikaz popusta.">
                  <input name="compareAtPrice" defaultValue={item?.compareAtPrice ?? ""} className={inputCls} placeholder="0" />
                </Field>
                <Field label="Valuta">
                  <select name="currency" defaultValue={item?.currency ?? "RSD"} className={selectCls}>
                    <option value="RSD">RSD din</option>
                    <option value="EUR">EUR €</option>
                  </select>
                </Field>
                <Field label="Količina">
                  <input name="stockQuantity" defaultValue={item?.stockQuantity ?? ""} className={inputCls} placeholder="0" />
                </Field>
                <Field label="SKU" hint="Šifra proizvoda.">
                  <input name="sku" defaultValue={item?.sku ?? ""} className={inputCls} placeholder="npr. PLK-200-60-H" />
                </Field>
              </div>
            </FormSection>

            <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={`store/${item?.id ?? "draft"}/cover`}
                initialId={item?.coverMediaId ?? undefined}
                initialUrl={item?.coverMedia?.url}
              />
            </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={item?.videoUrl ?? ""}
                defaultTitle={item?.videoTitle ?? ""}
                uploadDirectory={`prodavnica/${item?.id ?? "draft"}/video`}
                hint="Posetioci će videti video na stranici proizvoda. 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">
                  <select name="status" defaultValue={item?.status ?? "DRAFT"} className={selectCls}>
                    {STATUS_OPTIONS.map((s) => (
                      <option key={s.value} value={s.value}>{s.label}</option>
                    ))}
                  </select>
                </Field>

                {item?.status ? (
                  <div className={`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold ${statusColors[item.status]}`}>
                    <span className="h-1.5 w-1.5 rounded-full bg-current opacity-70" />
                    {STATUS_OPTIONS.find((s) => s.value === item.status)?.label}
                  </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={item?.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 prodavnice</p>
                  </div>
                </label>

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

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