import { Link } from 'react-router-dom';
import React, { useEffect, useState } from 'react';
import type { IconType } from 'react-icons';
import {
  FaArrowDown,
  FaArrowRight,
  FaArrowUp,
  FaChartLine,
  FaMousePointer,
  FaPercent,
  FaRegCommentDots,
  FaRegThumbsUp,
  FaShoppingCart,
  FaUsers,
} from 'react-icons/fa';

import {
  formatNumber,
  formatPercentage,
  getDateRangeFromPreset,
} from '../agent-analytics/helpers';
import type {
  IAgentDashboardData,
  IAgentOverview,
  IAgentOverviewTrends,
} from '../../service/agent-analytics/agent-analytics.interface';
import { fetchAgentDashboard } from '../../service/agent-analytics/agent-analytics.service';

import InfoTooltip from './InfoTooltip';

interface CardMeta {
  key: keyof IAgentOverview & keyof IAgentOverviewTrends;
  label: string;
  icon: IconType;
  format: 'number' | 'percent';
  tooltip: string;
  iconClass: string;
  chipClass: string;
}

const CARD_META: CardMeta[] = [
  {
    key: 'total_conversations',
    label: 'Conversations',
    icon: FaRegCommentDots,
    format: 'number',
    tooltip: 'Total chat conversations started by visitors in the last 7 days.',
    iconClass: 'text-pink-500',
    chipClass: 'bg-pink-50 ring-pink-100',
  },
  {
    key: 'unique_visitors',
    label: 'Unique Visitors',
    icon: FaUsers,
    format: 'number',
    tooltip: 'Distinct users who interacted with the AI agent.',
    iconClass: 'text-sky-500',
    chipClass: 'bg-sky-50 ring-sky-100',
  },
  {
    key: 'real_conversion_rate',
    label: 'Conversion Rate',
    icon: FaPercent,
    format: 'percent',
    tooltip: 'Share of conversations that led to a purchase.',
    iconClass: 'text-emerald-500',
    chipClass: 'bg-emerald-50 ring-emerald-100',
  },
  {
    key: 'satisfaction_rate',
    label: 'Satisfaction',
    icon: FaRegThumbsUp,
    format: 'percent',
    tooltip:
      'Likes divided by total feedback votes on agent messages. A handful of votes can swing it.',
    iconClass: 'text-amber-500',
    chipClass: 'bg-amber-50 ring-amber-100',
  },
  {
    key: 'product_clicks',
    label: 'Product Clicks',
    icon: FaMousePointer,
    format: 'number',
    tooltip: 'Number of product recommendations clicked by users.',
    iconClass: 'text-violet-500',
    chipClass: 'bg-violet-50 ring-violet-100',
  },
  {
    key: 'add_to_cart_count',
    label: 'Add to Cart',
    icon: FaShoppingCart,
    format: 'number',
    tooltip: 'Products added to cart directly from agent recommendations.',
    iconClass: 'text-fuchsia-500',
    chipClass: 'bg-fuchsia-50 ring-fuchsia-100',
  },
];

/**
 * Last-7-day at-a-glance stat cards for the dashboard. Fetches the agent
 * dashboard client-side (same service the Agent Analytics tab uses).
 *
 * @param {object} props - Component props.
 * @param {string} props.token - Recomaze JWT.
 * @return {React.ReactElement} The stat-card section.
 */
export function OverviewStatCards({ token }: { token: string }) {
  const [data, setData] = useState<IAgentDashboardData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!token) return;
    let cancelled = false;
    const range = getDateRangeFromPreset('7d');
    setLoading(true);
    void (async () => {
      try {
        const dashboard = await fetchAgentDashboard(range.start, range.end);
        if (!cancelled) setData(dashboard);
      } catch {
        // Benign: the store may have no agent analytics yet.
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [token]);

  const overview = data?.overview ?? null;
  const trends = data?.overview_trends ?? {};

  return (
    <section>
      <div className="mb-4 flex flex-wrap items-end justify-between gap-3">
        <div className="flex items-center gap-2.5">
          <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-pink-50 ring-1 ring-pink-100">
            <FaChartLine className="h-4 w-4 text-[#B7007C]" />
          </span>
          <div>
            <h2 className="text-base font-semibold text-gray-900">
              Performance at a glance
            </h2>
            <p className="mt-0.5 inline-flex items-center gap-1.5 text-xs text-gray-500">
              <span className="relative flex h-1.5 w-1.5">
                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400/70" />
                <span className="relative inline-flex h-1.5 w-1.5 rounded-full bg-emerald-400" />
              </span>
              Last 7 days · vs the previous 7
            </p>
          </div>
        </div>
        <Link
          to="/agent-analytics"
          className="group inline-flex items-center gap-1 rounded-full border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-gray-600 transition-colors hover:border-[#B7007C]/30 hover:text-[#B7007C]"
        >
          View analytics
          <FaArrowRight className="h-3 w-3 transition-transform group-hover:translate-x-0.5" />
        </Link>
      </div>

      <div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-6">
        {CARD_META.map(meta => (
          <StatCard
            key={meta.key}
            meta={meta}
            overview={overview}
            delta={trends[meta.key]?.delta_pct ?? null}
            loading={loading && !data}
          />
        ))}
      </div>
    </section>
  );
}

function StatCard({
  meta,
  overview,
  delta,
  loading,
}: {
  meta: CardMeta;
  overview: IAgentOverview | null;
  delta: number | null;
  loading: boolean;
}) {
  const Icon = meta.icon;
  const raw = overview ? overview[meta.key] : 0;
  const value =
    meta.format === 'percent' ? formatPercentage(raw) : formatNumber(raw);

  return (
    <div className="rounded-2xl border border-gray-200 bg-white p-4 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-sm">
      <div className="flex items-start justify-between gap-2">
        <span
          className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-xl ring-1 ${meta.chipClass}`}
        >
          <Icon className={`h-4 w-4 ${meta.iconClass}`} />
        </span>
        {!loading && <DeltaBadge delta={delta} />}
      </div>

      <p className="mt-3.5 inline-flex items-center text-xs text-gray-500">
        {meta.label}
        <InfoTooltip text={meta.tooltip} />
      </p>
      {loading ? (
        <div className="mt-1.5 h-7 w-16 animate-pulse rounded-md bg-gray-100" />
      ) : (
        <p className="mt-0.5 text-2xl font-semibold tabular-nums tracking-tight text-gray-900">
          {value}
        </p>
      )}
    </div>
  );
}

function DeltaBadge({ delta }: { delta: number | null }) {
  if (delta == null || delta === 0) {
    return (
      <span className="inline-flex shrink-0 items-center rounded-full bg-gray-100 px-2 py-0.5 text-[11px] font-medium text-gray-500">
        --
      </span>
    );
  }

  const isUp = delta > 0;

  return (
    <span
      className={`inline-flex shrink-0 items-center gap-0.5 whitespace-nowrap rounded-full px-2 py-0.5 text-[11px] font-semibold tabular-nums ${
        isUp ? 'bg-emerald-50 text-emerald-600' : 'bg-red-50 text-red-600'
      }`}
    >
      {isUp ? (
        <FaArrowUp className="h-2.5 w-2.5" />
      ) : (
        <FaArrowDown className="h-2.5 w-2.5" />
      )}
      {isUp ? '+' : '-'}
      {Math.abs(delta).toFixed(1)}%
    </span>
  );
}
