import {
	CheckCircle2,
	ChevronRight,
	Eye,
	Compass,
	FileText,
} from 'lucide-react';
import { Button } from '@/components/ui/button';

const MS_PER_DAY = 24 * 60 * 60 * 1000;

const parseISODate = (value) => {
	if (!value) return null;
	const d = new Date(value);
	return Number.isNaN(d.getTime()) ? null : d;
};

const formatPeriod = (period) => {
	const start = parseISODate(period?.start);
	const end = parseISODate(period?.end);
	if (!start || !end) return '';
	// period is [start, end); subtract one day to display an inclusive end.
	const inclusiveEnd = new Date(end.getTime() - MS_PER_DAY);
	const sameYear = start.getUTCFullYear() === inclusiveEnd.getUTCFullYear();
	const sameMonth =
		sameYear && start.getUTCMonth() === inclusiveEnd.getUTCMonth();
	const opts = { timeZone: 'UTC' };
	if (sameMonth && start.getUTCDate() === 1) {
		return start.toLocaleDateString('en-US', {
			...opts,
			month: 'long',
			year: 'numeric',
		});
	}
	const startStr = start.toLocaleDateString('en-US', {
		...opts,
		month: 'short',
		day: 'numeric',
	});
	const endStr = inclusiveEnd.toLocaleDateString('en-US', {
		...opts,
		month: 'short',
		day: 'numeric',
		year: sameYear ? undefined : 'numeric',
	});
	return `${startStr} to ${endStr}`;
};

const formatGeneratedAt = (value) => {
	const d = parseISODate(value);
	if (!d) return '';
	return d.toLocaleDateString('en-US', {
		month: 'short',
		day: 'numeric',
		year: 'numeric',
	});
};

const trimTrailingPunctuation = (s) =>
	typeof s === 'string' ? s.replace(/[.\s]+$/, '') : s;

const Section = ({ icon: Icon, label, children }) => (
	<section className="flex flex-col gap-4">
		<div className="flex items-center gap-2">
			{Icon && <Icon className="w-4 h-4 text-sky-600 shrink-0" />}
			<p className="label-semibold uppercase tracking-wider text-sky-700 m-0!">
				{label}
			</p>
		</div>
		{children}
	</section>
);

const ImprovementItem = ({ item }) => (
	<li className="flex items-start gap-3">
		<CheckCircle2 className="w-4.5 h-4.5 text-green-500 shrink-0 mt-1" />
		<div className="flex-1 min-w-0 flex flex-col gap-1">
			<p className="paragraph-semibold text-foreground m-0!">
				{item.title}
			</p>
			{item.detail && (
				<p className="small-regular text-muted-foreground m-0!">
					{item.detail}
				</p>
			)}
		</div>
	</li>
);

const NeededItem = ({ item, onOpenIntervention }) => {
	const ctaLabel = trimTrailingPunctuation(item.cta) || 'Review';
	const canAct = Boolean(item.intervention_id) && Boolean(onOpenIntervention);
	return (
		<div className="rounded-lg border border-amber-200 bg-amber-50/40 p-5">
			<div className="flex items-start gap-4">
				<div className="flex-1 min-w-0 flex flex-col gap-1">
					<p className="paragraph-semibold text-foreground m-0!">
						{item.title}
					</p>
					{item.detail && (
						<p className="small-regular text-muted-foreground m-0!">
							{item.detail}
						</p>
					)}
				</div>
				{canAct && (
					<Button
						type="button"
						size="sm"
						onClick={() => onOpenIntervention(item.intervention_id)}
						className="shrink-0"
					>
						{ctaLabel}
						<ChevronRight className="w-4 h-4" />
					</Button>
				)}
			</div>
		</div>
	);
};

/**
 * Header chunk for the Site Status monthly report. Always visible (chip,
 * period, generated date). The right-side action slot is rendered by the
 * caller — SiteReportEntry puts the collapse + expand buttons there;
 * SiteReportFullscreen puts the close button.
 */
export const SiteReportHeader = ({ report, headerAction = null }) => {
	const period = formatPeriod(report?.period);
	const generated = formatGeneratedAt(report?.generated_at);
	return (
		<header className="flex items-start justify-between gap-4">
			<div className="min-w-0">
				<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-sky-100 text-sky-700 text-xs font-semibold mb-2">
					<FileText className="w-3.5 h-3.5" />
					Monthly Report
				</span>
				{period && (
					<h3 className="heading-h3 text-foreground mb-1">
						{period}
					</h3>
				)}
				{generated && (
					<p className="small-regular text-muted-foreground m-0!">
						Generated {generated}
					</p>
				)}
			</div>
			{headerAction && <div className="shrink-0">{headerAction}</div>}
		</header>
	);
};

/**
 * Body chunk for the Site Status monthly report: the six narrative sections.
 * Rendered by SiteReportEntry only when expanded, and by
 * SiteReportFullscreen always.
 */
export const SiteReportBody = ({
	report,
	onOpenIntervention,
	spacing = 'flex flex-col gap-10',
}) => {
	const improvements = Array.isArray(report?.improvements)
		? report.improvements
		: [];
	const needed = Array.isArray(report?.needed) ? report.needed : [];
	const nextSteps = Array.isArray(report?.next_steps)
		? report.next_steps.filter(Boolean)
		: [];

	return (
		<div className={spacing}>
			{/* 1. Opening summary */}
			{report?.summary && (
				<p className="paragraph-regular text-foreground m-0!">
					{report.summary}
				</p>
			)}

			{/* 2. What I improved */}
			{improvements.length > 0 && (
				<Section icon={CheckCircle2} label="What I improved">
					<ul className="space-y-5 list-none p-0 m-0!">
						{improvements.map((item, i) => (
							<ImprovementItem key={i} item={item} />
						))}
					</ul>
					<p className="paragraph-regular italic text-muted-foreground m-0! pl-[1.875rem]">
						→ Plus a few more fixes behind the scenes.
					</p>
				</Section>
			)}

			{/* 3. What this means for you */}
			{report?.meaning && (
				<Section label="What this means for you">
					<p className="paragraph-regular text-foreground m-0!">
						{report.meaning}
					</p>
				</Section>
			)}

			{/* 4. What I'm watching */}
			{report?.watching && (
				<Section icon={Eye} label="What I'm watching">
					<p className="paragraph-regular text-foreground m-0!">
						{report.watching}
					</p>
				</Section>
			)}

			{/* 5. What I need from you (only if blockers) */}
			{needed.length > 0 && (
				<Section label="What I need from you">
					<div className="space-y-4">
						{needed.map((item, i) => (
							<NeededItem
								key={item.intervention_id || i}
								item={item}
								onOpenIntervention={onOpenIntervention}
							/>
						))}
					</div>
				</Section>
			)}

			{/* 6. Suggested next steps (optional) */}
			{nextSteps.length > 0 && (
				<Section icon={Compass} label="Suggested next steps">
					<ul className="space-y-2 list-disc pl-5 m-0!">
						{nextSteps.map((step, i) => (
							<li
								key={i}
								className="paragraph-regular text-foreground"
							>
								{typeof step === 'string'
									? step
									: step?.title || step?.detail || ''}
							</li>
						))}
					</ul>
				</Section>
			)}
		</div>
	);
};
