/* global wp */
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useLicense } from '../../contexts/LicenseContext';
import NotificationsFeed from '../../components/NotificationsFeed';
import OverviewTab from './OverviewTab';
import QuickSetupWizard from './QuickSetupWizard';
import ModuleManagerTab from './ModuleManagerTab';
import ProrankHeader from '../../components/ProrankHeader';
import ProrankDivider from '../../components/ProrankDivider';
import ModuleNav from '../../components/ModuleNav';
import headerBadges from '../../utils/headerBadges';
import * as React from 'react';

// TypeScript interfaces
interface DashboardStats {
  seo_score?: number;
  published_pages?: number; // Local count from wp_count_posts()
  indexed_pages?: number; // GSC data (premium only, future)
  issues_count?: number;
  redirects_count?: number;
  seo_score_trend?: number | null;
  indexed_pages_trend?: number | null;
  issues_count_trend?: number | null;
  redirects_count_trend?: number | null;
  audit?: {
    id?: string;
    score?: number;
    state?: string;
    last_run?: string | null;
    source?: 'local' | 'cloud'; // 'cloud' = premium external audit
    issues?: {
      critical?: number;
      high?: number;
      medium?: number;
      low?: number;
      total?: number;
    };
    history?: Array<{
      id?: string;
      score?: number;
      completed_at?: string | null;
      issues_total?: number | null;
    }>;
    // Cloud audit extras (premium only)
    cloud?: {
      pages_crawled?: number;
      crawl_depth?: number;
      lighthouse_scores?: {
        performance?: number;
        accessibility?: number;
        best_practices?: number;
        seo?: number;
      };
      credits_used?: number;
      credits_remaining?: number;
    };
  };
  performance?: {
    cache?: Record<string, any>;
    assets?: Record<string, any>;
    images?: Record<string, any>;
    database?: Record<string, any>;
    rum?: Record<string, any>;
  };
  // Premium-only analytics (future)
  analytics?: {
    gsc?: {
      clicks?: number;
      impressions?: number;
      avg_position?: number;
      top_queries?: Array<{ query: string; clicks: number; impressions: number }>;
    };
    ga?: {
      sessions?: number;
      pageviews?: number;
      bounce_rate?: number;
    };
    rank_tracking?: {
      keywords_tracked?: number;
      avg_position?: number;
      positions_up?: number;
      positions_down?: number;
    };
  };
  [key: string]: any;
}

interface Tab {
  name: string;
  title: string;
  tier: 'free' | 'pro' | 'enterprise';
}

const Dashboard: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [activeTab, setActiveTab] = useState<string>(() => {
    const params = new URLSearchParams(window.location.search);
    return params.get('tab') || 'overview';
  });
  const [notificationCount, setNotificationCount] = useState<number>(0);
  const { currentTier } = useLicense();

  // Callback to receive notification count from NotificationsFeed
  const handleNotificationCountChange = useCallback((count: number) => {
    setNotificationCount(count);
  }, []);

  useEffect(() => {
    document.title =
      __('Dashboard', 'prorank-seo') + ' \u2039 ' + __('ProRank SEO', 'prorank-seo') + ' \u2014 WordPress';
    loadDashboardData();
  }, []);

  const loadDashboardData = async (forceRefresh: boolean = false): Promise<void> => {
    setLoading(true);
    try {
      // Load dashboard statistics from REST API
      const path = forceRefresh
        ? '/prorank-seo/v1/dashboard/stats?refresh=1'
        : '/prorank-seo/v1/dashboard/stats';
      const response = await (window as any).wp.apiFetch({
        path,
      }) as any;
      const payload = (response && typeof response === 'object' && 'data' in response) ? (response as any).data : response;
      setStats(payload);
    } catch (error) {
      // Show error state instead of fallback data
      setStats(null);
    } finally {
      setLoading(false);
    }
  };

  const tabs: Tab[] = [
    {
      name: 'overview',
      title: __('Overview', 'prorank-seo'),
      tier: 'free',
    },
    {
      name: 'module-manager',
      title: __('Module Manager', 'prorank-seo'),
      tier: 'free',
    },
    {
      name: 'quick-setup',
      title: __('Quick Setup', 'prorank-seo'),
      tier: 'free',
    },
    {
      name: 'notifications',
      title: __('Notifications', 'prorank-seo'),
      tier: 'free',
    },
  ];

  const renderTabContent = (): JSX.Element | null => {
    switch (activeTab) {
      case 'overview':
        return <OverviewTab stats={stats} onRefresh={() => loadDashboardData(true)} />;
      case 'module-manager':
        return <ModuleManagerTab />;
      case 'quick-setup':
        return <QuickSetupWizard />;
      case 'notifications':
        return (
          <div className="prorank-dashboard-notifications">
            <NotificationsFeed maxItems={20} onCountChange={handleNotificationCountChange} />
          </div>
        );
      default:
        return null;
    }
  };

  if (loading && !stats) {
    return (
      <div className="prorank-dashboard-loading">
        <div className="prorank-spinner" />
        <p>{__('Loading dashboard\u2026', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="prorank-page">
      <ProrankHeader
        title={__('Dashboard', 'prorank-seo')}
        subtitle={__('Monitor your SEO performance and manage your optimization tasks', 'prorank-seo')}
        badges={headerBadges.dashboard}
      />

      <div className="prorank-content">
        <ModuleNav
          modules={tabs.map((tab) => ({
            id: tab.name,
            label: tab.title,
            count: tab.name === 'notifications' && notificationCount > 0
              ? (notificationCount > 99 ? '99+' : String(notificationCount))
              : undefined,
          }))}
          activeModule={activeTab}
          onModuleChange={setActiveTab}
        />

        <ProrankDivider />

        <div className="pr:mt-6">{renderTabContent()}</div>
      </div>
    </div>
  );
};

export default Dashboard;
