import Link from "next/link";
import { notFound } from "next/navigation";
import { PublicShell } from "@/components/public/public-shell";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ALL_ORGANIZATIONS, getOrganizationBySlug, SUBSIDIARIES } from "@/lib/sag/entities";
import { getToastForEntity } from "@/lib/sag/toast-sample";
import {
  getDiscographySummary,
  getPortfolioMusicData,
  getUpcomingBookings,
  type PortfolioReleaseStreamingLinks,
  type PortfolioSocialLinks,
} from "@/lib/music/portfolio-data";
import { formatCurrency, formatDate } from "@/lib/utils";

export function generateStaticParams() {
  return ALL_ORGANIZATIONS.map((o) => ({ slug: o.slug }));
}

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const org = getOrganizationBySlug(slug);
  return { title: org?.name || "Not found" };
}

export default async function OrgPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const org = getOrganizationBySlug(slug);
  if (!org) notFound();

  const toast = getToastForEntity(org.slug);
  const related = SUBSIDIARIES.filter((o) => o.slug !== org.slug && o.industry === org.industry).slice(0, 3);
  const music = org.industry === "Music & Entertainment" ? getPortfolioMusicData(org.slug) : null;
  const upcomingBookings = music ? getUpcomingBookings(music, 3) : [];
  const discography = music ? getDiscographySummary(music, 5) : [];

  return (
    <PublicShell>
      <section
        className="border-b"
        style={{
          background: `linear-gradient(135deg, ${org.primaryColor}15, transparent 70%)`,
        }}
      >
        <div className="container mx-auto max-w-7xl px-6 py-16">
          <Link href="/portfolio" className="text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1">
            ← All ventures
          </Link>
          <div className="mt-6 flex items-start gap-6">
            {music?.heroImage ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={music.heroImage}
                alt={`${org.name} portrait`}
                className="w-32 h-32 md:w-40 md:h-40 rounded-xl object-cover shrink-0"
              />
            ) : (
              <div
                className="flex items-center justify-center w-20 h-20 rounded-xl text-5xl shrink-0"
                style={{ backgroundColor: `${org.primaryColor}25` }}
              >
                {org.emoji}
              </div>
            )}
            <div className="flex-1">
              <div className="flex flex-wrap items-center gap-2 mb-2">
                <Badge variant="outline">{org.industry}</Badge>
                <Badge variant="success">{org.status}</Badge>
                <Badge variant="secondary">{org.entityType}</Badge>
                <Badge variant="outline">{org.state}</Badge>
              </div>
              <h1 className="text-3xl md:text-5xl font-semibold tracking-tight">{org.name}</h1>
              {org.dba && <p className="mt-1 text-muted-foreground">d/b/a {org.dba}</p>}
              <p className="mt-3 text-xl italic text-muted-foreground">{org.tagline}</p>
              {music?.bio && (
                <p className="mt-4 max-w-3xl text-base leading-relaxed text-foreground/85">
                  {music.bio}
                </p>
              )}
            </div>
          </div>
        </div>
      </section>

      <section className="container mx-auto max-w-7xl px-6 py-12">
        <div className="grid gap-10 lg:grid-cols-3">
          <div className="lg:col-span-2 space-y-8">
            <div>
              <h2 className="text-2xl font-semibold tracking-tight mb-3">About</h2>
              <p className="text-lg leading-relaxed text-foreground/85">{org.blurb}</p>
            </div>

            {music && (
              <>
                <LatestReleaseCard
                  release={music.latestRelease}
                  artistColor={org.primaryColor}
                />

                <UpcomingBookingsList bookings={upcomingBookings} />

                <DiscographyTable entries={discography} />
              </>
            )}

            {toast && (
              <div>
                <h2 className="text-2xl font-semibold tracking-tight mb-3">2025 sales (Toast POS)</h2>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                  <Card><CardContent className="p-4">
                    <div className="text-xs text-muted-foreground uppercase">Net sales</div>
                    <div className="mt-1 text-xl font-semibold">{formatCurrency(toast.netSales)}</div>
                  </CardContent></Card>
                  <Card><CardContent className="p-4">
                    <div className="text-xs text-muted-foreground uppercase">Gross</div>
                    <div className="mt-1 text-xl font-semibold">{formatCurrency(toast.grossSales)}</div>
                  </CardContent></Card>
                  <Card><CardContent className="p-4">
                    <div className="text-xs text-muted-foreground uppercase">Items</div>
                    <div className="mt-1 text-xl font-semibold">{toast.itemQty.toLocaleString()}</div>
                  </CardContent></Card>
                  <Card><CardContent className="p-4">
                    <div className="text-xs text-muted-foreground uppercase">Tax</div>
                    <div className="mt-1 text-xl font-semibold">{formatCurrency(toast.taxAmount)}</div>
                  </CardContent></Card>
                </div>
                <p className="mt-3 text-xs text-muted-foreground">Source: Toast POS export, partial year.</p>
              </div>
            )}

            {org.slug === "koshu-sake" && (
              <Card>
                <CardContent className="p-6">
                  <Badge variant="warning">In application</Badge>
                  <h3 className="mt-3 text-xl font-semibold">TTB Winery Permit (in progress)</h3>
                  <p className="mt-2 text-sm text-muted-foreground">
                    Koshu is pursuing a Federal Basic Permit as a Wine Producer with the Alcohol and Tobacco Tax and Trade Bureau (TTB), plus state-level NC ABC approval. Sake is federally classified as wine. Progress is tracked internally via the SAG operations app.
                  </p>
                </CardContent>
              </Card>
            )}
          </div>

          <aside className="space-y-6">
            <Card>
              <CardContent className="p-6 space-y-3 text-sm">
                <Row label="Industry">{org.industry}</Row>
                <Row label="Entity type">{org.entityType}</Row>
                <Row label="State">{org.state}</Row>
                <Row label="Status">{org.status}</Row>
                <Row label="Parent">South Armz Global</Row>
                {org.website && (
                  <Row label="Website">
                    <a href={org.website} target="_blank" rel="noopener noreferrer" className="text-[var(--sag-brand)] hover:underline">
                      Visit ↗
                    </a>
                  </Row>
                )}
              </CardContent>
            </Card>
            <Button asChild className="w-full" variant="brand">
              <Link href="/contact">Get in touch</Link>
            </Button>

            {music?.socialLinks && <ConnectCard links={music.socialLinks} />}
          </aside>
        </div>

        {related.length > 0 && (
          <>
            <Separator className="my-16" />
            <h2 className="text-2xl font-semibold tracking-tight mb-6">More in {org.industry}</h2>
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
              {related.map((r) => (
                <Link key={r.slug} href={`/portfolio/${r.slug}`} className="group">
                  <Card className="h-full transition-all group-hover:shadow-md">
                    <CardContent className="p-5">
                      <div className="flex items-center gap-3 mb-2">
                        <span className="text-2xl">{r.emoji}</span>
                        <h3 className="text-base font-semibold">{r.name}</h3>
                      </div>
                      <p className="text-sm text-muted-foreground line-clamp-2">{r.blurb}</p>
                    </CardContent>
                  </Card>
                </Link>
              ))}
            </div>
          </>
        )}
      </section>
    </PublicShell>
  );
}

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="flex justify-between gap-4">
      <span className="text-muted-foreground">{label}</span>
      <span className="font-medium text-right">{children}</span>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Music-specific sections — server-rendered so they ship in the initial HTML
// (SEO-critical). All gracefully degrade when the JSON has no data yet.
// ──────────────────────────────────────────────────────────────────────────

function LatestReleaseCard({
  release,
  artistColor,
}: {
  release: NonNullable<ReturnType<typeof getPortfolioMusicData>>["latestRelease"];
  artistColor?: string;
}) {
  return (
    <div>
      <h2 className="text-2xl font-semibold tracking-tight mb-3">Latest release</h2>
      {!release ? (
        <Card>
          <CardContent className="p-6 text-sm text-muted-foreground">
            New music in the works. Check back soon.
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-5">
            <div className="flex items-start gap-5 flex-wrap sm:flex-nowrap">
              {release.coverImage ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={release.coverImage}
                  alt={`${release.title} cover art`}
                  className="w-32 h-32 rounded-md object-cover shrink-0"
                />
              ) : (
                <div
                  className="w-32 h-32 rounded-md flex items-center justify-center text-5xl shrink-0"
                  style={{ backgroundColor: `${artistColor ?? "#7c3aed"}25` }}
                  aria-hidden
                >
                  💿
                </div>
              )}
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2 flex-wrap mb-1">
                  <Badge variant="outline">{release.type}</Badge>
                  <span className="text-xs text-muted-foreground">
                    {formatDate(release.releaseDate)}
                  </span>
                </div>
                <h3 className="text-xl font-semibold">{release.title}</h3>
                <StreamingLinksRow links={release.streamingLinks} />
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function StreamingLinksRow({
  links,
}: {
  links?: PortfolioReleaseStreamingLinks;
}) {
  if (!links) return null;
  const items: Array<{ label: string; url: string }> = [];
  if (links.spotify) items.push({ label: "Spotify", url: links.spotify });
  if (links.appleMusic) items.push({ label: "Apple Music", url: links.appleMusic });
  if (links.youtube) items.push({ label: "YouTube", url: links.youtube });
  if (links.soundcloud) items.push({ label: "SoundCloud", url: links.soundcloud });
  if (links.bandcamp) items.push({ label: "Bandcamp", url: links.bandcamp });

  if (items.length === 0) return null;

  return (
    <div className="mt-4 flex flex-wrap gap-2">
      {items.map((item) => (
        <Button
          key={item.label}
          asChild
          variant="outline"
          size="sm"
        >
          <a href={item.url} target="_blank" rel="noopener noreferrer">
            {item.label} ↗
          </a>
        </Button>
      ))}
    </div>
  );
}

function UpcomingBookingsList({
  bookings,
}: {
  bookings: Array<{ date: string; venue: string; location?: string | null }>;
}) {
  return (
    <div>
      <h2 className="text-2xl font-semibold tracking-tight mb-3">Upcoming bookings</h2>
      {bookings.length === 0 ? (
        <Card>
          <CardContent className="p-6 text-sm text-muted-foreground">
            No upcoming bookings announced. Want to book a date?{" "}
            <Link href="/contact" className="text-[var(--sag-brand)] hover:underline">
              Get in touch
            </Link>
            .
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <ul className="divide-y">
              {bookings.map((b, i) => (
                <li key={`${b.date}-${i}`} className="flex items-center gap-4 px-5 py-4">
                  <div className="text-xs font-mono uppercase tracking-wider text-muted-foreground w-24 shrink-0">
                    {formatDate(b.date)}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="font-medium">{b.venue}</div>
                    {b.location && (
                      <div className="text-xs text-muted-foreground">📍 {b.location}</div>
                    )}
                  </div>
                </li>
              ))}
            </ul>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function DiscographyTable({
  entries,
}: {
  entries: Array<{ title: string; type: string; releaseDate: string }>;
}) {
  return (
    <div>
      <h2 className="text-2xl font-semibold tracking-tight mb-3">Discography</h2>
      {entries.length === 0 ? (
        <Card>
          <CardContent className="p-6 text-sm text-muted-foreground">
            Discography coming soon.
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <table className="w-full text-sm">
              <thead className="border-b">
                <tr className="text-left text-xs uppercase tracking-wider text-muted-foreground">
                  <th className="px-5 py-3 font-medium">Title</th>
                  <th className="px-5 py-3 font-medium">Format</th>
                  <th className="px-5 py-3 font-medium">Released</th>
                </tr>
              </thead>
              <tbody>
                {entries.map((e, i) => (
                  <tr key={`${e.title}-${i}`} className="border-b last:border-0">
                    <td className="px-5 py-3 font-medium">{e.title}</td>
                    <td className="px-5 py-3 text-muted-foreground">{e.type}</td>
                    <td className="px-5 py-3 text-muted-foreground tabular-nums">
                      {formatDate(e.releaseDate)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </CardContent>
        </Card>
      )}
    </div>
  );
}

function ConnectCard({ links }: { links: PortfolioSocialLinks }) {
  const items: Array<{ label: string; url: string }> = [];
  if (links.instagram) items.push({ label: "Instagram", url: links.instagram });
  if (links.spotify) items.push({ label: "Spotify", url: links.spotify });
  if (links.appleMusic) items.push({ label: "Apple Music", url: links.appleMusic });
  if (links.youtube) items.push({ label: "YouTube", url: links.youtube });
  if (links.soundcloud) items.push({ label: "SoundCloud", url: links.soundcloud });
  if (links.tiktok) items.push({ label: "TikTok", url: links.tiktok });
  if (links.twitter) items.push({ label: "X / Twitter", url: links.twitter });

  if (items.length === 0) return null;

  return (
    <Card>
      <CardContent className="p-6 space-y-3">
        <h3 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
          Connect
        </h3>
        <ul className="space-y-2 text-sm">
          {items.map((item) => (
            <li key={item.label}>
              <a
                href={item.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-[var(--sag-brand)] hover:underline inline-flex items-center gap-1"
              >
                {item.label} ↗
              </a>
            </li>
          ))}
        </ul>
      </CardContent>
    </Card>
  );
}
