import { useState } from 'react';
import { motion } from 'motion/react';
import { Maximize2, ChevronDown, ChevronUp } from 'lucide-react';
import FocusAreaIcon from '@/features/dashboard/FocusAreaIcon';
import {
	SiteReportHeader,
	SiteReportBody,
} from '@/features/timeline/SiteReportContent';
import useAnalytics from '@/hooks/analytics/useAnalytics';
import { EVENTS } from '@/lib/events';

// Cap the in-timeline expanded body so a long report doesn't dominate the
// chronological flow. Beyond this, the user clicks Expand to read it
// comfortably in the fullscreen modal.
const EXPANDED_MAX_HEIGHT = 'max-h-[28rem]';

const IconButton = ({ onClick, ariaLabel, children }) => (
	<button
		type="button"
		onClick={onClick}
		aria-label={ariaLabel}
		className="inline-flex items-center justify-center w-9 h-9 rounded-md border border-sky-200 bg-white text-sky-700 hover:bg-sky-50 transition-colors cursor-pointer"
	>
		{children}
	</button>
);

/**
 * SiteReportEntry
 *
 * Monthly Site Status report rendered as a distinct timeline block. Replaces
 * the regular FocusArea card layout for executions whose only detail is the
 * sitereport.
 *
 * The body is collapsible and, when open, capped at `EXPANDED_MAX_HEIGHT` with
 * an internal scroll + a bottom gradient hint — this anchors the entry to its
 * chronological slot and gives the Expand affordance a real reason to exist.
 * Clicking Expand hands `fa.id` to the parent, which mounts the fullscreen
 * modal (URL-synced).
 */
const SiteReportEntry = ({
	fa,
	report,
	entryRef,
	onOpenIntervention,
	onExpand,
}) => {
	const [open, setOpen] = useState(true);
	const { track } = useAnalytics();

	const toggleOpen = () =>
		setOpen((v) => {
			// Fire only on the collapsed -> open transition (the card starts open
			// by default, so we don't want to count the initial render).
			if (!v) {
				track(EVENTS.MONTHLY_REPORT_OPENED, {
					source: 'timeline_card',
					focus_area_id: fa.id,
				});
			}
			return !v;
		});

	return (
		<div ref={entryRef} className="relative flex items-start gap-5 mb-10">
			{/* Icon on the timeline rail */}
			<div className="relative z-10 shrink-0 mt-4">
				<FocusAreaIcon icon={fa.icon} color={fa.color} size="md" />
			</div>

			{/* The visible card is a regular div — its body collapses/expands
			 *  instantly. The `motion.div` placeholder beside it carries the
			 *  shared `layoutId` so motion can morph it into the fullscreen
			 *  modal (and back) without animating internal collapse changes. */}
			<div className="flex-1 min-w-0 relative">
				<div className="relative rounded-lg border-2 border-sky-200 bg-white shadow-sm overflow-hidden">
					<div className="p-6">
						<SiteReportHeader
							report={report}
							headerAction={
								<div className="flex items-center gap-2">
									<IconButton
										onClick={toggleOpen}
										ariaLabel={
											open ? 'Collapse report' : 'Expand report'
										}
									>
										{open ? (
											<ChevronUp className="w-4 h-4" />
										) : (
											<ChevronDown className="w-4 h-4" />
										)}
									</IconButton>
									{onExpand && (
										<IconButton
											onClick={() => {
												track(EVENTS.MONTHLY_REPORT_OPENED, {
													source: 'timeline_fullscreen',
													focus_area_id: fa.id,
												});
												onExpand(fa.id);
											}}
											ariaLabel="Open report fullscreen"
										>
											<Maximize2 className="w-4 h-4" />
										</IconButton>
									)}
								</div>
							}
						/>
					</div>

					{open && (
						<div className="relative border-t border-sky-100">
							<div
								className={`px-6 py-6 overflow-y-auto ${EXPANDED_MAX_HEIGHT}`}
							>
								<SiteReportBody
									report={report}
									onOpenIntervention={onOpenIntervention}
								/>
							</div>
							{/* Soft fade to hint at more content when scrolled. The
							 *  gradient is harmless when the body fits within the cap. */}
							<div
								aria-hidden="true"
								className="pointer-events-none absolute bottom-0 left-0 right-0 h-10 bg-gradient-to-t from-white to-transparent"
							/>
						</div>
					)}
				</div>
				<motion.div
					layoutId={`site-report-${fa.id}`}
					transition={{ duration: 0.4, ease: [0.22, 1, 0.36, 1] }}
					className="absolute inset-0 pointer-events-none"
					aria-hidden="true"
				/>
			</div>
		</div>
	);
};

export default SiteReportEntry;
