"use client";

import Link from "next/link";
import { useMemo } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Kpi, KpiStrip } from "@/components/ui/kpi";
import { MiniKpi } from "@/components/ui/mini-kpi";
import { useLocalStorage } from "@/lib/hooks/use-local-storage";
import { ALL_ORGANIZATIONS } from "@/lib/sag/entities";
import { formatCurrency, formatDate } from "@/lib/utils";
import {
  MUSIC_ENTITY_SLUGS,
  type ArtistSlug,
  type MusicBooking,
  type MusicContact,
  type MusicRelease,
} from "@/lib/music/types";

export function MusicLanding() {
  const [releases] = useLocalStorage<MusicRelease[]>("sag.music.releases", []);
  const [bookings] = useLocalStorage<MusicBooking[]>("sag.music.bookings", []);
  const [contacts] = useLocalStorage<MusicContact[]>("sag.music.contacts", []);

  const today = new Date().toISOString().slice(0, 10);
  const stats = useMemo(() => {
    const out = new Map<
      ArtistSlug,
      {
        upcomingReleases: MusicRelease[];
        upcomingBookings: MusicBooking[];
        confirmedFeeYTD: number;
        contactCount: number;
        lastReleased?: MusicRelease;
      }
    >();
    for (const slug of MUSIC_ENTITY_SLUGS) {
      const releasesForSlug = releases.filter((r) => r.artistSlug === slug);
      const bookingsForSlug = bookings.filter((b) => b.artistSlug === slug);
      const contactsForSlug = contacts.filter((c) => c.artistSlug === slug);
      const upcomingReleases = releasesForSlug
        .filter((r) => r.status !== "Released" && r.status !== "Shelved" && r.releaseDate >= today)
        .sort((a, b) => a.releaseDate.localeCompare(b.releaseDate));
      const upcomingBookings = bookingsForSlug
        .filter(
          (b) =>
            (b.status === "Inquiry" ||
              b.status === "Held" ||
              b.status === "Contract Sent" ||
              b.status === "Confirmed") &&
            b.date >= today
        )
        .sort((a, b) => a.date.localeCompare(b.date));
      const year = today.slice(0, 4);
      const confirmedFeeYTD = bookingsForSlug
        .filter(
          (b) =>
            b.date.startsWith(year) &&
            (b.status === "Confirmed" || b.status === "Performed" || b.status === "Paid")
        )
        .reduce((a, b) => a + b.fee, 0);
      const lastReleased = releasesForSlug
        .filter((r) => r.status === "Released")
        .sort((a, b) => b.releaseDate.localeCompare(a.releaseDate))[0];
      out.set(slug, {
        upcomingReleases,
        upcomingBookings,
        confirmedFeeYTD,
        contactCount: contactsForSlug.length,
        lastReleased,
      });
    }
    return out;
  }, [releases, bookings, contacts, today]);

  const totals = useMemo(() => {
    return {
      totalReleases: releases.length,
      upcomingBookings: bookings.filter(
        (b) =>
          b.date >= today &&
          (b.status === "Confirmed" || b.status === "Held" || b.status === "Contract Sent")
      ).length,
      lifetimeFee: bookings.reduce((a, b) => a + b.fee, 0),
      contacts: contacts.length,
    };
  }, [releases, bookings, contacts, today]);

  return (
    <div className="space-y-6 max-w-6xl">
      <Card>
        <CardContent className="p-6">
          <h2 className="text-base font-semibold">Music ops, one workspace</h2>
          <p className="mt-2 text-sm text-foreground/85 max-w-3xl">
            Manage Riich Villainz (the label Glenn co-owns 49%), Ricoveli (the recording artist
            Glenn manages on behalf of the label), and DJ Ricoveli (the SAG-owned subsidiary
            that books Ricoveli for live DJ sets). Releases, bookings, royalty splits, contacts,
            and streaming snapshots — all in one place.
          </p>
          <KpiStrip cols={4} className="mt-4">
            <Kpi label="Releases tracked" value={String(totals.totalReleases)} />
            <Kpi
              label="Upcoming bookings"
              value={String(totals.upcomingBookings)}
              tone={totals.upcomingBookings > 0 ? "violet" : "neutral"}
            />
            <Kpi
              label="Lifetime fee booked"
              value={formatCurrency(totals.lifetimeFee)}
              tone="emerald"
            />
            <Kpi label="Contacts" value={String(totals.contacts)} />
          </KpiStrip>
        </CardContent>
      </Card>

      <div className="grid gap-4 md:grid-cols-3">
        {MUSIC_ENTITY_SLUGS.map((slug) => {
          const org = ALL_ORGANIZATIONS.find((o) => o.slug === slug);
          if (!org) return null;
          const s = stats.get(slug);
          return (
            <Card key={slug} className="flex flex-col">
              <CardContent className="p-5 flex-1 flex flex-col">
                <div className="flex items-center gap-3 mb-3">
                  <div
                    className="w-14 h-14 rounded-xl flex items-center justify-center text-3xl shrink-0"
                    style={{ backgroundColor: `${org.primaryColor}25` }}
                  >
                    {org.emoji}
                  </div>
                  <div className="min-w-0">
                    <h3 className="text-base font-semibold truncate">{org.name}</h3>
                    <p className="text-xs italic text-muted-foreground truncate">
                      {org.tagline}
                    </p>
                  </div>
                </div>

                <div className="flex flex-wrap gap-1 mb-3">
                  {slug === "riich-villainz" && (
                    <>
                      <Badge variant="warning">Label · 49% Glenn</Badge>
                      <Badge variant="outline">Owner investment</Badge>
                    </>
                  )}
                  {slug === "dj-ricoveli" && (
                    <>
                      <Badge variant="info">SAG subsidiary</Badge>
                      <Badge variant="outline">Recording + DJ</Badge>
                    </>
                  )}
                </div>

                <p className="text-xs text-muted-foreground line-clamp-3 mb-4">{org.blurb}</p>

                <div className="space-y-2 mb-4">
                  <MiniKpi label="Upcoming releases" value={String(s?.upcomingReleases.length ?? 0)} />
                  <MiniKpi label="Upcoming bookings" value={String(s?.upcomingBookings.length ?? 0)} />
                  <MiniKpi
                    label="Booked fees YTD"
                    value={formatCurrency(s?.confirmedFeeYTD ?? 0)}
                  />
                  <MiniKpi label="Contacts on file" value={String(s?.contactCount ?? 0)} />
                </div>

                {s?.lastReleased && (
                  <div className="mb-3 rounded-md border bg-muted/30 p-2 text-[11px]">
                    <div className="text-muted-foreground">Last release</div>
                    <div className="font-medium">{s.lastReleased.title}</div>
                    <div className="text-muted-foreground">
                      {s.lastReleased.type} · {formatDate(s.lastReleased.releaseDate)}
                    </div>
                  </div>
                )}

                <div className="mt-auto flex flex-col gap-2">
                  <Button asChild variant="brand" size="sm">
                    <Link href={`/app/music/${slug}`}>Open workspace →</Link>
                  </Button>
                  <Button asChild variant="outline" size="sm">
                    <Link href={`/portfolio/${slug}`}>Public bio</Link>
                  </Button>
                </div>
              </CardContent>
            </Card>
          );
        })}
      </div>

      <Card className="border-dashed">
        <CardContent className="p-5 text-xs text-muted-foreground">
          Streaming numbers are manual snapshots today. When the Spotify-for-Artists and Apple
          Music for Artists APIs are wired, the per-artist workspace will auto-pull monthly
          listeners and top tracks. Until then, paste them in by hand and date the snapshot.
          Releases sync to the social composer when you schedule a launch post.
        </CardContent>
      </Card>
    </div>
  );
}
