/**
 * External dependencies.
 */
import { useState, useEffect } from '@wordpress/element';
import { useNavigate, useLocation } from 'react-router-dom';
import { FolderOpen, Users, FileText, Tag } from 'lucide-react';

/**
 * Internal dependencies.
 */
import SettingsLayout from '../layout/SettingsLayout';
import SyncStatusHero from '../dashboard/SyncStatusHero';
import StatCard from '../dashboard/StatCard';
import SyncPerformanceChart from '../dashboard/SyncPerformanceChart';
import ContentActivityChart from '../dashboard/ContentActivityChart';
import RecentSyncActivity from '../dashboard/RecentSyncActivity';
import QuickActions from '../dashboard/QuickActions';
import SystemHealth from '../dashboard/SystemHealth';
import HelpResources from '../dashboard/HelpResources';
import EmptyStateJustCompleted from '../dashboard/EmptyStateJustCompleted';
import EmptyStateNoSyncs from '../dashboard/EmptyStateNoSyncs';
import { useSyncData } from '../../context/SyncContext';
import { fetchDashboardStats } from '../../api/settings';

const Dashboard = () => {
	const navigate = useNavigate();
	const location = useLocation();
	const { syncData } = useSyncData();
	const [stats, setStats] = useState(null);
	const [loading, setLoading] = useState(true);

	// Check if credentials are set up - redirect to setup if not
	const checkCredentials = window.openAssetPluginState?.checkCredentials || false;
	useEffect(() => {
		if (!checkCredentials) {
			navigate('/setup');
		}
	}, [checkCredentials, navigate]);

	// Check for empty state conditions
	const urlParams = new URLSearchParams(location.search);
	const emptyStateParam = urlParams.get('emptyState'); // For testing
	const installCompleteFromUrl = urlParams.get('installComplete') === 'true'; // From Setup page

	// Persist installComplete in sessionStorage so it survives navigation (Setup → General Settings → Dashboard)
	const INSTALL_COMPLETE_KEY = 'openasset_just_completed_setup';
	useEffect(() => {
		if (installCompleteFromUrl) {
			sessionStorage.setItem(INSTALL_COMPLETE_KEY, 'true');
		}
	}, [installCompleteFromUrl]);
	const installComplete = installCompleteFromUrl || (typeof sessionStorage !== 'undefined' && sessionStorage.getItem(INSTALL_COMPLETE_KEY) === 'true');

	// Clear the flag when Dashboard unmounts (e.g. user navigates to General Settings)
	// So when they return, we show "No Syncs Yet" instead of "Just Completed Setup"
	useEffect(() => {
		return () => {
			sessionStorage.removeItem(INSTALL_COMPLETE_KEY);
		};
	}, []);

	// Fetch dashboard stats
	const loadDashboardStats = async () => {
		try {
			const data = await fetchDashboardStats();
			setStats(data);
		} catch (error) {
			if (typeof window !== 'undefined' && window.location?.search?.includes('debug=1')) {
				console.error('Error loading dashboard stats:', error);
			}
		} finally {
			setLoading(false);
		}
	};

	// Load on mount
	useEffect(() => {
		loadDashboardStats();
	}, []);

	// Refresh data handler
	const handleRefresh = async () => {
		setLoading(true);
		await loadDashboardStats();
	};

	const handleManualSync = () => {
		// TODO: Implement manual sync trigger
	};

	// Show empty states for testing via URL param (for development)
	if (emptyStateParam === 'justCompleted') {
		return (
			<SettingsLayout>
				<EmptyStateJustCompleted />
			</SettingsLayout>
		);
	}

	if (emptyStateParam === 'noSyncs') {
		return (
			<SettingsLayout>
				<EmptyStateNoSyncs />
			</SettingsLayout>
		);
	}

	// Real empty state logic
	if (!loading && stats) {
		// Scenario 1: Just completed setup
		if (installComplete) {
			return (
				<SettingsLayout>
					<EmptyStateJustCompleted />
				</SettingsLayout>
			);
		}

		// Scenario 2: No content yet (show onboarding - user needs to configure & run sync)
		// Show even if last_sync exists (e.g. sync ran with nothing enabled, or migration/cache)
		const totals = stats.content_totals || {};
		const hasContent = (totals.projects || 0) > 0 ||
		                   (totals.employees || 0) > 0 ||
		                   (totals.text_assets || 0) > 0 ||
		                   (totals.keywords || 0) > 0;

		if (!hasContent) {
			return (
				<SettingsLayout>
					<EmptyStateNoSyncs />
				</SettingsLayout>
			);
		}
	}

	// Show loading skeleton while fetching data
	if (loading || !stats) {
		return (
			<SettingsLayout>
				<div className="max-w-7xl mx-auto space-y-6">
					<div className="bg-white rounded-oa-lg p-6 animate-pulse">
						<div className="h-8 bg-gray-200 rounded w-1/3 mb-4"></div>
						<div className="h-4 bg-gray-200 rounded w-1/2"></div>
					</div>
					<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
						{[1, 2, 3, 4].map((i) => (
							<div key={i} className="bg-white rounded-oa-lg p-6 animate-pulse">
								<div className="h-12 bg-gray-200 rounded w-12 mb-4"></div>
								<div className="h-8 bg-gray-200 rounded w-20 mb-2"></div>
								<div className="h-4 bg-gray-200 rounded w-24"></div>
							</div>
						))}
					</div>
				</div>
			</SettingsLayout>
		);
	}

	return (
		<SettingsLayout>
			<div className="max-w-7xl mx-auto space-y-6">
				{/* Hero - Sync Status */}
				<SyncStatusHero
					isRunning={syncData.is_processing || syncData.is_initiating}
					lastSync={stats.sync_summary.last_sync}
					nextSync={syncData.next_scheduled}
					successRate={stats.sync_summary.success_rate}
					avgDuration={stats.sync_summary.avg_duration}
					currentProgress={syncData.is_processing ? {
						current: syncData.progress.projects + syncData.progress.employees,
						total: syncData.totals.projects + syncData.totals.employees,
						type: 'items'
					} : null}
					onRefresh={handleRefresh}
				/>

			{/* Stat Cards Row */}
			<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
				<StatCard
					type="projects"
					total={stats.content_totals.projects}
					recentChange={stats.recent_changes.projects}
					trend="up"
					icon={FolderOpen}
					color="#2563eb"
					enabled={stats.sync_settings.projects_enabled}
					onClick={() => window.location.href = '/wp-admin/edit.php?post_type=oa-project'}
				/>
				<StatCard
					type="employees"
					total={stats.content_totals.employees}
					recentChange={stats.recent_changes.employees}
					trend="up"
					icon={Users}
					color="#2563eb"
					enabled={stats.sync_settings.employees_enabled}
					onClick={() => window.location.href = '/wp-admin/edit.php?post_type=oa-employee'}
				/>
				<StatCard
					type="text-assets"
					total={stats.content_totals.text_assets}
					recentChange={stats.recent_changes.text_assets}
					trend="up"
					icon={FileText}
					color="#2563eb"
					enabled={stats.sync_settings.text_assets_enabled}
					onClick={() => window.location.href = '/wp-admin/edit.php?post_type=oa-text-asset'}
				/>
				<StatCard
					type="keywords"
					total={stats.content_totals.keywords}
					recentChange={stats.recent_changes.keywords}
					trend="up"
					icon={Tag}
					color="#2563eb"
					enabled={stats.sync_settings.keywords_enabled}
					onClick={() => window.location.href = '/wp-admin/edit-tags.php?taxonomy=oa-keyword&post_type=oa-project'}
				/>
			</div>

				{/* Charts Row */}
				<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
					<SyncPerformanceChart data={stats.performance_data || []} />
					<ContentActivityChart data={stats.activity_data || []} />
				</div>

			{/* Recent Sync Activity */}
			<RecentSyncActivity syncs={stats.recent_syncs || []} />

			{/* Help & Resources */}
			<HelpResources />

			{/* Bottom Row - Hidden for now */}
			{/* <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
				<QuickActions onManualSync={handleManualSync} />
				<SystemHealth health={systemHealth} />
			</div> */}
		</div>
		</SettingsLayout>
	);
};

export default Dashboard;

