import React, { useState, useMemo, useCallback } from 'react';

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

import Section from './Section';
import ChartCanvas from './ChartCanvas';
import EmptyState from './EmptyState';
import ErrorBanner from './ErrorBanner';
import { ChartSkeleton } from './CardSkeleton';
import { formatNumber, formatPercentage } from './helpers';
import InfoTooltip from './InfoTooltip';
import {
  BAR_CHART_OPTIONS,
  DOUGHNUT_CHART_OPTIONS,
  LINE_CHART_OPTIONS,
  LINE_CHART_OPTIONS_NO_LEGEND,
  PRODUCT_SORT_KEYS,
  getDefaultProductPerformance,
  getDefaultIntentSentiment,
  getDefaultChatbotPerformance,
  getDefaultCompetitiveIntel,
  getDefaultEngagementPatterns,
  buildCategoryDistributionChartData,
  buildIntentDistributionChartData,
  buildSentimentBreakdownChartData,
  buildOutcomeDistributionChartData,
  buildSentimentTrendChartData,
  buildSatisfactionTrendChartData,
  buildPeakHoursChartData,
  buildLanguageDistributionChartData,
} from './analyticsTab.utils';

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

type SortDirection = 'ascending' | 'descending';

const PRODUCTS_PAGE_SIZE = 10;

const SortIcon = ({
  direction,
  active,
}: {
  direction: SortDirection;
  active: boolean;
}) => (
  <span
    className={`ml-1 inline-block ${active ? 'text-gray-900' : 'text-gray-400'}`}
  >
    {direction === 'ascending' ? '\u2191' : '\u2193'}
  </span>
);

const AnalyticsTab = ({
  data,
  loading,
  error,
  onRetry,
}: AnalyticsTabProps): JSX.Element => {
  const [sortIndex, setSortIndex] = useState(0);
  const [sortDirection, setSortDirection] =
    useState<SortDirection>('descending');
  const [visibleProductsCount, setVisibleProductsCount] =
    useState(PRODUCTS_PAGE_SIZE);
  const currencySymbol = recomaze_ai_personalization_env?.currency || 'USD';

  const handleSort = useCallback(
    (headingIndex: number) => {
      if (sortIndex === headingIndex) {
        setSortDirection(d => (d === 'ascending' ? 'descending' : 'ascending'));
      } else {
        setSortIndex(headingIndex);
        setSortDirection('descending');
      }
      setVisibleProductsCount(PRODUCTS_PAGE_SIZE);
    },
    [sortIndex]
  );

  if (loading) {
    return (
      <div className="space-y-6">
        <ChartSkeleton />
        <ChartSkeleton />
        <ChartSkeleton />
      </div>
    );
  }
  if (error) return <ErrorBanner message={error} onRetry={onRetry} />;
  if (!data) return <EmptyState />;

  const pp = data.product_performance || getDefaultProductPerformance();
  const is_ = data.intent_sentiment || getDefaultIntentSentiment();
  const cp = data.chatbot_performance || getDefaultChatbotPerformance();
  const ci = data.competitive_intel || getDefaultCompetitiveIntel();
  const ep = data.engagement_patterns || getDefaultEngagementPatterns();

  const sortedProducts = useMemo(() => {
    const sorted = [...(pp.top_products || [])];
    const key = PRODUCT_SORT_KEYS[sortIndex];
    if (!key) return sorted;
    sorted.sort((a, b) => {
      const va = (a[key] as number) ?? 0;
      const vb = (b[key] as number) ?? 0;
      return sortDirection === 'ascending' ? va - vb : vb - va;
    });
    return sorted;
  }, [pp.top_products, sortIndex, sortDirection]);

  const visibleProducts = sortedProducts.slice(0, visibleProductsCount);
  const remainingProducts = sortedProducts.length - visibleProducts.length;

  const catData = buildCategoryDistributionChartData(
    pp.category_distribution || {}
  );
  const intentData = buildIntentDistributionChartData(
    is_.intent_distribution || {}
  );
  const sentData = buildSentimentBreakdownChartData(
    is_.sentiment_breakdown || { positive: 0, neutral: 0, negative: 0 }
  );
  const outcomeData = buildOutcomeDistributionChartData(
    is_.outcome_distribution || {}
  );
  const sentTrendData = buildSentimentTrendChartData(is_.sentiment_trend || []);
  const satData = buildSatisfactionTrendChartData(cp.satisfaction_trend || []);
  const peakData = buildPeakHoursChartData(ep.peak_hours || {});
  const langData = buildLanguageDistributionChartData(
    ep.language_distribution || {}
  );

  const tableHeadings = [
    'Recommended',
    'Clicked',
    'Added to cart',
    'Click Rate',
    'Cart Rate',
  ];

  return (
    <div className="space-y-6">
      {/* Product Performance */}
      <Section
        title="Product Performance"
        tooltip="How each recommended product performs in terms of clicks and add-to-cart actions"
      >
        {sortedProducts.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-2 px-3 font-medium text-gray-600">
                    Product
                  </th>
                  {tableHeadings.map((h, i) => (
                    <th
                      key={h}
                      className="text-right py-2 px-3 font-medium text-gray-600 cursor-pointer select-none hover:text-gray-900"
                      onClick={() => handleSort(i)}
                    >
                      {h}
                      <SortIcon
                        direction={sortDirection}
                        active={sortIndex === i}
                      />
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {visibleProducts.map(p => (
                  <tr
                    key={p.name || p.sku}
                    className="border-b border-gray-100 hover:bg-gray-50"
                  >
                    <td className="py-2 px-3">
                      <span className="font-semibold text-gray-900">
                        {p.name || p.sku}
                      </span>
                      {p.price > 0 && (
                        <span className="block text-xs text-gray-500">
                          {`${currencySymbol} ${formatNumber(p.price, 2)}`}
                        </span>
                      )}
                    </td>
                    <td className="text-right py-2 px-3">
                      {formatNumber(p.times_recommended)}
                    </td>
                    <td className="text-right py-2 px-3">
                      {formatNumber(p.times_clicked)}
                    </td>
                    <td className="text-right py-2 px-3">
                      {formatNumber(p.times_carted)}
                    </td>
                    <td className="text-right py-2 px-3">
                      {formatPercentage(p.click_rate)}
                    </td>
                    <td className="text-right py-2 px-3">
                      {formatPercentage(p.cart_rate)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
            {remainingProducts > 0 && (
              <div className="mt-4 flex items-center justify-center gap-3">
                <span className="text-xs text-gray-500">
                  Showing {visibleProducts.length} of {sortedProducts.length}
                </span>
                <button
                  type="button"
                  onClick={() =>
                    setVisibleProductsCount(c => c + PRODUCTS_PAGE_SIZE)
                  }
                  className="text-sm font-medium text-gray-700 border border-gray-300 rounded-md px-3 py-1.5 hover:bg-gray-50"
                >
                  Load more
                </button>
                {sortedProducts.length > PRODUCTS_PAGE_SIZE * 2 && (
                  <button
                    type="button"
                    onClick={() =>
                      setVisibleProductsCount(sortedProducts.length)
                    }
                    className="text-sm font-medium text-gray-600 hover:text-gray-900"
                  >
                    Show all
                  </button>
                )}
              </div>
            )}
            {visibleProducts.length > PRODUCTS_PAGE_SIZE &&
              remainingProducts === 0 && (
                <div className="mt-4 flex items-center justify-center">
                  <button
                    type="button"
                    onClick={() => setVisibleProductsCount(PRODUCTS_PAGE_SIZE)}
                    className="text-sm font-medium text-gray-600 hover:text-gray-900"
                  >
                    Show less
                  </button>
                </div>
              )}
          </div>
        ) : (
          <EmptyState message="No product data" />
        )}
      </Section>

      {/* Missing Products + Category Distribution */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Section
          title="Missing Products (Catalog Gaps)"
          tooltip="Products users asked about that are not in your catalog."
        >
          {(pp.missing_products || []).length > 0 ? (
            <div className="flex flex-col gap-2">
              {pp.missing_products.map((m, i) => (
                <div key={i} className="flex items-center justify-between">
                  <span className="text-sm text-gray-700">{m.name}</span>
                  <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-yellow-100 text-yellow-800">
                    {m.times_requested}x requested
                  </span>
                </div>
              ))}
            </div>
          ) : (
            <EmptyState message="No missing products detected" />
          )}
        </Section>
        <Section
          title="Category Distribution"
          tooltip="Breakdown of product categories recommended by the agent"
        >
          {catData ? (
            <ChartCanvas
              type="doughnut"
              data={catData}
              options={DOUGHNUT_CHART_OPTIONS}
              height={220}
            />
          ) : (
            <EmptyState message="No category data" />
          )}
        </Section>
      </div>

      {/* Intent & Sentiment */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Section
          title="Intent Distribution"
          tooltip="Classification of user purchase intent levels across conversations"
        >
          {intentData ? (
            <ChartCanvas
              type="bar"
              data={intentData}
              options={BAR_CHART_OPTIONS}
              height={220}
            />
          ) : (
            <EmptyState message="No intent data" />
          )}
        </Section>
        <Section
          title="Sentiment Breakdown"
          tooltip="Overall emotional tone of user messages: positive, neutral, or negative"
        >
          {sentData ? (
            <ChartCanvas
              type="doughnut"
              data={sentData}
              options={DOUGHNUT_CHART_OPTIONS}
              height={220}
            />
          ) : (
            <EmptyState message="No sentiment data" />
          )}
        </Section>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Section
          title="Outcome Distribution"
          tooltip="How conversations ended: converted, abandoned, or other outcomes"
        >
          {outcomeData ? (
            <ChartCanvas
              type="bar"
              data={outcomeData}
              options={BAR_CHART_OPTIONS}
              height={220}
            />
          ) : (
            <EmptyState message="No outcome data" />
          )}
        </Section>
        <Section
          title="Sentiment Trend"
          tooltip="How user sentiment evolves over time across all conversations"
        >
          {sentTrendData ? (
            <ChartCanvas
              type="line"
              data={sentTrendData}
              options={LINE_CHART_OPTIONS}
              height={220}
            />
          ) : (
            <EmptyState message="No sentiment trend" />
          )}
        </Section>
      </div>

      {/* Chatbot Performance */}
      <Section
        title="Chatbot Performance"
        tooltip="Agent satisfaction trends, most asked questions, and user pain points"
      >
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <div>
            <p className="text-sm text-gray-500">Satisfaction Trend</p>
            <div className="mt-2">
              {satData ? (
                <ChartCanvas
                  type="line"
                  data={satData}
                  options={LINE_CHART_OPTIONS_NO_LEGEND}
                  height={180}
                />
              ) : (
                <EmptyState message="No trend data" />
              )}
            </div>
          </div>
          <div>
            <p className="text-sm text-gray-500">Common Questions</p>
            <div className="mt-2">
              {(cp.common_questions || []).length > 0 ? (
                <div className="flex flex-col gap-1">
                  {cp.common_questions.map((q, i) => (
                    <div key={i} className="flex items-center justify-between">
                      <span className="text-sm text-gray-700 truncate mr-2">
                        {q.question}
                      </span>
                      <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-gray-100 text-gray-700 flex-shrink-0">
                        {q.count}x
                      </span>
                    </div>
                  ))}
                </div>
              ) : (
                <EmptyState message="No questions data" />
              )}
            </div>
          </div>
          <div>
            <p className="text-sm text-gray-500">Pain Points</p>
            <div className="mt-2">
              {(cp.common_pain_points || []).length > 0 ? (
                <div className="flex flex-col gap-1">
                  {cp.common_pain_points.map((p, i) => (
                    <div key={i} className="flex items-center justify-between">
                      <span className="text-sm text-gray-700 truncate mr-2">
                        {p.issue}
                      </span>
                      <span className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-red-100 text-red-800 flex-shrink-0">
                        {p.count}x
                      </span>
                    </div>
                  ))}
                </div>
              ) : (
                <EmptyState message="No pain points detected" />
              )}
            </div>
          </div>
        </div>
      </Section>

      {/* Competitive Intelligence */}
      <Section
        title={`Competitive Intelligence (${ci.total_mentions || 0} mentions)`}
        tooltip="Competitor brands mentioned by users during conversations"
      >
        {(ci.competitors || []).length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-gray-200">
                  <th className="text-left py-2 px-3 font-medium text-gray-600">
                    Competitor
                  </th>
                  <th className="text-right py-2 px-3 font-medium text-gray-600">
                    Mentions
                  </th>
                  <th className="text-left py-2 px-3 font-medium text-gray-600">
                    Contexts
                  </th>
                </tr>
              </thead>
              <tbody>
                {ci.competitors.map(c => (
                  <tr key={c.name} className="border-b border-gray-100">
                    <td className="py-2 px-3 text-gray-900">{c.name}</td>
                    <td className="text-right py-2 px-3">{c.mention_count}</td>
                    <td className="py-2 px-3">
                      <div className="flex flex-wrap gap-1">
                        {(c.contexts || []).slice(0, 3).map((ctx, j) => (
                          <span
                            key={j}
                            className="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium bg-gray-100 text-gray-700"
                          >
                            {ctx}
                          </span>
                        ))}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <EmptyState message="No competitor mentions" />
        )}
      </Section>

      {/* Engagement Patterns */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <Section
          title="Peak Hours"
          tooltip="Hours of the day with the most conversation activity"
        >
          {peakData ? (
            <ChartCanvas
              type="bar"
              data={peakData}
              options={BAR_CHART_OPTIONS}
              height={220}
            />
          ) : (
            <EmptyState message="No peak hours data" />
          )}
        </Section>
        <Section
          title="Language Distribution"
          tooltip="Languages used by visitors when chatting with the agent"
        >
          {langData ? (
            <ChartCanvas
              type="doughnut"
              data={langData}
              options={DOUGHNUT_CHART_OPTIONS}
              height={220}
            />
          ) : (
            <EmptyState message="No language data" />
          )}
        </Section>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Section>
          <p className="text-sm text-gray-500">
            Avg User Message
            <InfoTooltip text="Average character length of messages sent by users" />
          </p>
          <p className="text-base font-bold text-gray-900">
            {formatNumber(ep.avg_user_message_length, 0)}{' '}
            <span className="text-sm font-normal">chars</span>
          </p>
        </Section>
        <Section>
          <p className="text-sm text-gray-500">
            Avg AI Response
            <InfoTooltip text="Average character length of AI agent responses" />
          </p>
          <p className="text-base font-bold text-gray-900">
            {formatNumber(ep.avg_ai_response_length, 0)}{' '}
            <span className="text-sm font-normal">chars</span>
          </p>
        </Section>
        <Section>
          <p className="text-sm text-gray-500">
            With Products
            <InfoTooltip text="Conversations where the agent showed product recommendations" />
          </p>
          <p className="text-base font-bold text-gray-900">
            {formatNumber(ep.conversations_with_products)}
          </p>
        </Section>
        <Section>
          <p className="text-sm text-gray-500">
            Product Engagement
            <InfoTooltip text="Percentage of conversations where users interacted with shown products" />
          </p>
          <p className="text-base font-bold text-gray-900">
            {formatPercentage(ep.product_engagement_rate)}
          </p>
        </Section>
      </div>
    </div>
  );
};

export default AnalyticsTab;
