"use client";

import { useState, useEffect, useCallback } from "react";
import { useBrand } from "@/context/brand-context";
import {
  BarChart3, Loader2, ChevronRight, X, TrendingUp, TrendingDown,
  Search, Globe, Mail, Monitor, Users, MapPin, Bot, Tv, Link2, Minus,
} from "lucide-react";

interface ChannelRow {
  channel: string;
  count: number;
  delta: number;
  prevCount: number;
}

const CHANNEL_META: Record<string, { label: string; color: string; icon: typeof Search }> = {
  organic_search: { label: "Organic Search", color: "#10b981", icon: Search },
  paid_search:    { label: "Paid Search",    color: "#ef4444", icon: Monitor },
  paid_social:    { label: "Paid Social",    color: "#f43f5e", icon: Users },
  organic_social: { label: "Organic Social", color: "#3b82f6", icon: Users },
  email:          { label: "Email",          color: "#8b5cf6", icon: Mail },
  referral:       { label: "Referral",       color: "#f59e0b", icon: Link2 },
  direct:         { label: "Direct",         color: "#94a3b8", icon: Globe },
  display:        { label: "Display",        color: "#ec4899", icon: Monitor },
  affiliate:      { label: "Affiliate",      color: "#14b8a6", icon: Link2 },
  local_maps:     { label: "Local / Maps",   color: "#f97316", icon: MapPin },
  ai_assistant:   { label: "AI Assistant",   color: "#6366f1", icon: Bot },
  video:          { label: "Video",          color: "#e11d48", icon: Tv },
  internal:       { label: "Internal",       color: "#cbd5e1", icon: Minus },
  other:          { label: "Other",          color: "#9ca3af", icon: Minus },
};

export default function ConversionsBySource({ range = "28d" }: { range?: string }) {
  const { brand } = useBrand();
  const [data, setData] = useState<{ channels: ChannelRow[]; total: number } | null>(null);
  const [loading, setLoading] = useState(true);
  const [drilldown, setDrilldown] = useState<string | null>(null);

  const load = useCallback(async () => {
    if (!brand?.id) return;
    setLoading(true);
    try {
      const res = await fetch(`/api/dashboard/channel-breakdown?brandId=${brand.id}&range=${range}`);
      if (res.ok) setData(await res.json());
    } catch { /* silent */ }
    setLoading(false);
  }, [brand?.id, range]);

  useEffect(() => { load(); }, [load]);

  if (loading) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-5">
        <div className="flex items-center gap-2 mb-4">
          <BarChart3 className="w-4 h-4 text-brand-600" />
          <h3 className="text-sm font-bold text-slate-800">Conversions by Source</h3>
        </div>
        <div className="flex items-center justify-center py-8">
          <Loader2 className="w-5 h-5 text-brand-500 animate-spin" />
        </div>
      </div>
    );
  }

  if (!data || data.channels.length === 0) {
    return (
      <div className="bg-white rounded-xl border border-slate-200 p-5">
        <div className="flex items-center gap-2 mb-3">
          <BarChart3 className="w-4 h-4 text-brand-600" />
          <h3 className="text-sm font-bold text-slate-800">Conversions by Source</h3>
        </div>
        <p className="text-xs text-slate-400 text-center py-4">No classified conversions in this period.</p>
      </div>
    );
  }

  const maxCount = Math.max(...data.channels.map((c) => c.count), 1);

  return (
    <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 justify-between">
        <div className="flex items-center gap-2">
          <BarChart3 className="w-4 h-4 text-brand-600" />
          <h3 className="text-sm font-bold text-slate-800">Conversions by Source</h3>
        </div>
        <span className="text-[10px] text-slate-400 uppercase tracking-widest font-semibold">
          Site Tag · {range} · First-touch
        </span>
      </div>

      <div className="divide-y divide-slate-50">
        {data.channels.map((ch) => {
          const meta = CHANNEL_META[ch.channel] ?? CHANNEL_META.other;
          const Icon = meta.icon;
          const pct = data.total > 0 ? Math.round((ch.count / data.total) * 100) : 0;
          const barWidth = Math.max((ch.count / maxCount) * 100, 2);

          return (
            <button
              key={ch.channel}
              onClick={() => setDrilldown(ch.channel)}
              className="w-full flex items-center gap-3 px-5 py-2.5 hover:bg-slate-50 text-left group"
            >
              <Icon className="w-3.5 h-3.5 shrink-0" style={{ color: meta.color }} />
              <span className="text-xs font-semibold text-slate-700 w-28 shrink-0 truncate">{meta.label}</span>
              <div className="flex-1 bg-slate-100 rounded-full h-4 overflow-hidden">
                <div className="h-full rounded-full" style={{ width: `${barWidth}%`, backgroundColor: meta.color }} />
              </div>
              <span className="text-xs font-bold text-slate-900 tabular-nums w-12 text-right">{ch.count.toLocaleString()}</span>
              <span className="text-[10px] text-slate-400 tabular-nums w-10 text-right">{pct}%</span>
              {ch.delta !== 0 && (
                <span className={`text-[10px] font-semibold w-12 text-right ${ch.delta > 0 ? "text-emerald-600" : "text-red-500"}`}>
                  {ch.delta > 0 ? "+" : ""}{ch.delta}%
                </span>
              )}
              <ChevronRight className="w-3 h-3 text-slate-300 opacity-0 group-hover:opacity-100 shrink-0" />
            </button>
          );
        })}
      </div>

      <div className="px-5 py-2 border-t border-slate-100 flex items-center justify-between">
        <span className="text-[10px] text-slate-400">Total: {data.total.toLocaleString()} conversions</span>
        <span className="text-[10px] text-slate-400">
          {data.channels.find((c) => c.channel === "other")
            ? `Other: ${Math.round(((data.channels.find((c) => c.channel === "other")?.count ?? 0) / data.total) * 100)}%`
            : "Other: 0%"}
        </span>
      </div>

      {/* Drill-down drawer */}
      {drilldown && (
        <div className="fixed inset-0 z-50 flex justify-end">
          <div className="absolute inset-0 bg-black/30" onClick={() => setDrilldown(null)} />
          <div className="relative w-full max-w-md bg-white shadow-xl overflow-y-auto">
            <div className="sticky top-0 bg-white border-b border-slate-200 px-5 py-3 flex items-center justify-between z-10">
              <div>
                <h3 className="text-sm font-bold text-slate-900">
                  {CHANNEL_META[drilldown]?.label ?? drilldown}
                </h3>
                <p className="text-xs text-slate-500">
                  {data.channels.find((c) => c.channel === drilldown)?.count.toLocaleString() ?? 0} conversions
                </p>
              </div>
              <button onClick={() => setDrilldown(null)} className="p-1.5 hover:bg-slate-100 rounded-lg">
                <X className="w-4 h-4 text-slate-400" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <ChannelDrilldown brandId={brand?.id ?? ""} channel={drilldown} range={range} />
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

function ChannelDrilldown({ brandId, channel, range }: { brandId: string; channel: string; range: string }) {
  const [data, setData] = useState<{ sources: Array<{ source: string; count: number }>; pages: Array<{ page: string; count: number }>; types: Array<{ type: string; count: number }> } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!brandId || !channel) return;
    fetch(`/api/dashboard/channel-drilldown?brandId=${brandId}&channel=${channel}&range=${range}`)
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setData(d))
      .catch(() => null)
      .finally(() => setLoading(false));
  }, [brandId, channel, range]);

  if (loading) return <div className="flex justify-center py-8"><Loader2 className="w-4 h-4 text-brand-500 animate-spin" /></div>;
  if (!data) return <p className="text-xs text-slate-400">No drill-down data available.</p>;

  return (
    <>
      {data.sources.length > 0 && (
        <div>
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Top Sources</p>
          <div className="space-y-1">
            {data.sources.slice(0, 15).map((s) => (
              <div key={s.source} className="flex items-center justify-between text-xs py-1">
                <span className="text-slate-700 truncate flex-1 mr-2">{s.source || "(empty)"}</span>
                <span className="text-slate-900 font-bold tabular-nums">{s.count}</span>
              </div>
            ))}
          </div>
        </div>
      )}
      {data.pages.length > 0 && (
        <div>
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Top Landing Pages</p>
          <div className="space-y-1">
            {data.pages.slice(0, 10).map((p) => (
              <div key={p.page} className="flex items-center justify-between text-xs py-1">
                <span className="text-slate-600 font-mono truncate flex-1 mr-2">{p.page}</span>
                <span className="text-slate-900 font-bold tabular-nums">{p.count}</span>
              </div>
            ))}
          </div>
        </div>
      )}
      {data.types.length > 0 && (
        <div>
          <p className="text-[10px] font-bold uppercase tracking-widest text-slate-400 mb-2">Conversion Types</p>
          <div className="space-y-1">
            {data.types.map((t) => (
              <div key={t.type} className="flex items-center justify-between text-xs py-1">
                <span className="text-slate-700">{t.type}</span>
                <span className="text-slate-900 font-bold tabular-nums">{t.count}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </>
  );
}
