/**
 * External dependencies.
 */
import { useState, useEffect } from "@wordpress/element";
import classNames from 'clsx';
import { CheckCircle, XCircle, AlertTriangle, Clock, Trash2, Download, ChevronDown, ChevronUp, FileText } from 'lucide-react';

/**
 * Internal dependencies.
 */
import { fetchSyncLogs, clearAllSyncLogs, fetchDebugLogPreview, triggerDebugLogDownload } from "../../../api/settings";
import SettingsLayout from "../../layout/SettingsLayout";
import { SettingsCard } from "../../templates";

const SyncLogs = () => {
	const [logs, setLogs] = useState([]);
	const [loading, setLoading] = useState(true);
	const [page, setPage] = useState(1);
	const [totalPages, setTotalPages] = useState(1);
	const [total, setTotal] = useState(0);
	const [expandedLog, setExpandedLog] = useState(null);
	const [error, setError] = useState(null);
	const [debugPreview, setDebugPreview] = useState({ file: null, lines: [] });
	const [previewExpanded, setPreviewExpanded] = useState(false);
	const [previewLoading, setPreviewLoading] = useState(false);
	const perPage = 10;

	useEffect(() => {
		loadLogs();
	}, [page]);

	const loadLogs = async () => {
		setLoading(true);
		setError(null);
		try {
			const response = await fetchSyncLogs(page, perPage);
			console.log('Sync logs response:', response);
			setLogs(response.logs || []);
			setTotal(response.total || 0);
			setTotalPages(response.total_pages || 1);
		} catch (error) {
			console.error('Error loading sync logs:', error);
			setError(error.message);
		} finally {
			setLoading(false);
		}
	};

	const formatDate = (dateString) => {
		if (!dateString) return 'N/A';
		const date = new Date(dateString + ' UTC'); // Parse as UTC
		return date.toLocaleString();
	};

	const formatDuration = (seconds) => {
		if (!seconds) return 'N/A';
		if (seconds < 60) return `${seconds}s`;
		const minutes = Math.floor(seconds / 60);
		const remainingSeconds = seconds % 60;
		return `${minutes}m ${remainingSeconds}s`;
	};

	const getStatusBadge = (status) => {
		const configs = {
			completed: {
				Icon: CheckCircle,
				text: 'Completed',
				className: 'bg-green-100 text-green-800',
			},
			failed: {
				Icon: XCircle,
				text: 'Failed',
				className: 'bg-red-100 text-red-800',
			},
			partial: {
				Icon: AlertTriangle,
				text: 'Partial',
				className: 'bg-yellow-100 text-yellow-800',
			},
			pending: {
			Icon: Clock,
			text: 'Pending',
			className: 'bg-[#dbeafe] text-[#2563eb]',
			},
		};

		const config = configs[status] || configs.pending;
		const StatusIcon = config.Icon;

		return (
			<span
				className={classNames(
					'inline-flex items-center gap-1 px-oa-md py-oa-xs rounded-oa-md text-oa-xs font-oa-medium',
					config.className
				)}
			>
				<StatusIcon className="w-3 h-3" />
				{config.text}
			</span>
		);
	};

	const getSyncTypeLabel = (type) => {
		const labels = {
			incremental: 'Incremental',
			maintenance: 'Maintenance',
			manual: 'Manual',
			historical: 'Historical',
		};
		return labels[type] || type;
	};

	const toggleExpandLog = (logId) => {
		setExpandedLog(expandedLog === logId ? null : logId);
	};
	
	// Load debug log preview
	const loadDebugPreview = async () => {
		setPreviewLoading(true);
		try {
			const data = await fetchDebugLogPreview();
			setDebugPreview(data);
		} catch (err) {
			console.error('Error loading debug log preview:', err);
		} finally {
			setPreviewLoading(false);
		}
	};

	const handleTogglePreview = () => {
		if (!previewExpanded) {
			loadDebugPreview();
		}
		setPreviewExpanded(!previewExpanded);
	};

	const handleDownloadLog = async () => {
		await triggerDebugLogDownload();
	};

	// Clear all logs with confirmation
	const handleClearLogs = async () => {
		if (!window.confirm(`Are you sure you want to delete all ${total} sync logs? This cannot be undone.`)) {
			return;
		}
		
		setLoading(true);
		try {
			const result = await clearAllSyncLogs();
			console.log('Cleared logs:', result);
			// Reload logs (should be empty now)
			await loadLogs();
		} catch (error) {
			console.error('Error clearing logs:', error);
			setError('Failed to clear logs: ' + error.message);
		} finally {
			setLoading(false);
		}
	};

	return (
		<SettingsLayout isLoading={loading}>
			<SettingsCard isLoading={loading}>
				<div className="px-3 sm:px-0">
					<div className="flex items-center justify-between mb-2">
						<h1 className='text-2xl font-oa-bold text-oa-text-primary'>
							Sync Logs
						</h1>
					<div className="flex gap-2">
						{/* Download debug log button */}
						<button
							onClick={handleDownloadLog}
							className="inline-flex items-center gap-2 px-oa-lg py-oa-md text-oa-sm font-oa-semibold rounded-oa-md bg-transparent text-[#2563eb] border border-[#93c5fd] hover:bg-[#2563eb] hover:text-white hover:border-[#2563eb] disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
						>
							<Download className="w-4 h-4" />
							Download Debug Log
						</button>
						{/* Clear logs button - Ghost danger style */}
							{total > 0 && (
								<button
									onClick={handleClearLogs}
									disabled={loading}
									className="inline-flex items-center gap-2 px-oa-lg py-oa-md text-oa-sm font-oa-semibold rounded-oa-md bg-transparent text-red-600 border border-red-300 hover:bg-red-600 hover:text-white hover:border-red-600 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
								>
									<Trash2 className="w-4 h-4" />
									Clear All Logs
								</button>
							)}
						</div>
					</div>
					<p className="text-oa-sm text-oa-text-tertiary mt-1">
						View history of all sync operations. Total logs: {total}
					</p>

					{error && (
						<div className="bg-red-50 border border-red-200 rounded-oa-md p-oa-xl mb-oa-xl mt-oa-xl">
							<p className="text-red-800 font-oa-semibold">Error loading sync logs</p>
							<p className="text-red-600 text-oa-sm mt-1">{error}</p>
							<button 
								onClick={loadLogs}
								className="mt-2 text-oa-sm text-red-700 underline hover:text-red-900 font-oa-medium"
							>
								Try again
							</button>
						</div>
					)}

					{loading ? (
						<div className="text-center py-oa-4xl">
							<p className="text-oa-text-tertiary">Loading sync logs...</p>
						</div>
					) : logs.length === 0 ? (
						<div className="text-center py-oa-4xl">
							<p className="text-oa-text-tertiary">No sync logs found. Logs will appear here after your first sync.</p>
						</div>
					) : (
						<>
							{/* Logs Table */}
							<div className="overflow-x-auto mt-oa-xl border border-oa-border rounded-oa-md">
								<table className="min-w-full divide-y divide-oa-border">
									<thead className="bg-oa-bg-secondary">
										<tr>
											<th scope="col" className="px-oa-lg py-oa-lg text-left text-oa-xs font-oa-semibold text-oa-text-quaternary uppercase tracking-wider">
												Date/Time
											</th>
											<th scope="col" className="px-oa-lg py-oa-lg text-left text-oa-xs font-oa-semibold text-oa-text-quaternary uppercase tracking-wider">
												Type
											</th>
											<th scope="col" className="px-oa-lg py-oa-lg text-left text-oa-xs font-oa-semibold text-oa-text-quaternary uppercase tracking-wider">
												Status
											</th>
											<th scope="col" className="px-oa-lg py-oa-lg text-left text-oa-xs font-oa-semibold text-oa-text-quaternary uppercase tracking-wider">
												Duration
											</th>
											<th scope="col" className="px-oa-lg py-oa-lg text-left text-oa-xs font-oa-semibold text-oa-text-quaternary uppercase tracking-wider">
												Items Synced
											</th>
											<th scope="col" className="px-oa-lg py-oa-lg text-left text-oa-xs font-oa-semibold text-oa-text-quaternary uppercase tracking-wider">
												Errors
											</th>
										</tr>
									</thead>
									<tbody className="bg-white divide-y divide-oa-border-secondary">
										{logs.map((log) => (
											<>
												<tr key={log.id} className="hover:bg-oa-bg-secondary transition-colors">
													<td className="px-oa-lg py-oa-xl whitespace-nowrap text-oa-sm text-oa-text-secondary">
														{formatDate(log.sync_started)}
													</td>
													<td className="px-oa-lg py-oa-xl whitespace-nowrap text-oa-sm text-oa-text-secondary">
														<div className="font-oa-medium text-oa-text-primary">{getSyncTypeLabel(log.sync_type)}</div>
														{log.sync_trigger && (
															<span className="text-oa-xs text-oa-text-tertiary block mt-0.5">
																({log.sync_trigger})
															</span>
														)}
													</td>
													<td className="px-oa-lg py-oa-xl whitespace-nowrap">
														{getStatusBadge(log.status)}
													</td>
													<td className="px-oa-lg py-oa-xl whitespace-nowrap text-oa-sm text-oa-text-secondary">
														{formatDuration(log.duration_seconds)}
													</td>
													<td className="px-oa-lg py-oa-xl text-oa-sm text-oa-text-secondary">
													<div className="space-y-0.5">
														{log.projects_synced > 0 && (
															<div className="text-oa-text-primary">Projects: {log.projects_synced}</div>
														)}
														{log.employees_synced > 0 && (
															<div className="text-oa-text-primary">Employees: {log.employees_synced}</div>
														)}
														{log.text_assets_synced > 0 && (
															<div className="text-oa-text-primary">Text Assets: {log.text_assets_synced}</div>
														)}
														{log.keywords_synced > 0 && (
															<div className="text-oa-text-primary">Keywords: {log.keywords_synced}</div>
														)}
														{log.projects_synced === 0 && log.employees_synced === 0 && log.text_assets_synced === 0 && log.keywords_synced === 0 && (
															<div className="text-oa-text-tertiary italic">None</div>
														)}
													</div>
													</td>
												<td className="px-oa-lg py-oa-xl whitespace-nowrap text-oa-sm">
													{log.errors_count > 0 ? (
														<button
															onClick={() => toggleExpandLog(log.id)}
															className="text-red-600 font-oa-medium hover:text-red-800 underline decoration-dotted cursor-pointer"
															title="Click to view error details"
														>
															{log.errors_count}
														</button>
													) : (
														<span className="text-oa-text-tertiary">0</span>
													)}
												</td>
											</tr>
											{expandedLog === log.id && (
												<tr>
													<td colSpan="6" className="px-oa-lg py-oa-xl bg-oa-bg-secondary">
															<div className="space-y-oa-lg">
																{/* Deletions */}
																{(log.projects_deleted > 0 || log.employees_deleted > 0) && (
																	<div>
																		<h4 className="font-oa-semibold text-oa-sm text-oa-text-primary mb-oa-sm">Items Deleted</h4>
																		<div className="text-oa-sm text-oa-text-secondary space-y-1">
																			{log.projects_deleted > 0 && (
																				<div>Projects: {log.projects_deleted}</div>
																			)}
																			{log.employees_deleted > 0 && (
																				<div>Employees: {log.employees_deleted}</div>
																			)}
																		</div>
																	</div>
																)}
																
																{/* Errors */}
																{log.errors_count > 0 && log.error_details && (
																	<div>
																		<h4 className="font-oa-semibold text-oa-sm text-oa-text-primary mb-oa-sm">Errors ({log.errors_count})</h4>
																		<div className="bg-red-50 border border-red-200 rounded-oa-md p-oa-lg max-h-60 overflow-y-auto">
																			{Array.isArray(log.error_details) ? (
																				<ul className="space-y-oa-sm text-oa-sm">
																					{log.error_details.map((error, idx) => (
																						<li key={idx} className="text-red-800">
																							<span className="font-oa-medium">{error.message}</span>
																							{error.timestamp && (
																								<span className="text-oa-xs text-red-600 block">
																									{formatDate(error.timestamp)}
																								</span>
																							)}
																						</li>
																					))}
																				</ul>
																			) : (
																				<pre className="text-oa-xs text-red-800 whitespace-pre-wrap">
																					{JSON.stringify(log.error_details, null, 2)}
																				</pre>
																			)}
																		</div>
																	</div>
																)}
																
																{/* Additional Info */}
																<div>
																	<h4 className="font-oa-semibold text-oa-sm text-oa-text-primary mb-oa-sm">Additional Info</h4>
																	<div className="text-oa-sm text-oa-text-secondary space-y-1">
																		<div>Items Queued: {log.items_queued}</div>
																		<div>Items Processed: {log.items_processed}</div>
																		<div>Completed: {formatDate(log.sync_completed)}</div>
																	</div>
																</div>
															</div>
														</td>
													</tr>
												)}
											</>
										))}
									</tbody>
								</table>
							</div>

							{/* Pagination */}
							{totalPages > 1 && (
								<div className="flex items-center justify-between border-t border-oa-border bg-white px-oa-xl py-oa-lg sm:px-oa-2xl mt-oa-xl">
									<div className="flex flex-1 justify-between sm:hidden">
										<button
											onClick={() => setPage(page - 1)}
											disabled={page === 1}
											className="relative inline-flex items-center rounded-oa-md border border-oa-border bg-white px-oa-xl py-oa-md text-oa-sm font-oa-medium text-oa-text-secondary hover:bg-oa-bg-secondary disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
										>
											Previous
										</button>
										<button
											onClick={() => setPage(page + 1)}
											disabled={page === totalPages}
											className="relative ml-3 inline-flex items-center rounded-oa-md border border-oa-border bg-white px-oa-xl py-oa-md text-oa-sm font-oa-medium text-oa-text-secondary hover:bg-oa-bg-secondary disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
										>
											Next
										</button>
									</div>
									<div className="hidden sm:flex sm:flex-1 sm:items-center sm:justify-between">
										<div>
											<p className="text-oa-sm text-oa-text-secondary">
												Showing page <span className="font-oa-medium">{page}</span> of{' '}
												<span className="font-oa-medium">{totalPages}</span>
											</p>
										</div>
										<div>
											<nav className="isolate inline-flex -space-x-px rounded-oa-md shadow-oa-xs" aria-label="Pagination">
												<button
													onClick={() => setPage(page - 1)}
													disabled={page === 1}
													className="relative inline-flex items-center rounded-l-oa-md px-oa-md py-oa-md text-oa-text-quaternary ring-1 ring-inset ring-oa-border hover:bg-oa-bg-secondary focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
												>
													<span className="sr-only">Previous</span>
													<svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
														<path fillRule="evenodd" d="M12.79 5.23a.75.75 0 01-.02 1.06L8.832 10l3.938 3.71a.75.75 0 11-1.04 1.08l-4.5-4.25a.75.75 0 010-1.08l4.5-4.25a.75.75 0 011.06.02z" clipRule="evenodd" />
													</svg>
												</button>
												
												{/* Page numbers */}
												{[...Array(totalPages)].map((_, idx) => {
													const pageNum = idx + 1;
													// Show first, last, current, and pages around current
													if (
														pageNum === 1 ||
														pageNum === totalPages ||
														(pageNum >= page - 1 && pageNum <= page + 1)
													) {
														return (
															<button
																key={pageNum}
																onClick={() => setPage(pageNum)}
															className={`relative inline-flex items-center px-oa-xl py-oa-md text-oa-sm font-oa-semibold transition-colors ${
																page === pageNum
																	? 'z-10 bg-[#2563eb] text-white hover:bg-[#1d4ed8] focus:z-20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#2563eb]'
																	: 'text-oa-text-primary bg-white ring-1 ring-inset ring-oa-border hover:bg-oa-bg-secondary focus:z-20 focus:outline-offset-0'
															}`}
															>
																{pageNum}
															</button>
														);
													} else if (pageNum === page - 2 || pageNum === page + 2) {
														return (
															<span key={pageNum} className="relative inline-flex items-center px-oa-xl py-oa-md text-oa-sm font-oa-semibold text-oa-text-secondary ring-1 ring-inset ring-oa-border">
																...
															</span>
														);
													}
													return null;
												})}
												
												<button
													onClick={() => setPage(page + 1)}
													disabled={page === totalPages}
													className="relative inline-flex items-center rounded-r-oa-md px-oa-md py-oa-md text-oa-text-quaternary ring-1 ring-inset ring-oa-border hover:bg-oa-bg-secondary focus:z-20 focus:outline-offset-0 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
												>
													<span className="sr-only">Next</span>
													<svg className="h-5 w-5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
														<path fillRule="evenodd" d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z" clipRule="evenodd" />
													</svg>
												</button>
											</nav>
										</div>
									</div>
								</div>
							)}
						</>
					)}
				</div>
			</SettingsCard>

			{/* Debug Log Preview */}
			<SettingsCard>
				<div className="px-3 sm:px-0">
					<button
						onClick={handleTogglePreview}
						className="flex items-center justify-between w-full text-left"
					>
						<div className="flex items-center gap-2">
							<FileText className="w-5 h-5 text-oa-text-tertiary" />
							<h2 className="text-lg font-oa-semibold text-oa-text-primary">Debug Log Preview</h2>
							{debugPreview.file && debugPreview.file.exists && (
								<span className="text-oa-xs text-oa-text-quaternary bg-oa-bg-secondary px-2 py-0.5 rounded-full">
									{debugPreview.file.size_human}
								</span>
							)}
						</div>
						{previewExpanded
							? <ChevronUp className="w-5 h-5 text-oa-text-tertiary" />
							: <ChevronDown className="w-5 h-5 text-oa-text-tertiary" />
						}
					</button>

					{previewExpanded && (
						<div className="mt-4">
							{previewLoading ? (
								<div className="text-oa-sm text-oa-text-tertiary py-4">Loading preview...</div>
							) : debugPreview.lines && debugPreview.lines.length > 0 ? (
								<>
									{debugPreview.file && debugPreview.file.modified && (
										<p className="text-oa-xs text-oa-text-quaternary mb-2">
											Last modified: {debugPreview.file.modified} UTC
										</p>
									)}
									<pre className="bg-gray-900 text-green-400 text-xs font-mono p-4 rounded-lg overflow-x-auto max-h-96 overflow-y-auto leading-relaxed">
										{debugPreview.lines.join('\n')}
									</pre>
								</>
							) : (
								<div className="text-oa-sm text-oa-text-tertiary py-4 bg-oa-bg-secondary rounded-oa-md px-4">
									No debug log file found. Run a sync to generate logs. Enable Detailed Logging in General Settings for more verbose output.
								</div>
							)}
						</div>
					)}
				</div>
			</SettingsCard>
		</SettingsLayout>
	);
};

export default SyncLogs;

