import {
  AdCreativeType,
  type AdCreative,
  type Media,
} from "@prisma/client";

import { deleteAdCreativeAction, saveAdCreativeAction } from "@/app/(admin)/admin/oglasi/kreativi/actions";
import { AdminDeleteButton } from "@/components/admin/common/AdminDeleteButton";
import { AdminSaveNotice } from "@/components/admin/common/AdminSaveNotice";
import { MediaFieldPicker } from "@/components/admin/media/MediaFieldPicker";
import { adSlotLabel } from "@/lib/constants/ad-slots";
import { SubmitButton } from "@/components/common/SubmitButton";

type CampaignOption = {
  id: string;
  name: string;
  slot: string | null;
  status: string;
};

type CreativeDetails = AdCreative & {
  campaign?: CampaignOption | null;
  media?: Media | null;
};

type IconProps = { className?: string };

function IconLayers({ className }: IconProps) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
      <path d="M12 3 3 8l9 5 9-5-9-5Z" />
      <path d="m3 13 9 5 9-5" />
      <path d="m3 18 9 5 9-5" />
    </svg>
  );
}

function IconContent({ className }: IconProps) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
      <rect x="3" y="4" width="18" height="14" rx="2" />
      <path d="m10 9 4 2.5L10 14V9Z" />
      <path d="M3 21h18" />
    </svg>
  );
}

function IconGoogle({ className }: IconProps) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
      <circle cx="12" cy="12" r="9" />
      <path d="M21 12h-9" />
      <path d="M12 3a9 9 0 0 0 0 18" />
    </svg>
  );
}

function _IconImage({ className }: IconProps) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
      <rect x="3" y="3" width="18" height="18" rx="2" />
      <circle cx="8.5" cy="8.5" r="1.5" />
      <path d="m21 15-5-5L5 21" />
    </svg>
  );
}

function IconInfo({ className }: IconProps) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
      <circle cx="12" cy="12" r="9" />
      <path d="M12 16v-4" />
      <path d="M12 8h.01" />
    </svg>
  );
}

function IconCheck({ className }: IconProps) {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
      <path d="m5 12 4.5 4.5L19 7" />
    </svg>
  );
}

const labelClass = "text-[0.7rem] font-bold uppercase tracking-[0.14em] text-[#6b7280]";
const inputClass =
  "h-11 w-full rounded-xl border border-[#ede8e3] bg-white px-4 text-[0.95rem] font-medium text-[#0c1828] outline-none transition placeholder:text-[#9ca3af] focus:border-[#c2410c] focus:ring-2 focus:ring-[#c2410c]/15";
const cardClass = "rounded-2xl border border-[#ede8e3] bg-white p-6 shadow-[0_1px_2px_rgba(12,24,40,0.04)]";

function CardHeader({
  icon,
  title,
  description,
  tone = "default",
}: {
  icon: React.ReactNode;
  title: string;
  description: string;
  tone?: "default" | "google";
}) {
  const isGoogle = tone === "google";
  return (
    <div className="mb-5 flex items-start gap-3 border-b border-[#ede8e3] pb-4">
      <span
        className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ${
          isGoogle
            ? "bg-[#c2410c]/10 text-[#c2410c]"
            : "bg-[#faf9f7] text-[#0c1828]"
        }`}
      >
        {icon}
      </span>
      <div className="min-w-0">
        <div className="flex items-center gap-2">
          <h3 className="text-[1.05rem] font-bold leading-tight text-[#0c1828]">{title}</h3>
          {isGoogle ? (
            <span className="rounded-full bg-[#c2410c]/10 px-2 py-0.5 text-[0.62rem] font-bold uppercase tracking-[0.12em] text-[#c2410c]">
              Google
            </span>
          ) : null}
        </div>
        <p className="mt-0.5 text-[0.82rem] text-[#6b7280]">{description}</p>
      </div>
    </div>
  );
}

export function AdCreativeForm({
  creative,
  campaigns,
}: {
  creative?: CreativeDetails | null;
  campaigns: CampaignOption[];
}) {
  return (
    <form action={saveAdCreativeAction} className="surface admin-form-shell rounded-[2rem] p-5 xl:p-7">
      <input type="hidden" name="id" value={creative?.id ?? ""} />

      <div className="sticky top-2 z-10 mb-7 flex flex-wrap items-center justify-between gap-4 rounded-2xl border border-[#ede8e3] bg-white/85 px-5 py-4 shadow-[0_1px_2px_rgba(12,24,40,0.04)] backdrop-blur">
        <div>
          <h2 className="text-[1.4rem] font-bold leading-tight tracking-[-0.01em] text-[#0c1828]">
            Kreativa
          </h2>
          <p className="mt-0.5 text-[0.85rem] text-[#6b7280]">
            Definiši sadržaj reklame i način prikaza u reklamnom prostoru.
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          {creative?.id ? (
            <AdminDeleteButton
              action={deleteAdCreativeAction}
              title="Obrisati kreativu?"
              description="Kreativa će biti uklonjena iz kampanje i više neće biti dostupna za prikaz."
              triggerLabel="Obriši kreativu"
              inputs={[{ name: "id", value: creative.id }]}
            />
          ) : null}
          <SubmitButton
            className="inline-flex h-11 items-center justify-center rounded-full bg-gradient-to-r from-[#c2410c] to-[#ff7a45] px-6 text-[0.92rem] font-bold text-white shadow-[0_6px_18px_rgba(194,65,12,0.28)] transition hover:brightness-105 active:brightness-95"
          >
            Sačuvaj kreativu
          </SubmitButton>
        </div>
      </div>
      <AdminSaveNotice message="Kreativa je sačuvana." />

      <div className="grid gap-6 2xl:grid-cols-[minmax(0,1fr)_minmax(420px,560px)]">
        <div className="min-w-0 space-y-6">
          <section className={cardClass}>
            <CardHeader
              icon={<IconLayers className="h-[18px] w-[18px] stroke-[1.8]" />}
              title="Osnovno"
              description="Kampanja kojoj kreativa pripada, tip i naslov."
            />
            <div className="grid gap-5">
              <label className="grid gap-2">
                <span className={labelClass}>Kampanja</span>
                <select
                  required
                  name="campaignId"
                  defaultValue={creative?.campaignId ?? ""}
                  className={`${inputClass} appearance-none bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%236b7280%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22m6%209%206%206%206-6%22%2F%3E%3C%2Fsvg%3E')] bg-[length:18px] bg-[right_0.9rem_center] bg-no-repeat pr-11`}
                >
                  <option value="">Izaberi kampanju</option>
                  {campaigns.map((campaign) => (
                    <option key={campaign.id} value={campaign.id}>
                      {campaign.name} · {adSlotLabel(campaign.slot)} ·{" "}
                      {campaign.status}
                    </option>
                  ))}
                </select>
              </label>
              <div className="grid gap-5 md:grid-cols-2">
                <label className="grid gap-2">
                  <span className={labelClass}>Tip kreative</span>
                  <select
                    name="type"
                    defaultValue={creative?.type ?? AdCreativeType.IMAGE}
                    className={`${inputClass} appearance-none bg-[url('data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%236b7280%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22m6%209%206%206%206-6%22%2F%3E%3C%2Fsvg%3E')] bg-[length:18px] bg-[right_0.9rem_center] bg-no-repeat pr-11`}
                  >
                    {Object.values(AdCreativeType).map((type) => (
                      <option key={type} value={type}>
                        {type === "IMAGE"
                          ? "Slika (upload)"
                          : type === "VIDEO"
                            ? "Video (URL)"
                            : type === "HTML"
                              ? "HTML blok (custom)"
                              : "Google AdSense"}
                      </option>
                    ))}
                  </select>
                  <span className="text-[0.78rem] leading-relaxed text-[#6b7280]">
                    Tip određuje koju sekciju ispod popunjavaš:{" "}
                    <strong className="font-semibold text-[#0c1828]">Slika</strong> → upload ·{" "}
                    <strong className="font-semibold text-[#0c1828]">Video</strong> → Video URL ·{" "}
                    <strong className="font-semibold text-[#0c1828]">HTML</strong> → Custom HTML ·{" "}
                    <strong className="font-semibold text-[#0c1828]">Google AdSense</strong> → sekcija &quot;Google AdSense&quot;. Ostale sekcije ostavi prazne.
                  </span>
                </label>
                <label className="grid gap-2">
                  <span className={labelClass}>Naslov kreative</span>
                  <input
                    name="title"
                    defaultValue={creative?.title ?? ""}
                    className={inputClass}
                    placeholder="Naslov kreative"
                  />
                  <span className="text-[0.78rem] text-[#6b7280]">
                    Interni naziv radi lakšeg snalaženja u kampanji.
                  </span>
                </label>
              </div>
            </div>
          </section>

          <section className={cardClass}>
            <CardHeader
              icon={<IconContent className="h-[18px] w-[18px] stroke-[1.8]" />}
              title="Sadržaj"
              description="Video izvor i custom HTML blok kreative."
            />
            <div className="grid gap-5">
              <label className="grid gap-2">
                <span className={labelClass}>Video URL</span>
                <input
                  name="videoUrl"
                  defaultValue={creative?.videoUrl ?? ""}
                  className={inputClass}
                  placeholder="https://..."
                />
                <span className="text-[0.78rem] text-[#6b7280]">
                  Koristi se samo za <strong className="font-semibold text-[#0c1828]">VIDEO</strong> tip kreative.
                </span>
              </label>
              <label className="grid gap-2">
                <span className={labelClass}>Custom HTML</span>
                <textarea
                  name="html"
                  defaultValue={creative?.html ?? ""}
                  className={`${inputClass} h-auto min-h-48 resize-y py-3 font-mono text-[0.85rem] leading-relaxed`}
                  placeholder="<div>Custom HTML kreativa</div>"
                />
                <span className="text-[0.78rem] text-[#6b7280]">
                  Prikazuje se za <strong className="font-semibold text-[#0c1828]">HTML</strong> tip kreative.
                </span>
              </label>
            </div>
          </section>

          <section className={`${cardClass} ring-1 ring-[#c2410c]/10`}>
            <CardHeader
              tone="google"
              icon={<IconGoogle className="h-[18px] w-[18px] stroke-[1.8]" />}
              title="Google AdSense"
              description="Popunjava se SAMO ako je Tip kreative = Google AdSense. client = ca-pub-… iz AdSense naloga, slot = ID jedinice oglasa."
            />
            <div className="grid gap-5">
              <div className="grid gap-5 md:grid-cols-2">
                <label className="grid gap-2">
                  <span className={labelClass}>AdSense client</span>
                  <input
                    name="adsenseClient"
                    defaultValue={(creative as (CreativeDetails & { adsenseClient?: string | null }) | null | undefined)?.adsenseClient ?? ""}
                    className={inputClass}
                    placeholder="ca-pub-xxxxxxxxxxxxxxxx"
                  />
                </label>
                <label className="grid gap-2">
                  <span className={labelClass}>AdSense slot</span>
                  <input
                    name="adsenseSlot"
                    defaultValue={(creative as (CreativeDetails & { adsenseSlot?: string | null }) | null | undefined)?.adsenseSlot ?? ""}
                    className={inputClass}
                    placeholder="1234567890"
                  />
                </label>
              </div>
              <div className="grid gap-5 md:grid-cols-[minmax(0,1fr)_minmax(220px,auto)]">
                <label className="grid gap-2">
                  <span className={labelClass}>AdSense format</span>
                  <input
                    name="adsenseFormat"
                    defaultValue={(creative as (CreativeDetails & { adsenseFormat?: string | null }) | null | undefined)?.adsenseFormat ?? "auto"}
                    className={inputClass}
                    placeholder="auto"
                  />
                </label>
                <div className="grid gap-2">
                  <span className={labelClass}>Responsive širina</span>
                  <label className="group flex h-11 cursor-pointer items-center gap-3 rounded-xl border border-[#ede8e3] bg-[#faf9f7] px-4 text-[0.9rem] font-medium text-[#0c1828] transition has-[:checked]:border-[#c2410c]/40 has-[:checked]:bg-[#c2410c]/5">
                    <input
                      type="checkbox"
                      name="adsenseFullWidthResponsive"
                      defaultChecked={
                        (
                          creative as
                            | (CreativeDetails & { adsenseFullWidthResponsive?: boolean | null })
                            | null
                            | undefined
                        )?.adsenseFullWidthResponsive ?? true
                      }
                      className="peer sr-only"
                    />
                    <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border border-[#d6cfc6] bg-white text-white transition peer-checked:border-[#c2410c] peer-checked:bg-[#c2410c]">
                      <IconCheck className="h-3.5 w-3.5 opacity-0 transition peer-checked:opacity-100" />
                    </span>
                    Full width responsive
                  </label>
                </div>
              </div>
            </div>
          </section>
        </div>

        <div className="min-w-0 space-y-6">
          <MediaFieldPicker
            name="mediaId"
            label="Slika kreative"
            directory={`ads/creatives/${creative?.id ?? "draft"}`}
            initialId={creative?.mediaId}
            initialUrl={creative?.media?.url}
          />

          <section className={cardClass}>
            <CardHeader
              icon={<IconInfo className="h-[18px] w-[18px] stroke-[1.8]" />}
              title="Napomena"
              description="Kratke smernice za rad sa kreativama."
            />
            <ul className="grid gap-3">
              {[
                "IMAGE koristi uploadovanu sliku, VIDEO koristi video URL, HTML prikazuje custom blok unutar bannera, a ADSENSE prikazuje Google AdSense jedinicu preko client + slot parametara.",
                "Jedna kampanja može imati više kreativa, a javni slot trenutno prikazuje prvu aktivnu kreativu po prioritetu.",
                "Za ADSENSE tip nije potrebna slika kreative — dovoljno je da uneseš ca-pub-… client i broj slota, a Biznis Portal će sam prikazati Google oglas u tom prostoru.",
              ].map((text) => (
                <li
                  key={text}
                  className="flex gap-3 rounded-xl border border-[#ede8e3] bg-[#faf9f7] px-4 py-3.5 text-[0.85rem] leading-relaxed text-[#6b7280]"
                >
                  <span className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-[#c2410c]/10 text-[#c2410c]">
                    <IconCheck className="h-3 w-3" />
                  </span>
                  <span>{text}</span>
                </li>
              ))}
            </ul>
          </section>
        </div>
      </div>

      <div className="mt-8 flex flex-wrap items-center justify-end gap-3 border-t border-[#ede8e3] pt-6">
        <SubmitButton
          className="inline-flex h-11 items-center justify-center rounded-full border border-[#ede8e3] bg-white px-6 text-[0.92rem] font-bold text-[#0c1828] transition hover:border-[#c2410c]/40 hover:text-[#c2410c]"
        >
          Sačuvaj kreativu
        </SubmitButton>
      </div>
    </form>
  );
}
