import type { JobListing, JobListingStatus, Media } from "@prisma/client";

import { deleteJobAction, saveJobAction } from "@/app/(admin)/admin/poslovi/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 { AdminEntityCompanyField } from "@/components/admin/forms/AdminEntityCompanyField";
import { RegionPicker } from "@/components/common/RegionPicker";
import { MediaFieldPicker } from "@/components/admin/media/MediaFieldPicker";
import { AiCopyAssist } from "@/components/portal/forms/AiCopyAssist";
import { formatDateTimeLocalInput } from "@/lib/module-formatters";
import { SubmitButton } from "@/components/common/SubmitButton";
import {
  EDUCATION_LEVEL_OPTIONS,
  EMPLOYMENT_TYPE_OPTIONS,
  JOB_BENEFIT_OPTIONS,
  JOB_CATEGORY_OPTIONS,
  SALARY_PERIOD_OPTIONS,
  SENIORITY_OPTIONS,
  WORKPLACE_TYPE_OPTIONS,
} from "@/lib/constants/job-options";

type JobDetails = JobListing & {
  company?: { id: string; name: string; slug: string; type: string } | null;
  coverMedia?: Media | null;
};

const STATUS_OPTIONS: Array<{ value: JobListingStatus; label: string }> = [
  { value: "DRAFT", label: "Nacrt" },
  { value: "PUBLISHED", label: "Objavljeno" },
  { value: "PAUSED", label: "Pauzirano" },
  { value: "FILLED", label: "Popunjeno" },
  { value: "EXPIRED", label: "Isteklo" },
];

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

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: 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";

export function JobForm({
  job,
}: {
  job?: JobDetails | null;
}) {
  const isEdit = Boolean(job?.id);

  return (
    <div className="space-y-5">
      <form action={saveJobAction} className="space-y-5">
        <UnsavedChangesWatcher />
        <input type="hidden" name="id" value={job?.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 oglasa za posao" : "Novi oglas za posao"}
            </p>
            <p className="mt-0.5 text-sm font-semibold text-foreground">
              {isEdit ? (job?.title ?? "—") : "Popunite podatke o poziciji"}
            </p>
          </div>
          <div className="flex items-center gap-3">
            {job?.id ? (
              <AdminDeleteButton
                action={deleteJobAction}
                title="Obrisati oglas?"
                description="Oglas za posao biće uklonjen iz admina i javnog listinga."
                triggerLabel="Obriši"
                inputs={[{ name: "id", value: job.id }]}
              />
            ) : null}
            <SubmitButton className="primary-button h-10 px-5 text-sm">
              Sačuvaj posao
            </SubmitButton>
          </div>
        </div>
        <AdminSaveNotice message="Oglas 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="Poslodavac (kompanija)">
                  <AdminEntityCompanyField
                    initialCompany={job?.company ?? null}
                    required
                    searchLabel="Pretražite poslodavca"
                    placeholder="Ukucajte naziv poslodavca…"
                    emptyHint="Oglase za posao objavljuju registrovane kompanije. Pretražite naziv i izaberite poslodavca."
                  />
                </Field>

                <div className="grid gap-4 sm:grid-cols-[minmax(0,1fr)_200px]">
                  <Field label="Naslov pozicije">
                    <input required name="title" defaultValue={job?.title ?? ""} className={inputCls} placeholder="npr. Senior Frontend Developer" />
                  </Field>
                  <Field label="Slug">
                    <input name="slug" defaultValue={job?.slug ?? ""} className={inputCls} placeholder="senior-frontend-developer" />
                  </Field>
                </div>

                <Field label="Kratak sažetak" hint="Vidi se u listingu i pretrazi (do 200 karaktera).">
                  <textarea name="excerpt" defaultValue={job?.excerpt ?? ""} className="min-h-20 w-full resize-y rounded-xl border border-border bg-white px-3.5 py-2.5 text-sm text-foreground placeholder:text-muted-foreground/50 focus:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/10 transition" placeholder="Sažetak oglasa za listing i pretragu" />
                </Field>

                <Field
                  label={
                    <span className="flex w-full items-center justify-between gap-2">
                      <span>Opis posla</span>
                      <AiCopyAssist targetSelector="textarea[name='description']" category="job" />
                    </span>
                  }
                >
                  <textarea name="description" defaultValue={job?.description ?? ""} className={textareaCls} placeholder="Opis posla, odgovornosti, benefiti, profil kandidata..." />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Pozicija i način rada"
              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-3">
                <Field label="Kategorija">
                  <select name="category" defaultValue={job?.category ?? ""} className={selectCls}>
                    <option value="">— Izaberi kategoriju —</option>
                    {JOB_CATEGORY_OPTIONS.map((value) => <option key={value} value={value}>{value}</option>)}
                  </select>
                </Field>
                <Field label="Odeljenje">
                  <input name="department" defaultValue={job?.department ?? ""} className={inputCls} placeholder="npr. Razvoj proizvoda" />
                </Field>
                <Field label="Tip angažmana">
                  <select name="employmentType" defaultValue={job?.employmentType ?? ""} className={selectCls}>
                    <option value="">— Izaberi angažman —</option>
                    {EMPLOYMENT_TYPE_OPTIONS.map((value) => <option key={value} value={value}>{value}</option>)}
                  </select>
                </Field>
                <Field label="Senioritet">
                  <select name="seniority" defaultValue={job?.seniority ?? ""} className={selectCls}>
                    <option value="">— Izaberi senioritet —</option>
                    {SENIORITY_OPTIONS.map((value) => <option key={value} value={value}>{value}</option>)}
                  </select>
                </Field>
                <Field label="Način rada">
                  <select name="workplaceType" defaultValue={job?.workplaceType ?? (job?.isRemote ? "Rad na daljinu" : "")} className={selectCls}>
                    <option value="">— Izaberi način rada —</option>
                    {WORKPLACE_TYPE_OPTIONS.map((value) => <option key={value} value={value}>{value}</option>)}
                  </select>
                </Field>
                <Field label="Radno vreme">
                  <input name="workSchedule" defaultValue={job?.workSchedule ?? ""} className={inputCls} placeholder="npr. Pon–pet, 09–17h" />
                </Field>
                <Field label="Minimalno iskustvo (god.)">
                  <input type="number" min="0" name="experienceYearsMin" defaultValue={job?.experienceYearsMin ?? ""} className={inputCls} placeholder="0" />
                </Field>
                <Field label="Maksimalno iskustvo (god.)">
                  <input type="number" min="0" name="experienceYearsMax" defaultValue={job?.experienceYearsMax ?? ""} className={inputCls} placeholder="Bez ograničenja" />
                </Field>
                <Field label="Nivo obrazovanja">
                  <select name="educationLevel" defaultValue={job?.educationLevel ?? ""} className={selectCls}>
                    <option value="">— Izaberi obrazovanje —</option>
                    {EDUCATION_LEVEL_OPTIONS.map((value) => <option key={value} value={value}>{value}</option>)}
                  </select>
                </Field>
                <Field label="Broj otvorenih mesta">
                  <input type="number" min="1" name="positionsCount" defaultValue={job?.positionsCount ?? ""} className={inputCls} placeholder="1" />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Plata"
              icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><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="Plata od">
                  <input name="salaryFrom" defaultValue={job?.salaryFrom ?? ""} className={inputCls} placeholder="1500" />
                </Field>
                <Field label="Plata do">
                  <input name="salaryTo" defaultValue={job?.salaryTo ?? ""} className={inputCls} placeholder="2500" />
                </Field>
                <Field label="Valuta">
                  <select name="currency" defaultValue={job?.currency ?? "EUR"} className={selectCls}>
                    <option value="EUR">EUR €</option>
                    <option value="RSD">RSD din</option>
                  </select>
                </Field>
                <Field label="Period plate">
                  <select name="salaryPeriod" defaultValue={job?.salaryPeriod ?? "Mesečno"} className={selectCls}>
                    {SALARY_PERIOD_OPTIONS.map((value) => <option key={value} value={value}>{value}</option>)}
                  </select>
                </Field>
              </div>
              <div className="mt-4 grid gap-3 sm:grid-cols-2">
                <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="salaryVisible" defaultChecked={job?.salaryVisible ?? true} className="h-4 w-4 rounded border-border accent-primary" />
                  <div>
                    <p className="text-sm font-semibold text-foreground">Javno prikaži platu</p>
                    <p className="text-xs text-muted-foreground">Transparentna plata povećava kvalitet prijava</p>
                  </div>
                </label>
                <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="salaryIsGross" defaultChecked={job?.salaryIsGross ?? false} className="h-4 w-4 rounded border-border accent-primary" />
                  <div>
                    <p className="text-sm font-semibold text-foreground">Bruto iznos</p>
                    <p className="text-xs text-muted-foreground">Označite ako navedeni iznos nije neto</p>
                  </div>
                </label>
              </div>
            </FormSection>

            <FormSection
              title="Profil idealnog kandidata"
              icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="7" r="4"/><path d="M5.5 21a6.5 6.5 0 0 1 13 0"/></svg>}
            >
              <div className="grid gap-4 lg:grid-cols-3">
                <Field label="Odgovornosti">
                  <textarea name="responsibilities" defaultValue={job?.responsibilities ?? ""} className={textareaCls} placeholder="Svaku odgovornost unesite u novom redu…" />
                </Field>
                <Field label="Obavezni uslovi">
                  <textarea name="requirements" defaultValue={job?.requirements ?? ""} className={textareaCls} placeholder="Znanja, iskustvo i formalni uslovi…" />
                </Field>
                <Field label="Poželjno">
                  <textarea name="niceToHave" defaultValue={job?.niceToHave ?? ""} className={textareaCls} placeholder="Dodatne prednosti kandidata…" />
                </Field>
              </div>
              <div className="mt-4 grid gap-4 sm:grid-cols-2">
                <Field label="Veštine" hint="Odvojite zarezom ili novim redom.">
                  <textarea name="skills" defaultValue={job?.skills.join(", ") ?? ""} className="adminx-textarea min-h-24" placeholder="React, prodaja, Excel…" />
                </Field>
                <Field label="Jezici" hint="Odvojite zarezom ili novim redom.">
                  <textarea name="languages" defaultValue={job?.languages.join(", ") ?? ""} className="adminx-textarea min-h-24" placeholder="Srpski C2, engleski B2…" />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Benefiti"
              icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="8" width="18" height="13" rx="2"/><path d="M12 8v13M3 12h18M7.5 8C4 8 4 3 7 3c2.5 0 5 5 5 5M16.5 8C20 8 20 3 17 3c-2.5 0-5 5-5 5"/></svg>}
            >
              <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
                {JOB_BENEFIT_OPTIONS.map((benefit) => (
                  <label key={benefit} className="flex cursor-pointer items-center gap-3 rounded-xl border border-border bg-muted/30 px-3.5 py-3 text-sm font-medium text-foreground transition hover:border-primary/30 hover:bg-primary/5">
                    <input type="checkbox" name="benefits" value={benefit} defaultChecked={job?.benefits.includes(benefit)} className="h-4 w-4 rounded border-border accent-primary" />
                    {benefit}
                  </label>
                ))}
              </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 radnog mesta">
                  <input name="address" defaultValue={job?.address ?? ""} className={inputCls} placeholder="npr. Bulevar Mihajla Pupina 10" />
                </Field>
                <RegionPicker
                  cityValue={job?.cityId ?? ""}
                  municipalityValue={job?.municipalityId ?? ""}
                  neighborhoodValue={job?.neighborhoodId ?? ""}
                />
              </div>
            </FormSection>

            <FormSection
              title="Prijava kandidata"
              icon={<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 2L11 13"/><path d="M22 2l-7 20-4-9-9-4z"/></svg>}
            >
              <div className="grid gap-4 sm:grid-cols-2">
                <Field label="Link za prijavu" hint="Sistem za prijave, strana za karijere ili formular poslodavca.">
                  <input type="url" name="applicationUrl" defaultValue={job?.applicationUrl ?? ""} className={inputCls} placeholder="https://…" />
                </Field>
                <Field label="E-mail za prijavu">
                  <input type="email" name="applicationEmail" defaultValue={job?.applicationEmail ?? ""} className={inputCls} placeholder="posao@kompanija.rs" />
                </Field>
              </div>
            </FormSection>

            <FormSection
              title="Termini objave"
              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-3">
                <AdminDateTimeField name="publishedAt" label="Datum objave" defaultValue={formatDateTimeLocalInput(job?.publishedAt)} />
                <AdminDateTimeField name="expiresAt" label="Ističe" defaultValue={formatDateTimeLocalInput(job?.expiresAt)} />
                <AdminDateTimeField name="applicationDeadline" label="Rok za prijavu" defaultValue={formatDateTimeLocalInput(job?.applicationDeadline)} />
              </div>
            </FormSection>

            <FormSection
              title="Naslovna fotografija"
              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={`jobs/${job?.id ?? "draft"}/cover`}
                initialId={job?.coverMediaId ?? undefined}
                initialUrl={job?.coverMedia?.url}
              />
            </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={job?.status ?? "DRAFT"} className={selectCls}>
                    {STATUS_OPTIONS.map((s) => (
                      <option key={s.value} value={s.value}>{s.label}</option>
                    ))}
                  </select>
                </Field>

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

                <label className="flex cursor-pointer items-center gap-3 rounded-xl border border-primary/20 bg-primary/5 px-4 py-3 transition hover:border-primary/40">
                  <input type="checkbox" name="isFeatured" defaultChecked={job?.isFeatured ?? false} className="h-4 w-4 rounded border-border accent-primary" />
                  <div>
                    <p className="text-sm font-semibold text-foreground">Istaknuti oglas</p>
                    <p className="text-xs text-muted-foreground">Prioritetna pozicija u rezultatima</p>
                  </div>
                </label>

                <label className="flex cursor-pointer items-center gap-3 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 transition hover:border-rose-300">
                  <input type="checkbox" name="isUrgent" defaultChecked={job?.isUrgent ?? false} className="h-4 w-4 rounded border-rose-300 accent-rose-600" />
                  <div>
                    <p className="text-sm font-semibold text-rose-950">Hitno zapošljavanje</p>
                    <p className="text-xs text-rose-700">Jasna oznaka kandidatu</p>
                  </div>
                </label>

                <div className="rounded-xl border border-border bg-muted/40 px-4 py-3 text-xs leading-5 text-muted-foreground">
                  Poslovi su spremni za javni listing, pretragu i AI preporuke čim status pređe u{" "}
                  <span className="font-semibold text-foreground">Objavljeno</span>.
                </div>

                {job?.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">Poslodavac</p>
                    <p className="mt-1 text-sm font-semibold text-foreground">{job.company.name}</p>
                    <p className="text-xs text-muted-foreground">{job.company.type === "PLACE" ? "Mesto" : "Kompanija"}</p>
                  </div>
                ) : null}
              </div>
            </FormSection>

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