import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { useSearchParams } from 'react-router-dom';

import OverviewTab from '../components/agent-analytics/OverviewTab';
import AnalyticsTab from '../components/agent-analytics/AnalyticsTab';
import ConversationsTab from '../components/agent-analytics/ConversationsTab';
import GapsTab from '../components/agent-analytics/GapsTab';
import InsightsTab from '../components/agent-analytics/InsightsTab';
import LiveSyncBanner from '../components/agent-analytics/LiveSyncBanner';
import PlanStatusCard from '../components/PlanStatusCard';
import {
  fetchAgentDashboard,
  fetchAiInsights,
} from '../service/agent-analytics/agent-analytics.service';
import { getDateRangeFromPreset } from '../components/agent-analytics/helpers';
import type {
  IAgentDashboardData,
  IInsightsResponse,
  IInsight,
} from '../service/agent-analytics/agent-analytics.interface';

type Tab = {
  id: string;
  label: string;
  badge?: string;
};

const DATE_PRESETS = [
  { id: 'today', label: 'Today' },
  { id: '7d', label: '7 Days' },
  { id: '30d', label: '30 Days' },
  { id: 'custom', label: 'Custom' },
] as const;

const VALID_TABS = [
  'overview',
  'analytics',
  'conversations',
  'gaps',
  'insights',
] as const;

const AgentAnalytics = (): JSX.Element => {
  const [searchParams, setSearchParams] = useSearchParams();
  const tabParam = searchParams.get('tab');
  const initialTab =
    tabParam && (VALID_TABS as readonly string[]).includes(tabParam)
      ? tabParam
      : 'overview';

  const [selectedTab, setSelectedTab] = useState(initialTab);
  const [datePreset, setDatePreset] = useState('30d');
  const [customStart, setCustomStart] = useState('');
  const [customEnd, setCustomEnd] = useState('');
  const [showCustom, setShowCustom] = useState(false);

  const [insightCount, setInsightCount] = useState(0);

  const [dashData, setDashData] = useState<IAgentDashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const dateRange = useMemo(() => {
    if (datePreset === 'custom' && customStart && customEnd) {
      return { start: customStart, end: customEnd };
    }
    return getDateRangeFromPreset(datePreset);
  }, [datePreset, customStart, customEnd]);

  const fetchDashboard = useCallback(() => {
    setLoading(true);
    setError(null);
    fetchAgentDashboard(dateRange.start, dateRange.end)
      .then(d => {
        setDashData(d);
        setLoading(false);
      })
      .catch(e => {
        setError(e.message);
        setLoading(false);
      });
  }, [dateRange.start, dateRange.end]);

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

  useEffect(() => {
    if (tabParam && (VALID_TABS as readonly string[]).includes(tabParam)) {
      setSelectedTab(tabParam);
    }
  }, [tabParam]);

  const handleSelectTab = useCallback(
    (tabId: string): void => {
      setSelectedTab(tabId);
      setSearchParams(
        prev => {
          const next = new URLSearchParams(prev);
          next.set('tab', tabId);
          return next;
        },
        { replace: true }
      );
    },
    [setSearchParams]
  );

  const tabs: Tab[] = useMemo(
    () => [
      { id: 'overview', label: 'Overview' },
      { id: 'analytics', label: 'Analytics' },
      { id: 'conversations', label: 'Conversations' },
      { id: 'gaps', label: 'Gaps' },
      {
        id: 'insights',
        label: 'Insights',
        badge: insightCount > 0 ? String(insightCount) : undefined,
      },
    ],
    [insightCount]
  );

  useEffect(() => {
    fetchAiInsights()
      .then((data: IInsightsResponse | null) => {
        const activeInsights: IInsight[] = (
          data?.report?.insights || []
        ).filter((insight: IInsight) => !insight.dismissed);
        setInsightCount(activeInsights.length);
      })
      .catch(() => {});
  }, []);

  return (
    <div className="mx-auto w-full max-w-[1600px] bg-white p-6 md:p-10">
      <header className="mb-8 flex flex-col gap-6 md:flex-row md:items-start md:justify-between">
        <div>
          <h1 className="text-xl font-medium tracking-tight text-gray-900 md:text-2xl">
            Agent Analytics
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            Monitor your AI agent{`'`}s performance, conversations, and impact.
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          {showCustom && (
            <div className="flex items-center gap-2 rounded-lg border border-gray-200 bg-white p-1 shadow-sm">
              <input
                type="date"
                value={customStart}
                onChange={e => setCustomStart(e.target.value)}
                className="w-[130px] rounded-md border-0 py-1.5 text-xs text-gray-900 ring-1 ring-inset ring-gray-200 focus:ring-2 focus:ring-inset focus:ring-gray-900"
              />
              <span className="text-xs text-gray-400">to</span>
              <input
                type="date"
                value={customEnd}
                onChange={e => setCustomEnd(e.target.value)}
                className="w-[130px] rounded-md border-0 py-1.5 text-xs text-gray-900 ring-1 ring-inset ring-gray-200 focus:ring-2 focus:ring-inset focus:ring-gray-900"
              />
            </div>
          )}

          <div className="flex items-center gap-1 rounded-lg border border-gray-200 bg-gray-50 p-1 shadow-sm">
            {DATE_PRESETS.map(p => (
              <button
                key={p.id}
                onClick={() => {
                  setDatePreset(p.id);
                  setShowCustom(p.id === 'custom');
                }}
                className={`rounded-md px-3 py-1.5 text-xs font-medium transition-all ${
                  datePreset === p.id
                    ? 'bg-white text-gray-900 shadow-sm ring-1 ring-black/5'
                    : 'text-gray-500 hover:text-gray-900'
                }`}
              >
                {p.label}
              </button>
            ))}
          </div>

          <button
            onClick={fetchDashboard}
            disabled={loading}
            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border border-gray-200 bg-white text-gray-500 shadow-sm transition-colors hover:bg-gray-50 hover:text-gray-900 disabled:cursor-not-allowed disabled:opacity-50"
            title="Refresh Analytics"
          >
            <svg
              className={`h-4 w-4 ${loading ? 'animate-spin text-gray-900' : ''}`}
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth="2"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"
              />
            </svg>
          </button>
        </div>
      </header>

      <div className="mb-6">
        <PlanStatusCard />
      </div>

      <div className="mb-6">
        <LiveSyncBanner />
      </div>

      <div className="mb-6 border-b border-gray-200">
        <nav className="-mb-px flex space-x-8" aria-label="Tabs">
          {tabs.map(tab => (
            <button
              key={tab.id}
              onClick={() => handleSelectTab(tab.id)}
              className={`whitespace-nowrap border-b-2 py-3 text-sm font-medium transition-colors ${
                selectedTab === tab.id
                  ? 'border-gray-900 text-gray-900'
                  : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'
              }`}
            >
              {tab.label}
              {tab.badge && (
                <span className="ml-1.5 inline-flex items-center rounded-full bg-pink-100 px-2 py-0.5 text-xs font-medium text-pink-700">
                  {tab.badge}
                </span>
              )}
            </button>
          ))}
        </nav>
      </div>

      <div className="mt-6">
        {selectedTab === 'overview' && (
          <OverviewTab
            data={dashData}
            loading={loading}
            error={error}
            onRetry={fetchDashboard}
          />
        )}
        {selectedTab === 'analytics' && (
          <AnalyticsTab
            data={dashData}
            loading={loading}
            error={error}
            onRetry={fetchDashboard}
          />
        )}
        {selectedTab === 'conversations' && (
          <ConversationsTab dateRange={dateRange} />
        )}
        {selectedTab === 'gaps' && (
          <GapsTab startDate={dateRange.start} endDate={dateRange.end} />
        )}
        {selectedTab === 'insights' && (
          <InsightsTab onInsightCountChange={setInsightCount} />
        )}
      </div>
    </div>
  );
};

export default AgentAnalytics;
