import { Button, Card } from "@vreko/ui/components";
import type React from "react";
import vrekoIcon from "../assets/vreko-icon.png";
import { CliInstallCard } from "../components/CliInstallCard";
import { StatusBadge } from "../components/StatusBadge";
import { formatNumber } from "../utils/format";

// Brand constants will be passed as props from extension
interface DashboardHomeProps {
	stats: {
		snapshotsToday: number;
		totalSnapshots: number;
		restoresToday: number;
		linesProtected: number;
		tokensSaved: number;
		restoresThisWeek: number;
		efficiencyPercentile: number;
	};
	mcpStatus: {
		enabled: boolean;
		serverUrl: string;
		queuedItems: number;
		pushCount: number;
	};
	onOpenSettings: () => void;
	onNavigateToActivity: () => void;
	/** CLI installation status (optional - shows card if not installed) */
	cliStatus?: {
		installed: boolean;
		version: string | null;
	};
	/** Handler for creating a snapshot */
	onCreateSnapshot?: () => void;
	/** NEW: Intelligence data from local-service */
	intelligence?: {
		fragileFiles?: {
			items: Array<{
				filePath: string;
				fragilityScore: number;
				severity: "moderate" | "high" | "critical";
				reason: string;
				suggestion: string;
				rollbackCount: number;
				aiChurnCount: number;
			}>;
			total: number;
		};
		coChanges?: {
			items: Array<{
				fileA: string;
				fileB: string;
				frequency: number;
				occurrences: number;
				relationship: string;
				reason: string;
				lastObserved: string;
			}>;
			total: number;
		};
		health?: {
			score: number;
			trajectory: "improving" | "stable" | "declining";
			warningCount: number;
		};
		summary?: {
			learningsCount: number;
			patternsCount: number;
			fragileFilesCount: number;
			coChangePatternsCount: number;
			totalSessions: number;
			linesAnalyzed: number;
			healthScore: number;
			healthTrajectory: string;
		};
	};
}

// Brand constants (from extension BRANDING export)
const ICONS = {
	snapshot: "📸",
	restore: "⏪",
	protected: "🛡️",
	money: "💰",
	growth: "📈",
	inject: "💉",
	settings: "⚙️",
	logo: "🦎",
} as const;

export const DashboardHome: React.FC<DashboardHomeProps> = ({
	stats,
	mcpStatus,
	onOpenSettings,
	onNavigateToActivity,
	cliStatus,
	onCreateSnapshot,
	intelligence,
}) => {
	const { fragileFiles, coChanges, summary } = intelligence || {};
	const {
		snapshotsToday,
		totalSnapshots,
		restoresToday,
		linesProtected,
		tokensSaved,
		restoresThisWeek,
		efficiencyPercentile,
	} = stats;

	// Calculate token cost estimates
	const gpt4Cost = ((tokensSaved / 1000) * 0.03).toFixed(2);
	const gpt35Cost = ((tokensSaved / 1000) * 0.002).toFixed(2);

	return (
		<div className="p-6 bg-zinc-950 text-zinc-100 min-h-screen">
			{/* Status Card with MCP/CLI badges */}
			<Card className="mb-6 border-emerald-900/30 bg-emerald-950/20">
				<div className="flex items-center gap-4 p-6">
					<img src={vrekoIcon} alt="Vreko" className="w-12 h-12" />
					<div className="flex-1">
						<h2 className="text-2xl font-bold text-emerald-400">AI Intelligence Active</h2>
						<p className="text-zinc-400">
							{totalSnapshots} AI change{totalSnapshots !== 1 ? "s" : ""} captured
						</p>
					</div>
					<div className="flex gap-2">
						<StatusBadge
							status={mcpStatus.enabled ? "connected" : "disabled"}
							label={mcpStatus.enabled ? "MCP" : "MCP Off"}
						/>
						{cliStatus?.installed && (
							<StatusBadge status="connected" label={`CLI ${cliStatus.version || ""}`} />
						)}
					</div>
				</div>
			</Card>

			{/* AI Changes Captured */}
			<div className="mb-6">
				<h3 className="text-sm font-semibold text-zinc-400 mb-3 uppercase tracking-wide">
					AI Changes Captured
				</h3>
				<div className="grid grid-cols-3 gap-4">
					<Card className="border-zinc-800 bg-zinc-900 p-4">
						<div className="text-2xl mb-1">{ICONS.snapshot}</div>
						<div className="text-2xl font-bold text-zinc-100">{formatNumber(snapshotsToday)}</div>
						<div className="text-xs text-zinc-500">Changes Today</div>
					</Card>
					<Card className="border-zinc-800 bg-zinc-900 p-4">
						<div className="text-2xl mb-1">{ICONS.restore}</div>
						<div className="text-2xl font-bold text-zinc-100">{formatNumber(restoresToday)}</div>
						<div className="text-xs text-zinc-500">Reverted</div>
					</Card>
					<Card className="border-zinc-800 bg-zinc-900 p-4">
						<div className="text-2xl mb-1">{ICONS.protected}</div>
						<div className="text-2xl font-bold text-zinc-100">{formatNumber(linesProtected)}</div>
						<div className="text-xs text-zinc-500">Lines Analyzed</div>
					</Card>
				</div>
			</div>

			{/* NEW: Workspace Intelligence Section */}
			{(fragileFiles?.total || coChanges?.total || summary) && (
				<div className="mb-6">
					<h3 className="text-sm font-semibold text-zinc-400 mb-3 uppercase tracking-wide">
						🧠 Workspace Intelligence
					</h3>
					<div className="space-y-4">
						{/* Fragile Files */}
						{fragileFiles && fragileFiles.total > 0 && (
							<Card className="border-zinc-800 bg-zinc-900 p-4">
								<div className="flex items-center justify-between mb-2">
									<h4 className="font-semibold text-zinc-200">⚠ Fragile Files</h4>
									<span className="text-xs text-zinc-500">{fragileFiles.total} files</span>
								</div>
								<ul className="space-y-1">
									{fragileFiles.items.slice(0, 3).map((file) => (
										<li key={file.filePath} className="text-sm text-zinc-400 flex justify-between">
											<span className="truncate">{file.filePath}</span>
											<span className="text-xs text-orange-400">
												{file.severity === "critical"
													? "🔴"
													: file.severity === "high"
														? "🟠"
														: "🟡"}
											</span>
										</li>
									))}
								</ul>
							</Card>
						)}

						{/* Co-Change Patterns */}
						{coChanges && coChanges.total > 0 && (
							<Card className="border-zinc-800 bg-zinc-900 p-4">
								<div className="flex items-center justify-between mb-2">
									<h4 className="font-semibold text-zinc-200">🔗 Co-Change Patterns</h4>
									<span className="text-xs text-zinc-500">{coChanges.total} patterns</span>
								</div>
								<ul className="space-y-1">
									{coChanges.items.slice(0, 3).map((pattern) => (
										<li key={`${pattern.fileA}-${pattern.fileB}`} className="text-sm text-zinc-400">
											<span className="truncate">{pattern.fileA}</span>
											<span className="mx-2 text-zinc-600">↔</span>
											<span className="truncate">{pattern.fileB}</span>
											<span className="text-xs text-zinc-600 ml-2">
												({Math.round(pattern.frequency * 100)}%)
											</span>
										</li>
									))}
								</ul>
							</Card>
						)}

						{/* Health Summary */}
						{summary && (
							<Card className="border-zinc-800 bg-zinc-900 p-4">
								<div className="grid grid-cols-2 gap-4 text-sm">
									<div>
										<span className="text-zinc-500">Health Score</span>
										<div className="text-lg font-bold text-emerald-400">
											{summary.healthScore}/100
										</div>
									</div>
									<div>
										<span className="text-zinc-500">Trend</span>
										<div className="text-lg font-bold">
											{summary.healthTrajectory === "improving"
												? "📈 Improving"
												: summary.healthTrajectory === "declining"
													? "📉 Declining"
													: "➡️ Stable"}
										</div>
									</div>
									<div>
										<span className="text-zinc-500">Patterns Learned</span>
										<div className="text-lg font-bold text-zinc-200">{summary.patternsCount}</div>
									</div>
									<div>
										<span className="text-zinc-500">Sessions Analyzed</span>
										<div className="text-lg font-bold text-zinc-200">{summary.totalSessions}</div>
									</div>
								</div>
							</Card>
						)}
					</div>
				</div>
			)}

			{/* CLI Installation Card - Show if CLI not installed */}
			{(!cliStatus || !cliStatus.installed) && (
				<div className="mb-6">
					<h3 className="text-sm font-semibold text-zinc-400 mb-3 uppercase tracking-wide">Setup</h3>
					<CliInstallCard initialStatus={cliStatus} />
				</div>
			)}

			{/* Impact Summary */}
			{restoresThisWeek > 0 && (
				<div className="mb-6">
					<h3 className="text-sm font-semibold text-zinc-400 mb-3 uppercase tracking-wide">
						Impact This Week
					</h3>
					<Card className="border-zinc-800 bg-zinc-900 p-4">
						<div className="flex items-start gap-3 mb-2">
							<span className="text-2xl">{ICONS.restore}</span>
							<div>
								<p className="text-zinc-300">
									{restoresThisWeek} AI changes reverted - ~{formatNumber(tokensSaved)} tokens saved
								</p>
								<p className="text-sm text-zinc-500 mt-1">
									{ICONS.money} Estimated: ${gpt4Cost} (GPT-4) / ${gpt35Cost} (3.5)
								</p>
								<p className="text-sm text-emerald-400 mt-1">
									{ICONS.growth} You're in top {efficiencyPercentile}% efficiency
								</p>
							</div>
						</div>
					</Card>
				</div>
			)}

			{/* Quick Actions */}
			<div>
				<h3 className="text-sm font-semibold text-zinc-400 mb-3 uppercase tracking-wide">Quick Actions</h3>
				<div className="flex gap-2">
					{onCreateSnapshot && (
						<Button size="sm" variant="primary" onClick={onCreateSnapshot}>
							<span className="mr-2">{ICONS.snapshot}</span>
							Create Snapshot
						</Button>
					)}
					<Button size="sm" variant="outline" onClick={onNavigateToActivity}>
						<span className="mr-2">📋</span>
						View Activity
					</Button>
					<Button size="sm" variant="outline" onClick={onOpenSettings}>
						<span className="mr-2">{ICONS.settings}</span>
						Settings
					</Button>
				</div>
			</div>
		</div>
	);
};
