"use client";

import { Card } from "@/components/ui/card";
import { formatCountryLabel } from "@/lib/countries";
import { formatInteger } from "@/lib/utils";

type Summary = {
  totalRows: number;
  totalCalls: number;
  callsWithPresentation: number;
  callsWithoutPresentation: number;
  mixedCalls: number;
  uniquePresentations: number;
  uniqueKeyMessages: number;
  inferredCountries: number;
};

type TopCountry = {
  code: string;
  label: string;
  count: number;
};

type TopProduct = {
  label: string;
  count: number;
  uniqueCalls?: number;
  callsWithPresentation?: number;
  callsWithoutPresentation?: number;
  uniquePresentations?: number;
};

type TopPresentation = {
  label: string;
  count: number;
  uniqueCalls: number;
  keyMessageCount: number;
  topProduct: string;
};

type ProductDeckLeader = {
  product: string;
  presentation: string;
  count: number;
  uniqueCalls: number;
};

type DeckSlides = {
  presentation: string;
  product: string;
  uniqueCalls: number;
  totalRecords: number;
  averageRecordsPerCall: number;
  keyMessageCount: number;
  keyMessages: string[];
};

export function ClmSnapshot({
  summary,
  topCountries,
  topProducts,
  topPresentations,
  topKeyMessages,
  productDeckLeaders,
  deckSlides,
  activePresentation,
  onPresentationSelect,
}: {
  summary: Summary;
  topCountries: TopCountry[];
  topProducts: TopProduct[];
  topPresentations: TopPresentation[];
  topKeyMessages: TopProduct[];
  productDeckLeaders: ProductDeckLeader[];
  deckSlides: DeckSlides[];
  activePresentation?: string;
  onPresentationSelect?: (presentation: string) => void;
}) {
  const totalDeckRecords = deckSlides.reduce((sum, row) => sum + row.totalRecords, 0);
  const totalDeckCalls = deckSlides.reduce((sum, row) => sum + row.uniqueCalls, 0);
  const averageRecordsPerCallOverall = totalDeckCalls > 0 ? totalDeckRecords / totalDeckCalls : 0;
  const isActivePresentation = (presentation: string) => activePresentation === presentation;

  return (
    <details
      open
      className="enter-fade-up group rounded-3xl border border-[#d8e4f3] bg-white/92 p-4 shadow-[0_22px_40px_-30px_rgba(38,99,172,0.56)]"
      style={{ ["--enter-delay" as string]: "200ms" }}
    >
      <summary className="flex cursor-pointer list-none items-center justify-between rounded-2xl border border-[#dce8f6] bg-[linear-gradient(120deg,#f2f8ff_0%,#eaf2fd_100%)] px-4 py-3.5 text-sm font-semibold text-slate-900 shadow-[inset_0_1px_0_rgba(255,255,255,0.8)] transition hover:border-[#c5d9ef] hover:bg-[linear-gradient(120deg,#edf6ff_0%,#e3eefb_100%)]">
        CLM Activity Snapshot
        <span className="flex h-7 w-7 items-center justify-center rounded-full bg-[#edf4ff] text-[#2663AC] transition-transform duration-200 group-open:rotate-180">
          <svg viewBox="0 0 20 20" className="h-4 w-4 fill-current" aria-hidden="true">
            <path d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 11.12l3.71-3.9a.75.75 0 1 1 1.08 1.04l-4.25 4.47a.75.75 0 0 1-1.08 0L5.21 8.27a.75.75 0 0 1 .02-1.06Z" />
          </svg>
        </span>
      </summary>

      <div className="mt-4 space-y-4">
        <div className="grid gap-3 2xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]">
          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Most Used Deck By Product</h3>
            </div>
            <div className="divide-y divide-[#e2ebf7]">
              {productDeckLeaders.length > 0 ? (
                productDeckLeaders.map((row) => (
                  <div key={`${row.product}-${row.presentation}`} className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
                    <div className="min-w-0">
                      <p className="font-medium text-slate-800">{row.product}</p>
                      <button
                        type="button"
                        onClick={() => onPresentationSelect?.(row.presentation)}
                        className={
                          isActivePresentation(row.presentation)
                            ? "truncate text-left text-xs font-semibold text-[#2663AC] underline"
                            : "truncate text-left text-xs text-slate-500 hover:text-[#2663AC] hover:underline"
                        }
                      >
                        {row.presentation}
                      </button>
                    </div>
                    <div className="shrink-0 text-right">
                      <p className="font-semibold text-[#2663AC]">{formatInteger(row.uniqueCalls)} calls</p>
                      <p className="text-xs text-slate-500">{formatInteger(row.count)} records</p>
                    </div>
                  </div>
                ))
              ) : (
                <div className="px-4 py-5 text-sm text-slate-500">No product deck leaders in this filter range.</div>
              )}
            </div>
          </Card>

          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Call Mix</h3>
            </div>
            <div className="divide-y divide-[#edf3fa] px-4 py-2">
              {[
                { label: "Using CLM", note: "CLM content presented during call", value: summary.callsWithPresentation, tone: "bg-[#fff4e8] text-[#d9852c]" },
                { label: "Without CLM", note: "May include phone/email or non-promotional — not filtered in this export", value: summary.callsWithoutPresentation, tone: "bg-[#eef5ff] text-[#2663AC]" },
                { label: "Mixed", note: "Call has both CLM and non-CLM records", value: summary.mixedCalls, tone: "bg-[#f3f4f6] text-slate-700" },
              ].map((row) => (
                <div key={row.label} className="py-3">
                  <div className="flex items-center justify-between gap-3">
                    <p className="text-sm font-semibold text-slate-800">{row.label}</p>
                    <span className={`rounded-full px-2.5 py-0.5 text-sm font-semibold ${row.tone}`}>
                      {formatInteger(row.value)}
                    </span>
                  </div>
                  <p className="mt-0.5 text-xs leading-relaxed text-slate-400">{row.note}</p>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <Card className="overflow-hidden p-0">
          <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#dbe7f5] px-4 py-3">
            <div>
              <h3 className="text-sm font-semibold text-slate-900">Deck Activity</h3>
              <p className="text-xs text-slate-500">Deck = presentation. Technical `CMT...` IDs are hidden; average records per call is shown instead.</p>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              {activePresentation ? (
                <span className="rounded-full border border-[#d7e3f1] bg-[#f7fbff] px-2.5 py-1 text-xs font-semibold text-[#2663AC]">
                  {activePresentation}
                </span>
              ) : null}
              <span className="rounded-full bg-[#fff4e8] px-2.5 py-1 text-xs font-semibold text-[#d9852c]">
                {averageRecordsPerCallOverall.toFixed(1)} avg records/call overall
              </span>
              <span className="rounded-full bg-[#eef5ff] px-2 py-0.5 text-xs font-semibold text-[#2663AC]">
                {formatInteger(deckSlides.length)} decks
              </span>
            </div>
          </div>
          <div className="divide-y divide-[#e2ebf7]">
            {deckSlides.length > 0 ? (
              deckSlides.map((row) => (
                <div key={row.presentation} className="px-4 py-3">
                  <div className="flex flex-wrap items-start justify-between gap-3">
                    <div className="min-w-0">
                      <button
                        type="button"
                        onClick={() => onPresentationSelect?.(row.presentation)}
                        className={
                          isActivePresentation(row.presentation)
                            ? "break-words text-left font-semibold text-[#2663AC] underline"
                            : "break-words text-left font-medium text-slate-800 hover:text-[#2663AC] hover:underline"
                        }
                      >
                        {row.presentation}
                      </button>
                      <div className="mt-1 flex flex-wrap gap-2 text-xs text-slate-500">
                        <span>{row.product || "Unspecified product"}</span>
                        <span>{formatInteger(row.uniqueCalls)} calls</span>
                        <span>{row.averageRecordsPerCall.toFixed(1)} avg records/call</span>
                        <span>{formatInteger(row.totalRecords)} total records</span>
                        {row.keyMessageCount > 0 ? <span>{formatInteger(row.keyMessageCount)} named key messages</span> : null}
                      </div>
                    </div>
                  </div>
                  <div className="mt-3 flex flex-wrap gap-2">
                    {row.keyMessages.length > 0 ? (
                      row.keyMessages.map((message) => (
                        <span
                          key={`${row.presentation}-${message}`}
                          className="inline-flex rounded-full border border-[#d7e3f1] bg-[#f7fbff] px-2.5 py-1 text-xs text-slate-700"
                        >
                          {message}
                        </span>
                      ))
                    ) : (
                      <span className="text-xs text-slate-500">No human-readable key messages available</span>
                    )}
                  </div>
                </div>
              ))
            ) : (
              <div className="px-4 py-5 text-sm text-slate-500">No deck activity in this filter range.</div>
            )}
          </div>
        </Card>

        <div className="grid gap-3 xl:grid-cols-2 2xl:grid-cols-4">
          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Top Countries</h3>
            </div>
            <div className="divide-y divide-[#e2ebf7]">
              {topCountries.length > 0 ? (
                topCountries.slice(0, 6).map((row) => (
                  <div key={row.code} className="flex items-center justify-between px-4 py-3 text-sm">
                    <div>
                      <p className="font-medium text-slate-800">
                        {row.code ? formatCountryLabel(row.code) : row.label}
                      </p>
                      <p className="text-xs text-slate-500">{row.code || "Unspecified"}</p>
                    </div>
                    <span className="rounded-full bg-[#eef5ff] px-2 py-0.5 font-semibold text-[#2663AC]">
                      {formatInteger(row.count)}
                    </span>
                  </div>
                ))
              ) : (
                <div className="px-4 py-5 text-sm text-slate-500">No CLM country activity in this filter range.</div>
              )}
            </div>
          </Card>

          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Top Products</h3>
            </div>
            <div className="divide-y divide-[#e2ebf7]">
              {topProducts.length > 0 ? (
                topProducts.slice(0, 6).map((row) => (
                  <div key={row.label} className="flex items-center justify-between px-4 py-3 text-sm">
                    <div>
                      <button
                        type="button"
                        onClick={() => onPresentationSelect?.(row.label)}
                        className="text-left font-medium text-slate-800 hover:text-[#2663AC] hover:underline"
                      >
                        {row.label}
                      </button>
                      <p className="text-xs text-slate-500">
                        {formatInteger(row.uniqueCalls ?? 0)} calls, {formatInteger(row.uniquePresentations ?? 0)} decks
                      </p>
                    </div>
                    <span className="rounded-full bg-[#fff4e8] px-2 py-0.5 font-semibold text-[#d9852c]">
                      {formatInteger(row.callsWithPresentation ?? row.count)}
                    </span>
                  </div>
                ))
              ) : (
                <div className="px-4 py-5 text-sm text-slate-500">No CLM product activity in this filter range.</div>
              )}
            </div>
          </Card>

          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Top Presentations</h3>
            </div>
            <div className="divide-y divide-[#e2ebf7]">
              {topPresentations.length > 0 ? (
                topPresentations.slice(0, 6).map((row) => (
                  <div key={row.label} className="flex items-center justify-between px-4 py-3 text-sm">
                    <div>
                      <p className="font-medium text-slate-800">{row.label}</p>
                      <p className="text-xs text-slate-500">
                        {formatInteger(row.uniqueCalls)} calls, top product {row.topProduct || "N/A"}
                      </p>
                    </div>
                    <span className="rounded-full bg-[#eef5ff] px-2 py-0.5 font-semibold text-[#2663AC]">
                      {formatInteger(row.count)}
                    </span>
                  </div>
                ))
              ) : (
                <div className="px-4 py-5 text-sm text-slate-500">No CLM presentation activity in this filter range.</div>
              )}
            </div>
          </Card>

          <Card className="overflow-hidden p-0">
            <div className="border-b border-[#dbe7f5] px-4 py-3">
              <h3 className="text-sm font-semibold text-slate-900">Top Key Messages</h3>
            </div>
            <div className="divide-y divide-[#e2ebf7]">
              {topKeyMessages.length > 0 ? (
                topKeyMessages.slice(0, 6).map((row) => (
                  <div key={row.label} className="flex items-center justify-between px-4 py-3 text-sm">
                    <button
                      type="button"
                      onClick={() => onPresentationSelect?.(row.label)}
                      className={
                        isActivePresentation(row.label)
                          ? "text-left font-semibold text-[#2663AC] underline"
                          : "text-left font-medium text-slate-800 hover:text-[#2663AC] hover:underline"
                      }
                    >
                      {row.label}
                    </button>
                    <span className="rounded-full bg-[#fff4e8] px-2 py-0.5 font-semibold text-[#d9852c]">
                      {formatInteger(row.count)}
                    </span>
                  </div>
                ))
              ) : (
                <div className="px-4 py-5 text-sm text-slate-500">No CLM key message activity in this filter range.</div>
              )}
            </div>
          </Card>
        </div>
      </div>
    </details>
  );
}
