"use client";

import Link from "next/link";

import type { SoftLaunchReport } from "@/lib/data/soft-launch";

function toneClass(value: "ready" | "attention" | "danger" | "inactive") {
  if (value === "ready") {
    return "border-success/18 bg-success/10 text-success";
  }

  if (value === "danger") {
    return "border-danger/18 bg-danger/10 text-danger";
  }

  if (value === "inactive") {
    return "border-border bg-muted/70 text-muted-foreground";
  }

  return "border-warning/18 bg-warning/10 text-warning";
}

function formatDateTime(value?: string | null) {
  if (!value) {
    return "Bez aktivnosti";
  }

  return new Intl.DateTimeFormat("sr-Latn-RS", {
    day: "2-digit",
    month: "long",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  }).format(new Date(value));
}

function formatDate(value?: string | null) {
  if (!value) {
    return "Nije definisano";
  }

  return new Intl.DateTimeFormat("sr-Latn-RS", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  }).format(new Date(value));
}

export function SoftLaunchCommandCenter({ report }: { report: SoftLaunchReport }) {
  return (
    <section className="admin-section-stack">
      <section className="admin-command-shell">
        <div className="admin-command-header border-b border-border/80 pb-5">
          <div>
            <p className="eyebrow">Soft launch komandni centar</p>
            <p className="mt-2 max-w-3xl text-sm leading-7 text-muted-foreground">
              Kontrolisani rollout prati prve klijente, prve oglase, prve validne leadove i kritične
              operativne signale tokom početnog perioda od 7 do 14 dana.
            </p>
          </div>
          <div className="flex flex-wrap items-center gap-2">
            <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${toneClass(report.enabled ? "ready" : "inactive")}`}>
              {report.enabled ? "Soft launch je aktivan" : "Soft launch je isključen"}
            </span>
            <span className="admin-chip !normal-case !tracking-normal">
              Generisano {formatDateTime(report.generatedAt)}
            </span>
          </div>
        </div>

        <div className="mt-5 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {report.kpis.map((kpi) => (
            <article key={kpi.label} className="admin-kpi-card">
              <div className="flex items-start justify-between gap-3">
                <div className="admin-kpi-label">{kpi.label}</div>
                <span className={`rounded-full border px-2.5 py-1 text-[0.7rem] font-semibold ${toneClass(kpi.state)}`}>
                  {kpi.state === "ready"
                    ? "Spremno"
                    : kpi.state === "danger"
                      ? "Kritično"
                      : kpi.state === "inactive"
                        ? "Isključeno"
                        : "Pažnja"}
                </span>
              </div>
              <div className="admin-kpi-value">{kpi.value}</div>
              <p className="mt-2 text-sm leading-7 text-muted-foreground">{kpi.detail}</p>
            </article>
          ))}
        </div>
      </section>

      <section className="grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_minmax(360px,0.9fr)]">
        <div className="admin-command-shell">
          <div className="admin-command-header border-b border-border/80 pb-5">
            <div>
              <p className="eyebrow">Launch status</p>
              <h3 className="mt-3 text-[1.55rem] font-semibold text-foreground">
                Prozor, cohort i lead signal
              </h3>
            </div>
          </div>

          <div className="mt-5 grid gap-4 lg:grid-cols-2">
            <div className="summary-item">
              <div className="summary-item-label">Soft launch prozor</div>
              <div className="summary-item-value">
                {formatDate(report.window.startDate)} → {formatDate(report.window.endDate)}
              </div>
              <p className="mt-3 text-sm leading-7 text-muted-foreground">
                Aktivno dana: {report.window.daysRunning ?? 0}. Preostalo dana:{" "}
                {report.window.daysRemaining ?? 0}. Cilj je stabilan rad u rasponu od{" "}
                {report.window.targetMinDays} do {report.window.targetMaxDays} dana.
              </p>
            </div>

            <div className="summary-item">
              <div className="summary-item-label">Launch cohort</div>
              <div className="summary-item-value">
                {report.cohort.activeClientAccounts} aktivnih naloga / {report.cohort.activeClientCompanies} klijenata
              </div>
              <p className="mt-3 text-sm leading-7 text-muted-foreground">
                Maksimalni prag u ovom režimu je {report.thresholds.maxClientAccounts} aktivnih
                portal naloga, kako bi podrška, QA i ispravke ostale pod punom kontrolom.
              </p>
            </div>

            <div className="summary-item">
              <div className="summary-item-label">Lead signal</div>
              <div className="summary-item-value">
                {report.leads.last14Days} leadova u 14 dana
              </div>
              <p className="mt-3 text-sm leading-7 text-muted-foreground">
                Danas: {report.leads.today}. Poslednjih 7 dana: {report.leads.last7Days}. Prag za
                uspešan soft launch je najmanje {report.thresholds.minValidLeads} validnih leadova.
              </p>
            </div>

            <div className="summary-item">
              <div className="summary-item-label">Oglasi i isticanja</div>
              <div className="summary-item-value">
                {report.cohort.activeAds} aktivnih oglasa / {report.cohort.activePlacements} isticanja
              </div>
              <p className="mt-3 text-sm leading-7 text-muted-foreground">
                Soft launch oglasni kapacitet je limitiran na {report.thresholds.maxActiveAds} live
                kampanja kako bi se lakše pratili učinak, rotacija i moguće greške.
              </p>
            </div>
          </div>
        </div>

        <aside className="admin-command-shell">
          <div className="admin-command-header border-b border-border/80 pb-5">
            <div>
              <p className="eyebrow">Brze intervencije</p>
              <h3 className="mt-3 text-[1.55rem] font-semibold text-foreground">
                Šta sada treba uraditi
              </h3>
            </div>
          </div>

          <div className="mt-5 space-y-3">
            {report.nextActions.map((action) => (
              <div key={action.title} className="summary-item">
                <div className="summary-item-label">Sledeći potez</div>
                <div className="summary-item-value">{action.title}</div>
                <p className="mt-2 text-sm leading-7 text-muted-foreground">{action.copy}</p>
                <div className="mt-4">
                  <Link href={action.href} className="ghost-button px-4 py-2 text-sm">
                    Otvori
                  </Link>
                </div>
              </div>
            ))}
          </div>
        </aside>
      </section>

      <section className="grid gap-6 xl:grid-cols-3">
        <div className="admin-command-shell">
          <div className="admin-command-header border-b border-border/80 pb-5">
            <div>
              <p className="eyebrow">Prvi klijenti</p>
              <h3 className="mt-3 text-[1.35rem] font-semibold text-foreground">
                Aktivni nalozi u cohort-u
              </h3>
            </div>
          </div>

          <div className="mt-5 space-y-3">
            {report.firstClients.length ? (
              report.firstClients.map((client) => (
                <article key={`${client.companyId}-${client.lastSeenAt || "never"}`} className="summary-item">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="summary-item-value">{client.companyName}</div>
                      <p className="mt-2 text-sm leading-7 text-muted-foreground">
                        Paket: {client.packageLabel} • Aktivnih naloga: {client.accountCount}
                      </p>
                    </div>
                    <Link href={`/kompanije/${client.slug}`} className="admin-chip !normal-case !tracking-normal">
                      Profil
                    </Link>
                  </div>
                  <p className="mt-2 text-sm leading-6 text-muted-foreground">
                    Poslednja aktivnost: {formatDateTime(client.lastSeenAt)}
                  </p>
                </article>
              ))
            ) : (
              <div className="summary-item text-sm leading-7 text-muted-foreground">
                Još nema aktivnih klijentskih naloga u cohort-u. Prvo uvedite mali broj pravih
                klijenata kroz portal naloge.
              </div>
            )}
          </div>
        </div>

        <div className="admin-command-shell">
          <div className="admin-command-header border-b border-border/80 pb-5">
            <div>
              <p className="eyebrow">Prvi oglasi</p>
              <h3 className="mt-3 text-[1.35rem] font-semibold text-foreground">
                Aktivne kampanje i zakup
              </h3>
            </div>
          </div>

          <div className="mt-5 space-y-3">
            {report.firstAds.length ? (
              report.firstAds.map((ad) => (
                <article key={ad.id} className="summary-item">
                  <div className="summary-item-label">{ad.pageType}</div>
                  <div className="summary-item-value">{ad.name}</div>
                  <p className="mt-2 text-sm leading-7 text-muted-foreground">
                    Slot: {ad.slot}
                    {ad.companyName ? ` • Partner: ${ad.companyName}` : ""}
                  </p>
                  <p className="mt-2 text-sm leading-6 text-muted-foreground">
                    Aktivno: {formatDate(ad.startsAt)} → {formatDate(ad.endsAt)}
                  </p>
                </article>
              ))
            ) : (
              <div className="summary-item text-sm leading-7 text-muted-foreground">
                Još nema aktivnih oglasa u kontrolisanom launch prozoru. Ubacite mali broj kvalitetnih
                kampanja pre šireg puštanja.
              </div>
            )}
          </div>
        </div>

        <div className="admin-command-shell">
          <div className="admin-command-header border-b border-border/80 pb-5">
            <div>
              <p className="eyebrow">Prvi leadovi</p>
              <h3 className="mt-3 text-[1.35rem] font-semibold text-foreground">
                Validni signali i upiti
              </h3>
            </div>
          </div>

          <div className="mt-5 space-y-3">
            {report.leads.topProfiles.length ? (
              report.leads.topProfiles.map((profile) => (
                <article key={profile.companyId} className="summary-item">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="summary-item-value">{profile.companyName}</div>
                      <p className="mt-2 text-sm leading-7 text-muted-foreground">
                        Ukupno leadova: {profile.total}
                      </p>
                    </div>
                    <Link href={`/kompanije/${profile.slug}`} className="admin-chip !normal-case !tracking-normal">
                      Otvori
                    </Link>
                  </div>
                  <div className="mt-3 flex flex-wrap gap-2">
                    <span className="admin-chip !normal-case !tracking-normal">Pozivi {profile.calls}</span>
                    <span className="admin-chip !normal-case !tracking-normal">E-mail {profile.emails}</span>
                    <span className="admin-chip !normal-case !tracking-normal">Sajt {profile.websites}</span>
                    <span className="admin-chip !normal-case !tracking-normal">Uputstva {profile.directions}</span>
                  </div>
                </article>
              ))
            ) : (
              <div className="summary-item text-sm leading-7 text-muted-foreground">
                Još nema dovoljno lead signala. Aktivirajte prve kampanje, profile i CTA tokove da
                se pojave prvi validni pozivi, email klikovi i uputstva.
              </div>
            )}

            {report.leads.recentCommercialInquiries.length ? (
              <div className="summary-item">
                <div className="summary-item-label">Sveži komercijalni upiti</div>
                <div className="mt-3 space-y-2">
                  {report.leads.recentCommercialInquiries.map((inquiry) => (
                    <div key={inquiry.id} className="rounded-[1rem] border border-border/80 bg-white/80 px-3 py-3">
                      <div className="text-sm font-semibold text-foreground">
                        {inquiry.companyName || inquiry.contactName}
                      </div>
                      <div className="mt-1 text-sm text-muted-foreground">
                        {inquiry.inquiryType} • {formatDateTime(inquiry.createdAt)}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
          </div>
        </div>
      </section>

      <section className="admin-command-shell">
        <div className="admin-command-header border-b border-border/80 pb-5">
          <div>
            <p className="eyebrow">Praćenje grešaka</p>
            <h3 className="mt-3 text-[1.45rem] font-semibold text-foreground">
              Operativni signali i brzo ispravljanje
            </h3>
          </div>
        </div>

        <div className="mt-5 grid gap-4 lg:grid-cols-2">
          <div className="space-y-3">
            <div className="summary-item">
              <div className="summary-item-label">Operativni rezime</div>
              <div className="mt-3 grid gap-3 sm:grid-cols-2">
                <div className="admin-kpi-card">
                  <div className="admin-kpi-label">Failed notifikacije 14 dana</div>
                  <div className="admin-kpi-value">{report.operations.failedNotifications14Days}</div>
                </div>
                <div className="admin-kpi-card">
                  <div className="admin-kpi-label">Računi van roka</div>
                  <div className="admin-kpi-value">{report.operations.overdueInvoices}</div>
                </div>
                <div className="admin-kpi-card">
                  <div className="admin-kpi-label">Prijave na čekanju</div>
                  <div className="admin-kpi-value">{report.operations.pendingSubmissions}</div>
                </div>
                <div className="admin-kpi-card">
                  <div className="admin-kpi-label">Recenzije na čekanju</div>
                  <div className="admin-kpi-value">{report.operations.pendingReviews}</div>
                </div>
                <div className="admin-kpi-card">
                  <div className="admin-kpi-label">Komercijalni upiti na obradi</div>
                  <div className="admin-kpi-value">{report.cohort.openCommercialInquiries}</div>
                </div>
                <div className="admin-kpi-card">
                  <div className="admin-kpi-label">Portal zahtevi otvoreni</div>
                  <div className="admin-kpi-value">{report.cohort.openPortalRequests}</div>
                </div>
              </div>
            </div>
          </div>

          <div className="space-y-3">
            {report.issues.length ? (
              report.issues.map((issue) => (
                <article key={issue.key} className="summary-item">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="summary-item-value">{issue.title}</div>
                      <p className="mt-2 text-sm leading-7 text-muted-foreground">
                        {issue.description}
                      </p>
                    </div>
                    <span className={`rounded-full border px-2.5 py-1 text-[0.7rem] font-semibold ${toneClass(issue.state)}`}>
                      {issue.state === "danger" ? "Kritično" : "Pažnja"}
                    </span>
                  </div>
                </article>
              ))
            ) : (
              <div className="summary-item text-sm leading-7 text-muted-foreground">
                Trenutno nema otvorenih soft launch upozorenja. Sistem izgleda spremno za mirno
                kontrolisano puštanje i praćenje prvih korisnika.
              </div>
            )}

            {report.operations.criticalDiagnostics.length ? (
              <div className="summary-item">
                <div className="summary-item-label">Kritične dijagnostike</div>
                <div className="mt-3 space-y-2">
                  {report.operations.criticalDiagnostics.map((item) => (
                    <div key={item.label} className="rounded-[1rem] border border-danger/12 bg-danger/6 px-3 py-3">
                      <div className="text-sm font-semibold text-foreground">{item.label}</div>
                      <div className="mt-1 text-sm text-muted-foreground">{item.summary}</div>
                    </div>
                  ))}
                </div>
              </div>
            ) : null}
          </div>
        </div>
      </section>
    </section>
  );
}
