import React from 'react';

import type { IAgentDashboardData } from '../../service/agent-analytics/agent-analytics.interface';

import KPICard from './KPICard';
import Section from './Section';
import HBar from './HBar';
import ChartCanvas from './ChartCanvas';
import EmptyState from './EmptyState';
import ErrorBanner from './ErrorBanner';
import { CardSkeleton, ChartSkeleton } from './CardSkeleton';
import { formatNumber, formatPercentage, RECOMAZE_COLORS } from './helpers';
import InfoTooltip from './InfoTooltip';
import {
  OVERVIEW_LINE_CHART_OPTIONS,
  buildDailyConversationsChartData,
} from './overviewTab.utils';

// Native SVG Icons to replace react-icons
const IconChat = ({ className = '' }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <path
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M8.625 12a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H8.25m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0H12m4.125 0a.375.375 0 11-.75 0 .375.375 0 01.75 0zm0 0h-.375M21 12c0 4.556-4.03 8.25-9 8.25a9.764 9.764 0 01-2.555-.337A5.972 5.972 0 015.41 20.97a5.969 5.969 0 01-.474-.065 4.48 4.48 0 00.978-2.025c.09-.457-.133-.901-.467-1.226C3.93 16.178 3 14.189 3 12c0-4.556 4.03-8.25 9-8.25s9 3.694 9 8.25z"
    />
  </svg>
);

const IconUsers = ({ className = '' }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <path
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M15 19.128a9.38 9.38 0 002.625.372 9.337 9.337 0 004.121-.952 4.125 4.125 0 00-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 018.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0111.964-3.07M12 6.375a3.375 3.375 0 11-6.75 0 3.375 3.375 0 016.75 0zm8.25 2.25a2.625 2.625 0 11-5.25 0 2.625 2.625 0 015.25 0z"
    />
  </svg>
);

const IconPercent = ({ className = '' }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <path
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M9 14.25L15 8.25M10.5 8.25h.008v.008H10.5V8.25zm3.75 6h.008v.008h-.008V14.25z"
    />
  </svg>
);

const IconThumbUp = ({ className = '' }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <path
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M14.25 15.446c1.16-1.02 2.375-2.072 2.658-3.327a3.002 3.002 0 00-1.921-3.551 2.978 2.978 0 00-1.897-.042l-.24.084a4.5 4.5 0 01-2.922 0l-.24-.084A3.003 3.003 0 005.127 12.08c.284 1.255 1.5 2.307 2.66 3.327a2.977 2.977 0 01.996 2.345v1.5a3 3 0 003 3h.034a3 3 0 003-3v-1.5a2.977 2.977 0 01.995-2.345h.438zM19.5 21v-3.75m0 0v-3.75m0 3.75h-3.75M19.5 17.25h3.75"
    />
  </svg>
);

const IconCursorClick = ({ className = '' }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <path
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"
    />
  </svg>
);

const IconCart = ({ className = '' }) => (
  <svg
    className={className}
    fill="none"
    viewBox="0 0 24 24"
    strokeWidth="1.5"
    stroke="currentColor"
  >
    <path
      strokeLinecap="round"
      strokeLinejoin="round"
      d="M2.25 3h1.386c.51 0 .955.343 1.087.835l.383 1.437M7.5 14.25a3 3 0 00-3 3h15.75m-12.75-3h11.218c1.121-2.3 2.1-4.684 2.924-7.138a60.114 60.114 0 00-16.536-1.84M7.5 14.25L5.106 5.272M6 20.25a.75.75 0 11-1.5 0 .75.75 0 011.5 0zm12.75 0a.75.75 0 11-1.5 0 .75.75 0 011.5 0z"
    />
  </svg>
);

interface OverviewTabProps {
  data: IAgentDashboardData | null;
  loading: boolean;
  error: string | null;
  onRetry: () => void;
}

const OverviewTab = ({
  data,
  loading,
  error,
  onRetry,
}: OverviewTabProps): JSX.Element => {
  if (loading) {
    return (
      <div className="space-y-6">
        <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-6">
          {Array.from({ length: 6 }).map((_, i) => (
            <CardSkeleton key={i} />
          ))}
        </div>
        <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
          <ChartSkeleton />
          <ChartSkeleton />
        </div>
      </div>
    );
  }

  if (error) return <ErrorBanner message={error} onRetry={onRetry} />;
  if (!data || !data.overview) return <EmptyState />;

  const o = data.overview;
  const t = data.overview_trends || {};
  const f = data.funnel || ({} as IAgentDashboardData['funnel']);
  const pf = f.product_funnel || {
    products_shown: 0,
    products_clicked: 0,
    products_carted: 0,
  };
  const ep =
    data.engagement_patterns ||
    ({} as IAgentDashboardData['engagement_patterns']);

  const dailyData = ep.daily_conversations || [];
  const lineData = buildDailyConversationsChartData(dailyData);

  const funnelMax = Math.max(f.total_conversations || 0, 1);
  const pfMax = Math.max(pf.products_shown || 0, 1);

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-6">
        <KPICard
          icon={IconChat}
          label="Conversations"
          value={formatNumber(o.total_conversations)}
          trend={t.total_conversations}
          tooltip="Total chat conversations started by visitors in the selected period"
        />
        <KPICard
          icon={IconUsers}
          label="Unique Visitors"
          value={formatNumber(o.unique_visitors)}
          trend={t.unique_visitors}
          tooltip="Distinct users who interacted with the AI agent"
        />
        <KPICard
          icon={IconPercent}
          label="Conversion Rate"
          value={formatPercentage(o.real_conversion_rate)}
          trend={t.real_conversion_rate}
          tooltip="Percentage of conversations that led to a purchase"
        />
        <KPICard
          icon={IconThumbUp}
          label="Satisfaction"
          value={formatPercentage(o.satisfaction_rate)}
          trend={t.satisfaction_rate}
          tooltip="Likes divided by total feedback votes (likes + dislikes) on agent messages. Only counts users who actually rated, so a few votes can swing it. Open Conversations to see which replies were thumbs-downed."
        />
        <KPICard
          icon={IconCursorClick}
          label="Product Clicks"
          value={formatNumber(o.product_clicks)}
          trend={t.product_clicks}
          tooltip="Number of product recommendations clicked by users"
        />
        <KPICard
          icon={IconCart}
          label="Add to Cart"
          value={formatNumber(o.add_to_cart_count)}
          trend={t.add_to_cart_count}
          tooltip="Products added to cart directly from agent recommendations"
        />
      </div>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        <Section
          title="Daily Conversations"
          tooltip="Number of conversations started each day"
        >
          {lineData ? (
            <div className="h-[300px] w-full">
              <ChartCanvas
                type="line"
                data={lineData}
                options={OVERVIEW_LINE_CHART_OPTIONS}
              />
            </div>
          ) : (
            <EmptyState message="No daily data available for this period." />
          )}
        </Section>

        <Section
          title="Conversion Funnel"
          tooltip="How users progress through conversation stages from discovery to purchase intent"
        >
          <div className="space-y-4">
            <HBar
              label="Discovery"
              value={f.reached_discovery || 0}
              max={funnelMax}
              color={RECOMAZE_COLORS.primary}
            />
            <HBar
              label="Consideration"
              value={f.reached_consideration || 0}
              max={funnelMax}
              color={RECOMAZE_COLORS.accent1}
            />
            <HBar
              label="Ready to Buy"
              value={f.reached_ready || 0}
              max={funnelMax}
              color={RECOMAZE_COLORS.dark}
            />
          </div>

          <div className="mt-6 border-t border-gray-100 pt-6">
            <h3 className="mb-4 text-sm font-medium text-gray-900">
              Product Funnel
            </h3>
            <div className="space-y-4">
              <HBar
                label="Shown"
                value={pf.products_shown || 0}
                max={pfMax}
                color="#6366f1"
              />
              <HBar
                label="Clicked"
                value={pf.products_clicked || 0}
                max={pfMax}
                color="#8b5cf6"
              />
              <HBar
                label="Added to Cart"
                value={pf.products_carted || 0}
                max={pfMax}
                color="#a855f7"
              />
            </div>
          </div>
        </Section>
      </div>

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <Section>
          <div className="flex items-center gap-1.5 text-xs font-medium text-gray-500">
            Avg Messages/Conv
            <InfoTooltip text="Average number of messages exchanged per conversation" />
          </div>
          <p className="mt-2 text-2xl font-semibold text-gray-900">
            {formatNumber(o.avg_messages_per_conversation, 1)}
          </p>
        </Section>
        <Section>
          <div className="flex items-center gap-1.5 text-xs font-medium text-gray-500">
            Avg Duration
            <InfoTooltip text="Average time a conversation lasts from first to last message" />
          </div>
          <p className="mt-2 text-2xl font-semibold text-gray-900">
            {formatNumber(o.avg_duration_minutes, 1)}{' '}
            <span className="text-base font-normal text-gray-500">min</span>
          </p>
        </Section>
        <Section>
          <div className="flex items-center gap-1.5 text-xs font-medium text-gray-500">
            High Intent Conv.
            <InfoTooltip text="Conversations where the user showed strong purchase intent" />
          </div>
          <p className="mt-2 text-2xl font-semibold text-gray-900">
            {formatNumber(o.high_intent_conversations)}
          </p>
          <p className="mt-0.5 text-xs text-gray-500">
            {formatPercentage(o.high_intent_rate)} of total
          </p>
        </Section>
        <Section>
          <div className="flex items-center gap-1.5 text-xs font-medium text-gray-500">
            Returning Rate
            <InfoTooltip text="Percentage of current-period visitors who also chatted with you in the previous 90 days. Starts at 0% on a new shop and grows naturally as customers return." />
          </div>
          <p className="mt-2 text-2xl font-semibold text-gray-900">
            {formatPercentage(o.returning_rate)}
          </p>
          <p className="mt-0.5 text-xs text-gray-500">
            {formatNumber(o.returning_visitors)} returning
          </p>
        </Section>
      </div>
    </div>
  );
};

export default OverviewTab;
