"use client";

import { Target, ArrowDown, Users, Eye, FileText, TrendingUp, Phone, MessageSquare, Activity } from "lucide-react";
import type { LucideIcon } from "lucide-react";

// ─── Types ──────────────────────────────────────────────────────────────────

interface TrafficData {
  pageViews: number;
  sessions: number;
  pagesPerSession: number;
}

interface ConvSummary {
  totalConversions: number;
  byType: Record<string, number>;
  conversionRate: number;
  topConvertingPages: Array<{ url: string; conversions: number }>;
}

interface EventTrend {
  hour: number;
  count: number;
}

export interface FunnelTabProps {
  traffic: TrafficData | null;
  conversions: ConvSummary | null;
  trends: EventTrend[];
  hasTag: boolean;
}

// ─── Per-type styling for the parallel-paths branching row ──────────────────

const PATH_STYLE: Record<string, { icon: LucideIcon; color: string; bg: string }> = {
  form_submit: { icon: FileText, color: "text-rose-700", bg: "bg-rose-50 border-rose-200" },
  form_start: { icon: FileText, color: "text-amber-700", bg: "bg-amber-50 border-amber-200" },
  form_filled: { icon: FileText, color: "text-orange-700", bg: "bg-orange-50 border-orange-200" },
  phone_number_click: { icon: Phone, color: "text-violet-700", bg: "bg-violet-50 border-violet-200" },
  click_to_call: { icon: Phone, color: "text-fuchsia-700", bg: "bg-fuchsia-50 border-fuchsia-200" },
  sms_submit: { icon: MessageSquare, color: "text-cyan-700", bg: "bg-cyan-50 border-cyan-200" },
};

function pathStyleFor(type: string): { icon: LucideIcon; color: string; bg: string } {
  return PATH_STYLE[type] ?? { icon: Activity, color: "text-slate-700", bg: "bg-slate-50 border-slate-200" };
}

function formatTypeLabel(type: string): string {
  return type
    .replace(/_/g, " ")
    .replace(/\b\w/g, (c) => c.toUpperCase());
}

// ─── Funnel Tab ─────────────────────────────────────────────────────────────

export function FunnelTab({ traffic, conversions, hasTag }: FunnelTabProps) {
  if (!hasTag || !traffic) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
        <Target className="w-10 h-10 text-slate-200 mx-auto mb-3" />
        <h2 className="text-lg font-bold text-slate-900 mb-1">Conversion Funnel</h2>
        <p className="text-sm text-slate-500 max-w-sm mx-auto">
          Install the meSEO Site Tag to see your conversion funnel. The tag tracks sessions,
          page views, form interactions, and conversions to build your funnel automatically.
        </p>
      </div>
    );
  }

  const sessions = traffic.sessions;
  const pageViews = traffic.pageViews;
  const totalConversions = conversions?.totalConversions ?? 0;

  // All non-zero conversion types become branches between Page Views and the
  // Total Conversions merge step. Sorted descending so the biggest path
  // renders leftmost — matches the user's expectation that the primary
  // conversion action is the most visible one.
  const paths = Object.entries(conversions?.byType ?? {})
    .filter(([, count]) => count > 0)
    .sort((a, b) => b[1] - a[1])
    .map(([type, count]) => ({ type, count, ...pathStyleFor(type) }));

  // The Page Views row's "drop-off" to the conversion step uses the sum of
  // all branches, not an arbitrary single type like form_submit.
  const totalBranchCount = paths.reduce((s, p) => s + p.count, 0) || totalConversions;

  const pagesPerSession = sessions > 0 ? pageViews / sessions : 0;
  const convRate = sessions > 0 ? (totalConversions / sessions) * 100 : 0;

  return (
    <div className="space-y-6">

      {/* Funnel visual */}
      <div className="bg-white rounded-xl border border-slate-200 p-6">
        <div className="flex items-center gap-2 mb-6">
          <Target className="w-4 h-4 text-brand-600" />
          <h2 className="font-bold text-slate-800 text-sm">Conversion Funnel</h2>
        </div>

        <div className="flex flex-col items-center gap-2">
          {/* Step 1: Sessions */}
          <FunnelCard
            label="Sessions"
            value={sessions}
            icon={Users}
            color="text-blue-700"
            bg="bg-blue-50 border-blue-200"
            widthPct={100}
          />

          {/* Arrow from Sessions → Page Views */}
          <ArrowDown className="w-4 h-4 text-slate-300 my-1.5" />

          {/* Step 2: Page Views.
              Engagement depth, not a drop-off — pages-per-session can easily
              exceed 1.0, so showing "108.4%" as a rate was misleading. Swap
              the metric label to Pages/Session. */}
          <FunnelCard
            label="Page Views"
            value={pageViews}
            icon={Eye}
            color="text-indigo-700"
            bg="bg-indigo-50 border-indigo-200"
            widthPct={88}
            side={{ label: "Pages/Session", value: pagesPerSession.toFixed(2) }}
          />

          {/* Arrow + aggregate drop-off into the conversion branches */}
          {paths.length > 0 && pageViews > 0 && (
            <div className="flex items-center gap-2 py-1.5">
              <ArrowDown className="w-4 h-4 text-slate-300" />
              <span className="text-[11px] font-semibold text-red-500">
                -{Math.round((1 - totalBranchCount / pageViews) * 100)}% drop-off
              </span>
            </div>
          )}

          {/* Parallel conversion branches + deduped summary */}
          {paths.length > 0 && (
            <div className="w-full flex flex-col lg:flex-row gap-3 py-1">
              {/* Conversion type cards */}
              <div className="flex flex-wrap gap-3 flex-1">
                {paths.map((p) => {
                  const rate = sessions > 0 ? (p.count / sessions) * 100 : 0;
                  const Icon = p.icon;
                  return (
                    <div
                      key={p.type}
                      className={`border rounded-xl px-4 py-3 flex items-center gap-3 min-w-[200px] flex-1 ${p.bg}`}
                    >
                      <Icon className={`w-5 h-5 shrink-0 ${p.color}`} />
                      <div className="flex-1 min-w-0">
                        <p className={`text-[11px] font-semibold uppercase tracking-wide truncate ${p.color}`}>
                          {formatTypeLabel(p.type)}
                        </p>
                        <p className="text-xl font-bold text-slate-900 tabular-nums">{p.count.toLocaleString()}</p>
                      </div>
                      <div className="text-right shrink-0">
                        <p className="text-[10px] text-slate-500">Rate</p>
                        <p className="text-xs font-bold text-slate-900 tabular-nums">{rate.toFixed(1)}%</p>
                      </div>
                    </div>
                  );
                })}
              </div>

              {/* Deduped total — summary card, not a funnel step */}
              <div className="border-2 border-dashed border-blue-300 rounded-xl bg-blue-50/50 px-5 py-4 min-w-[200px] lg:max-w-[220px] flex flex-col justify-center">
                <p className="text-[10px] font-bold uppercase tracking-widest text-blue-500 mb-1">Total (Deduped)</p>
                <p className="text-2xl font-bold text-blue-700 tabular-nums">{totalConversions.toLocaleString()}</p>
                <p className="text-xs font-semibold text-blue-600 mt-1">{convRate.toFixed(2)}% conv. rate</p>
                <p className="text-[10px] text-slate-400 mt-1.5">After 30-second dedup resolver</p>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Conversion breakdown by type */}
      {conversions && Object.keys(conversions.byType).length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <TrendingUp className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Conversion Breakdown</h3>
          </div>
          <div className="divide-y divide-slate-100">
            {Object.entries(conversions.byType).map(([type, count]) => {
              const pct = sessions > 0 ? ((count / sessions) * 100).toFixed(2) : "0";
              return (
                <div key={type} className="px-5 py-3 flex items-center gap-4">
                  <span className="text-sm font-semibold text-slate-800 flex-1 capitalize">
                    {type.replace(/_/g, " ")}
                  </span>
                  <span className="text-sm font-bold text-slate-900 tabular-nums">{count}</span>
                  <span className="text-xs text-slate-400 tabular-nums w-16 text-right">{pct}%</span>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Top converting pages in funnel context */}
      {conversions && conversions.topConvertingPages.length > 0 && (
        <div className="bg-white rounded-xl border border-slate-200 overflow-hidden">
          <div className="px-5 py-3.5 border-b border-slate-100 flex items-center gap-2">
            <Target className="w-4 h-4 text-brand-600" />
            <h3 className="font-bold text-slate-800 text-sm">Highest-Converting Pages</h3>
          </div>
          <div className="divide-y divide-slate-100">
            {conversions.topConvertingPages.slice(0, 5).map((p) => (
              <div key={p.url} className="px-5 py-3 flex items-center gap-4">
                <span className="text-sm font-mono text-brand-600 truncate flex-1">{p.url}</span>
                <span className="text-sm font-bold text-slate-900 tabular-nums">{p.conversions} conv.</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Internal card for a single funnel step ─────────────────────────────────

/**
 * Single stepped card used for Sessions / Page Views / Total Conversions.
 * The `side` prop lets the caller render its own contextual metric next to
 * the value — Pages/Session for the page-views row, Conversion Rate for
 * the total-conversions row — which replaces the old "Rate: X%" column
 * that was hard-coded to "current / previous" and misrepresented both.
 */
function FunnelCard({
  label,
  value,
  icon: Icon,
  color,
  bg,
  widthPct,
  side,
}: {
  label: string;
  value: number;
  icon: LucideIcon;
  color: string;
  bg: string;
  widthPct: number;
  side?: { label: string; value: string };
}) {
  return (
    <div
      className={`border rounded-xl px-5 py-4 flex items-center gap-4 transition-all ${bg}`}
      style={{ width: `${Math.max(widthPct, 20)}%`, minWidth: "280px" }}
    >
      <Icon className={`w-5 h-5 shrink-0 ${color}`} />
      <div className="flex-1 min-w-0">
        <p className={`text-xs font-semibold uppercase tracking-wide ${color}`}>{label}</p>
        <p className="text-2xl font-bold text-slate-900 tabular-nums">{value.toLocaleString()}</p>
      </div>
      {side && (
        <div className="text-right">
          <p className="text-xs text-slate-500">{side.label}</p>
          <p className="text-sm font-bold text-slate-900 tabular-nums">{side.value}</p>
        </div>
      )}
    </div>
  );
}
