import Link from "next/link";
import { notFound } from "next/navigation";
import { Card } from "@/components/ui/card";
import { env } from "@/lib/env";
import { createClient } from "@/lib/supabase/server";
import { getPublicSourceAssetUrl, getPublicThumbnailUrl, isPdfMetaAsset } from "@/lib/storage";
import { formatInteger } from "@/lib/utils";
import { computeRates } from "@/lib/metrics";
import { getViewerContext } from "@/lib/auth";
import { getLocalDb } from "@/lib/local-db";
import { EmailDeepDiveCharts } from "@/components/charts/email-deepdive-charts";
import { AnimatedCounter } from "@/components/ui/animated-counter";

type EventRow = {
  sent_email_name: string;
  primary_country_code: string;
  approved_document_name: string;
  opened: number;
  total_opens: number;
  clicked: number;
  total_clicks: number;
  thumbs_up: number;
  thumbs_down: number;
  sent_date: string | null;
  last_open: string | null;
  last_click: string | null;
  created_at: string | null;
};

type MetadataRow = {
  approved_document_name: string;
  friendly_title: string | null;
  brand: string | null;
  notes: string | null;
  thumbnail_path: string | null;
  campaign_group: string | null;
};

function monthStart(value: string | null | undefined) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  return `${date.toISOString().slice(0, 7)}-01`;
}

const PIE_COLORS = ["#2663AC", "#F7993A", "#5AA3D6", "#87C4A3", "#8F7EE7", "#D86762"];

export default async function EmailEventDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const viewer = await getViewerContext();
  const { id } = await params;
  const approvedDocumentName = decodeURIComponent(id);

  if (!approvedDocumentName) {
    notFound();
  }

  let events: EventRow[] = [];
  let metadata: MetadataRow | null = null;

  if (!env.hasSupabasePublicEnv) {
    const db = await getLocalDb();
    const allowedCountries =
      viewer.role === "admin"
        ? null
        : new Set(viewer.allowedCountries.map((country) => country.toUpperCase()));
    const sentimentByEvent = new Map(
      db.email_sentiment.map((item) => [item.sent_email_name, item]),
    );

    events = db.raw_email_events
      .filter((row) => row.approved_document_name === approvedDocumentName)
      .filter((row) =>
        allowedCountries ? allowedCountries.has((row.primary_country_code || "").toUpperCase()) : true,
      )
      .map((row) => {
        const sentiment = sentimentByEvent.get(row.sent_email_name);
        return {
        sent_email_name: row.sent_email_name,
        primary_country_code: row.primary_country_code,
        approved_document_name: row.approved_document_name,
        opened: Number(row.opened ?? 0),
        total_opens: Number(row.total_opens ?? 0),
        clicked: Number(row.clicked ?? 0),
        total_clicks: Number(row.total_clicks ?? 0),
        thumbs_up: Number(sentiment?.thumbs_up ?? 0),
        thumbs_down: Number(sentiment?.thumbs_down ?? 0),
        sent_date: row.sent_date,
        last_open: row.last_open,
        last_click: row.last_click,
        created_at: row.created_at,
      };
      });

    const found = db.email_metadata.find((row) => row.approved_document_name === approvedDocumentName);
    metadata = found
      ? {
          approved_document_name: found.approved_document_name,
          friendly_title: found.friendly_title,
          brand: found.brand,
          notes: found.notes,
          thumbnail_path: found.thumbnail_path,
          campaign_group: found.campaign_group,
        }
      : null;
  } else {
    const supabase = await createClient();
    let query = supabase
      .from("raw_email_events")
      .select(
        "sent_email_name, primary_country_code, approved_document_name, opened, total_opens, clicked, total_clicks, sent_date, last_open, last_click, created_at",
      )
      .eq("approved_document_name", approvedDocumentName);

    if (viewer.role !== "admin") {
      if (viewer.allowedCountries.length === 0) {
        notFound();
      }
      query = query.in("primary_country_code", viewer.allowedCountries);
    }

    const [eventsRes, metadataRes] = await Promise.all([
      query,
      supabase
        .from("email_metadata")
        .select("approved_document_name, friendly_title, brand, notes, thumbnail_path, campaign_group")
        .eq("approved_document_name", approvedDocumentName)
        .maybeSingle(),
    ]);

    if (eventsRes.error) throw new Error(eventsRes.error.message);
    if (metadataRes.error) throw new Error(metadataRes.error.message);

    events = ((eventsRes.data ?? []) as EventRow[]).map((row) => ({
      ...row,
      thumbs_up: 0,
      thumbs_down: 0,
    }));
    metadata = (metadataRes.data as MetadataRow | null) ?? null;
  }

  if (events.length === 0) {
    notFound();
  }

  const totals = computeRates({
    total_emails_sent: events.length,
    total_opened: events.reduce((sum, row) => sum + Number(row.opened ?? 0), 0),
    total_opens: events.reduce((sum, row) => sum + Number(row.total_opens ?? 0), 0),
    total_clicked: events.reduce((sum, row) => sum + Number(row.clicked ?? 0), 0),
    total_clicks: events.reduce((sum, row) => sum + Number(row.total_clicks ?? 0), 0),
  });

  const sentimentTotals = events.reduce(
    (acc, row) => {
      acc.thumbs_up += Number(row.thumbs_up ?? 0);
      acc.thumbs_down += Number(row.thumbs_down ?? 0);
      return acc;
    },
    { thumbs_up: 0, thumbs_down: 0 },
  );
  const sentimentVotes = sentimentTotals.thumbs_up + sentimentTotals.thumbs_down;
  const positiveSentimentRate = sentimentVotes > 0 ? sentimentTotals.thumbs_up / sentimentVotes : 0;

  const friendlyTitle = metadata?.friendly_title || approvedDocumentName;
  const brand = (metadata?.brand || "Unspecified").trim() || "Unspecified";
  const thumbnailUrl = getPublicThumbnailUrl(metadata?.thumbnail_path ?? null);
  const sourceAssetUrl = getPublicSourceAssetUrl(metadata?.thumbnail_path ?? null);
  const isPdfAsset = isPdfMetaAsset(metadata?.thumbnail_path ?? null);

  const monthlyBuckets = new Map<
    string,
    { month_start: string; total_emails_sent: number; total_opened: number; total_clicked: number }
  >();

  const countryBuckets = new Map<string, number>();

  for (const event of events) {
    const m = monthStart(event.sent_date || event.created_at);
    if (m) {
      const bucket = monthlyBuckets.get(m) ?? {
        month_start: m,
        total_emails_sent: 0,
        total_opened: 0,
        total_clicked: 0,
      };
      bucket.total_emails_sent += 1;
      bucket.total_opened += Number(event.opened ?? 0);
      bucket.total_clicked += Number(event.clicked ?? 0);
      monthlyBuckets.set(m, bucket);
    }

    const country = (event.primary_country_code || "").toUpperCase() || "N/A";
    countryBuckets.set(country, (countryBuckets.get(country) ?? 0) + 1);
  }

  const monthlySeries = [...monthlyBuckets.values()]
    .sort((a, b) => new Date(a.month_start).getTime() - new Date(b.month_start).getTime())
    .map((row) => ({
      ...row,
      open_rate: row.total_emails_sent > 0 ? row.total_opened / row.total_emails_sent : 0,
      ctr: row.total_emails_sent > 0 ? row.total_clicked / row.total_emails_sent : 0,
    }));

  const clicked = Math.min(totals.total_clicked, totals.total_emails_sent);
  const opened = Math.min(Math.max(totals.total_opened, clicked), totals.total_emails_sent);
  const openedNotClicked = Math.max(opened - clicked, 0);
  const unopened = Math.max(totals.total_emails_sent - opened, 0);

  const engagementPie = [
    { name: "Clicked", value: clicked, color: "#F7993A" },
    { name: "Opened (No Click)", value: openedNotClicked, color: "#2663AC" },
    { name: "No Open", value: unopened, color: "#DDE7F3" },
  ];

  const countryPie = [...countryBuckets.entries()].map(([name, value], index) => ({
    name,
    value,
    color: PIE_COLORS[index % PIE_COLORS.length],
  }));

  const latestSent = events
    .map((item) => item.sent_date || item.created_at)
    .filter((item): item is string => Boolean(item))
    .sort((a, b) => new Date(b).getTime() - new Date(a).getTime())[0];

  const recentEvents = [...events]
    .sort((a, b) => new Date(b.sent_date || b.created_at || 0).getTime() - new Date(a.sent_date || a.created_at || 0).getTime())
    .slice(0, 40);

  return (
    <div className="space-y-4">
      <Card>
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="caption text-xs uppercase tracking-[0.2em] text-[#2663AC]">Otsuka VEEVA Deep Dive</p>
            <h2 className="mt-2 text-2xl font-semibold text-slate-900">{friendlyTitle}</h2>
            <p className="mt-1 text-sm text-slate-500">{approvedDocumentName}</p>
            <p className="mt-2 text-xs text-slate-500">
              Brand: {brand} {metadata?.campaign_group ? `· Campaign: ${metadata.campaign_group}` : ""}
            </p>
          </div>
          <Link
            href="/dashboard"
            className="inline-flex h-10 items-center justify-center rounded-lg border border-slate-300 bg-white px-4 text-sm font-medium text-slate-700 transition hover:border-[#F7993A] hover:bg-[#fff4e8]"
          >
            Back to Dashboard
          </Link>
        </div>
      </Card>

      <section className="grid gap-3 sm:grid-cols-2 xl:grid-cols-7">
        <Card className="relative overflow-hidden bg-white ring-1 ring-[#2663AC]/10">
          <div className="absolute left-0 top-0 h-1 w-full bg-[#2663AC]" />
          <p className="caption text-xs uppercase tracking-[0.18em] text-slate-500">Emails Sent</p>
          <p className="mt-2 text-4xl font-semibold tracking-tight text-slate-900">
            <AnimatedCounter value={totals.total_emails_sent} />
          </p>
        </Card>
        <Card className="relative overflow-hidden bg-white ring-1 ring-[#2663AC]/10">
          <div className="absolute left-0 top-0 h-1 w-full bg-[#F7993A]" />
          <p className="caption text-xs uppercase tracking-[0.18em] text-slate-500">Open Rate</p>
          <p className="mt-2 text-4xl font-semibold tracking-tight text-slate-900">
            <AnimatedCounter value={totals.open_rate * 100} format="decimal" decimals={1} suffix="%" />
          </p>
        </Card>
        <Card className="relative overflow-hidden bg-white ring-1 ring-[#2663AC]/10">
          <div className="absolute left-0 top-0 h-1 w-full bg-[#2663AC]" />
          <p className="caption text-xs uppercase tracking-[0.18em] text-slate-500">CTR</p>
          <p className="mt-2 text-4xl font-semibold tracking-tight text-slate-900">
            <AnimatedCounter value={totals.ctr * 100} format="decimal" decimals={1} suffix="%" />
          </p>
        </Card>
        <Card className="relative overflow-hidden bg-white ring-1 ring-[#2663AC]/10">
          <div className="absolute left-0 top-0 h-1 w-full bg-[#4CAF50]" />
          <p className="caption text-xs uppercase tracking-[0.18em] text-slate-500">Thumbs Up</p>
          <p className="mt-2 text-4xl font-semibold tracking-tight text-slate-900">
            <AnimatedCounter value={sentimentTotals.thumbs_up} />
          </p>
        </Card>
        <Card className="relative overflow-hidden bg-white ring-1 ring-[#2663AC]/10">
          <div className="absolute left-0 top-0 h-1 w-full bg-[#E56A54]" />
          <p className="caption text-xs uppercase tracking-[0.18em] text-slate-500">Thumbs Down</p>
          <p className="mt-2 text-4xl font-semibold tracking-tight text-slate-900">
            <AnimatedCounter value={sentimentTotals.thumbs_down} />
          </p>
        </Card>
        <Card className="relative overflow-hidden bg-white ring-1 ring-[#2663AC]/10">
          <div className="absolute left-0 top-0 h-1 w-full bg-[#F7993A]" />
          <p className="caption text-xs uppercase tracking-[0.18em] text-slate-500">Positive Sentiment</p>
          <p className="mt-2 text-4xl font-semibold tracking-tight text-slate-900">
            <AnimatedCounter value={positiveSentimentRate * 100} format="decimal" decimals={1} suffix="%" />
          </p>
        </Card>
        <Card className="relative overflow-hidden bg-white ring-1 ring-[#2663AC]/10">
          <div className="absolute left-0 top-0 h-1 w-full bg-[#F7993A]" />
          <p className="caption text-xs uppercase tracking-[0.18em] text-slate-500">Latest Send</p>
          <p className="mt-2 text-base font-semibold text-slate-900">
            {latestSent ? new Date(latestSent).toLocaleString("en-GB") : "N/A"}
          </p>
        </Card>
      </section>

      <EmailDeepDiveCharts
        monthly={monthlySeries}
        engagementPie={engagementPie}
        countryPie={countryPie}
      />

      <section className="grid gap-4 xl:grid-cols-[1fr_300px]">
        <Card>
          <h3 className="text-sm font-semibold text-slate-900">Event-Level Rows</h3>
          <div className="mt-3 max-h-[420px] overflow-auto rounded-xl border border-slate-200">
            <table className="w-full text-left text-sm">
              <thead className="sticky top-0 bg-slate-50 text-[11px] uppercase tracking-[0.14em] text-slate-500">
                <tr>
                  <th className="px-3 py-2">Sent Email Name</th>
                  <th className="px-3 py-2">Country</th>
                  <th className="px-3 py-2">Sent Date</th>
                  <th className="px-3 py-2">Opened</th>
                  <th className="px-3 py-2">Clicked</th>
                  <th className="px-3 py-2">Thumbs Up</th>
                  <th className="px-3 py-2">Thumbs Down</th>
                  <th className="px-3 py-2">Total Opens</th>
                  <th className="px-3 py-2">Total Clicks</th>
                </tr>
              </thead>
              <tbody>
                {recentEvents.map((row) => (
                  <tr key={row.sent_email_name} className="border-t border-slate-200">
                    <td className="px-3 py-2 text-slate-800">{row.sent_email_name}</td>
                    <td className="px-3 py-2 text-slate-600">{row.primary_country_code}</td>
                    <td className="px-3 py-2 text-slate-600">
                      {row.sent_date ? new Date(row.sent_date).toLocaleString("en-GB") : "N/A"}
                    </td>
                    <td className="px-3 py-2 text-slate-700">{formatInteger(row.opened)}</td>
                    <td className="px-3 py-2 text-slate-700">{formatInteger(row.clicked)}</td>
                    <td className="px-3 py-2 text-emerald-700">{formatInteger(row.thumbs_up)}</td>
                    <td className="px-3 py-2 text-rose-700">{formatInteger(row.thumbs_down)}</td>
                    <td className="px-3 py-2 text-slate-700">{formatInteger(row.total_opens)}</td>
                    <td className="px-3 py-2 text-slate-700">{formatInteger(row.total_clicks)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <p className="mt-2 text-xs text-slate-500">Showing latest {recentEvents.length} events.</p>
        </Card>

        <Card className="h-fit">
          <h3 className="text-sm font-semibold text-slate-900">Metadata</h3>
          {thumbnailUrl ? (
            sourceAssetUrl && isPdfAsset ? (
              <a href={sourceAssetUrl} target="_blank" rel="noreferrer" className="block">
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img src={thumbnailUrl} alt={friendlyTitle} className="mt-3 w-full rounded-lg object-cover" />
              </a>
            ) : (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={thumbnailUrl} alt={friendlyTitle} className="mt-3 w-full rounded-lg object-cover" />
            )
          ) : sourceAssetUrl && isPdfAsset ? (
            <a
              href={sourceAssetUrl}
              target="_blank"
              rel="noreferrer"
              className="mt-3 inline-flex rounded-lg border border-[#d6e3f2] bg-white px-3 py-2 text-sm font-semibold text-[#2663AC]"
            >
              Open PDF
            </a>
          ) : (
            <div className="mt-3 rounded-lg border border-slate-200 bg-slate-50 p-6 text-sm text-slate-500">
              No thumbnail uploaded.
            </div>
          )}
          {metadata?.notes ? (
            <div className="mt-3 rounded-lg border border-slate-200 bg-slate-50 p-3 text-sm text-slate-600">
              {metadata.notes}
            </div>
          ) : null}
        </Card>
      </section>
    </div>
  );
}
