import type { Deal, ListingType, PublishStatus } from "@prisma/client";

import { saveDealAction, deleteDealAction } from "@/app/(admin)/admin/akcije/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 { formatDateTimeLocalInput } from "@/lib/module-formatters";
import { SubmitButton } from "@/components/common/SubmitButton";

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

type DealDetails = Deal & {
  company?: { id: string; name: string; slug: string } | null;
};

const STATUS_OPTIONS: Array<{ value: PublishStatus; label: string }> = [
  { value: "DRAFT", label: "Nacrt" },
  { value: "PUBLISHED", label: "Objavljeno" },
  { value: "HIDDEN", label: "Skriveno" },
];

const statusColors: Record<PublishStatus, string> = {
  DRAFT: "bg-gray-100 text-gray-600 border-gray-200",
  PUBLISHED: "bg-emerald-100 text-emerald-800 border-emerald-200",
  HIDDEN: "bg-amber-100 text-amber-800 border-amber-200",
  EXPIRED: "bg-gray-100 text-gray-500 border-gray-200",
};

const CATEGORY_OPTIONS = [
  "Hrana i piće",
  "Lepota i zdravlje",
  "Moda i obuća",
  "Elektronika",
  "Usluge",
  "Turizam i hoteli",
  "Auto i moto",
  "Sport i rekreacija",
  "Nekretnine",
  "Obrazovanje",
  "Ostalo",
];

function FormSection({
  title,
  icon,
  children,
  elevated = false,
}: {
  title: string;
  icon: React.ReactNode;
  children: React.ReactNode;
  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>
  );
}

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 DealForm({
  deal,
  companies,
}: {
  deal?: DealDetails | null;
  companies: CompanyOption[];
}) {
  const isEdit = Boolean(deal?.id);

  return (
    <div className="space-y-5">
      <form action={saveDealAction} className="space-y-5">
        <UnsavedChangesWatcher />
        <input type="hidden" name="id" value={deal?.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 akcije" : "Nova akcija"}
            </p>
            <p className="mt-0.5 text-sm font-semibold text-foreground">
              {isEdit ? (deal?.title ?? "—") : "Popunite podatke o akciji"}
            </p>
          </div>
          <div className="flex items-center gap-3">
            {deal?.id ? (
              <AdminDeleteButton
                action={deleteDealAction}
                title="Obrisati akciju?"
                description="Akcija i popust će biti trajno uklonjeni. Ova akcija se ne može poništiti."
                triggerLabel="Obriši"
                inputs={[{ name: "id", value: deal.id }]}
              />
            ) : null}
            <SubmitButton className="primary-button h-10 px-5 text-sm">
              Sačuvaj akciju
            </SubmitButton>
          </div>
        </div>
        <AdminSaveNotice message="Akcija je sačuvana." />

        <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="Kompanija" hint="Akcije i popusti se vežu za firmu — biraj iz liste.">
                  <select required name="companyId" defaultValue={deal?.companyId ?? ""} className={selectCls}>
                    <option value="">Izaberi firmu</option>
                    {companies.map((c) => (
                      <option key={c.id} value={c.id}>
                        {c.name}{c.city?.nameSr ? ` · ${c.city.nameSr}` : ""}
                      </option>
                    ))}
                  </select>
                </Field>

                <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_200px]">
                  <Field label="Naziv akcije">
                    <input required name="title" defaultValue={deal?.title ?? ""} className={inputCls} placeholder="npr. Prolećna rasprodaja – do 40% popusta" />
                  </Field>
                  <Field label="Slug">
                    <input name="slug" defaultValue={deal?.slug ?? ""} className={inputCls} placeholder="prolecna-rasprodaja" />
                  </Field>
                </div>

                <Field label="Kategorija">
                  <select name="category" defaultValue={deal?.category ?? ""} className={selectCls}>
                    <option value="">Bez kategorije</option>
                    {CATEGORY_OPTIONS.map((cat) => <option key={cat} value={cat}>{cat}</option>)}
                  </select>
                </Field>

                <Field label="Opis">
                  <textarea name="description" defaultValue={deal?.description ?? ""} className={textareaCls} placeholder="Kratki opis akcije i uslova — vidljiv kupcima" />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Popust i cene"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <line x1="19" y1="5" x2="5" y2="19" /><circle cx="6.5" cy="6.5" r="2.5" /><circle cx="17.5" cy="17.5" r="2.5" />
                </svg>
              }
            >
              <div className="grid gap-4 sm:grid-cols-3">
                <Field label="Popust">
                  <input name="discount" defaultValue={deal?.discount ?? ""} className={inputCls} placeholder="npr. 30% ili -500 RSD" />
                </Field>
                <Field label="Redovna cena">
                  <input name="originalPrice" defaultValue={deal?.originalPrice ?? ""} className={inputCls} placeholder="npr. 5.990 RSD" />
                </Field>
                <Field label="Cena sa popustom">
                  <input name="dealPrice" defaultValue={deal?.dealPrice ?? ""} className={inputCls} placeholder="npr. 3.990 RSD" />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="CTA dugme"
              icon={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M12 5l7 7-7 7" />
                </svg>
              }
            >
              <div className="grid gap-4 sm:grid-cols-2">
                <Field label="Tekst dugmeta">
                  <input name="ctaLabel" defaultValue={deal?.ctaLabel ?? ""} className={inputCls} placeholder="npr. Kupi odmah" />
                </Field>
                <Field label="URL dugmeta">
                  <input name="ctaUrl" defaultValue={deal?.ctaUrl ?? ""} className={inputCls} placeholder="https://... ili /kompanije/slug" />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Period trajanja"
              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 label="Važi od" name="validFrom" defaultValue={deal?.validFrom ? formatDateTimeLocalInput(deal.validFrom) : ""} />
                <AdminDateTimeField label="Važi do" name="validUntil" defaultValue={deal?.validUntil ? formatDateTimeLocalInput(deal.validUntil) : ""} />
              </div>
              <p className="mt-2 text-xs text-muted-foreground/70">Ostavite prazno ako akcija nema rok isteka.</p>
            </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>
              }
            >
              <div className="space-y-3">
                <Field label="URL cover slike">
                  <input name="coverUrl" defaultValue={deal?.coverUrl ?? ""} className={inputCls} placeholder="https://... ili /uploads/..." />
                </Field>
                {deal?.coverUrl ? (
                  <div className="overflow-hidden rounded-xl border border-border">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img src={deal.coverUrl} alt="Cover preview" className="h-40 w-full object-cover" />
                  </div>
                ) : null}
              </div>
            </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={deal?.status ?? "DRAFT"} className={selectCls}>
                    {STATUS_OPTIONS.map((s) => (
                      <option key={s.value} value={s.value}>{s.label}</option>
                    ))}
                  </select>
                </Field>

                {deal?.status ? (
                  <div className={`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-xs font-semibold ${statusColors[deal.status]}`}>
                    <span className="h-1.5 w-1.5 rounded-full bg-current opacity-70" />
                    {STATUS_OPTIONS.find((s) => s.value === deal.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">
                  Akcija se prikazuje na javnoj listi i u traženju samo kada je status{" "}
                  <span className="font-semibold text-foreground">Objavljeno</span> i u periodu trajanja.
                </div>

                {deal?.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 firmu</p>
                    <p className="mt-1 text-sm font-semibold text-foreground">{deal.company.name}</p>
                  </div>
                ) : null}
              </div>
            </FormSection>

            {deal?.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>Kreirana</span>
                    <span className="font-medium text-foreground">{new Date(deal.createdAt).toLocaleDateString("sr-RS")}</span>
                  </div>
                  <div className="flex justify-between gap-2">
                    <span>Ažurirana</span>
                    <span className="font-medium text-foreground">{new Date(deal.updatedAt).toLocaleDateString("sr-RS")}</span>
                  </div>
                  {deal.id ? (
                    <div className="flex justify-between gap-2">
                      <span>ID</span>
                      <span className="font-mono text-[0.68rem] text-muted-foreground">{deal.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 akciju
          </SubmitButton>
        </div>
      </form>
    </div>
  );
}
