import {
	MapPin,
	ChevronDown,
	Check,
	X,
	Trash2,
	Plus,
	Sparkles,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { TextInput } from '@/components/ui/text-input';
import { Textarea } from '@/components/ui/textarea';
import { RichTextEditor } from '@/components/ui/rich-text-editor';

const MAX_FAQ = 5;

/** One-line summary for the collapsed card. */
const summarize = (item) => {
	const text = (item.content_html || '').replace(/<[^>]*>/g, ' ');
	const words = text.trim().split(/\s+/).filter(Boolean).length;
	const paragraphs = (item.content_html || '').match(/<p[\s>]/gi)?.length || 0;
	const faqs = item.faq_pairs.length;
	const parts = [`H1 "${item.h1}"`];
	if (paragraphs) parts.push(`${paragraphs} paragraph${paragraphs === 1 ? '' : 's'}`);
	if (words) parts.push(`~${words} words`);
	parts.push(`${faqs} FAQ`);
	return parts.join(' · ');
};

const StatusBadge = ({ decision, edited }) => {
	if (decision === 'approved') {
		return (
			<span className="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-2.5 py-1 small-medium text-emerald-700">
				<Check className="w-3.5 h-3.5" />
				Approved{edited ? ' · edited' : ''}
			</span>
		);
	}
	if (decision === 'rejected') {
		return (
			<span className="inline-flex items-center gap-1.5 rounded-full bg-red-50 px-2.5 py-1 small-medium text-red-700">
				<X className="w-3.5 h-3.5" />
				Rejected
			</span>
		);
	}
	return (
		<span className="inline-flex items-center gap-1.5 rounded-full bg-muted px-2.5 py-1 small-medium text-muted-foreground">
			<span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/60" />
			Pending decision
		</span>
	);
};

/**
 * One proposal in the `locationpages` intervention: collapsed it shows a summary
 * and quick actions; expanded it shows the editable fields (H1, content WYSIWYG,
 * FAQ). Decisions and edits are local until the parent submits the whole
 * intervention.
 */
const LocationPageCard = ({
	proposal,
	item,
	isPaused,
	expanded,
	onToggle,
	onDecision,
	onChange,
	onAddFaq,
}) => {
	const decision = item.decision;
	const title =
		[proposal.service, proposal.location_name].filter(Boolean).join(' · ') ||
		item.h1 ||
		proposal.slug;

	const updateFaq = (pairId, field, value) =>
		onChange({
			faq_pairs: item.faq_pairs.map((f) =>
				f.id === pairId ? { ...f, [field]: value } : f
			),
		});
	const removeFaq = (pairId) =>
		onChange({
			faq_pairs: item.faq_pairs.filter((f) => f.id !== pairId),
		});

	const borderTone =
		decision === 'approved'
			? 'border-emerald-200'
			: decision === 'rejected'
				? 'border-red-200'
				: 'border-border';

	return (
		<div
			className={`rounded-2xl border ${borderTone} ${
				expanded ? 'shadow-sm' : ''
			} text-left overflow-hidden`}
		>
			{/* Header (always visible, toggles expand) */}
			<button
				type="button"
				onClick={onToggle}
				className="w-full flex items-center gap-3 px-5 py-4 text-left cursor-pointer hover:bg-muted/30 transition-colors"
			>
				<span className="inline-flex items-center justify-center w-9 h-9 rounded-full border border-border shrink-0">
					<MapPin className="w-4 h-4 text-muted-foreground" />
				</span>
				<span className="min-w-0 flex-1">
					<span className="block small-semibold text-foreground truncate">
						{title}
					</span>
					<span className="block small-regular text-muted-foreground truncate">
						{expanded
							? `/${proposal.slug}`
							: summarize(item)}
					</span>
				</span>
				<StatusBadge decision={decision} edited={item.edited} />
				<ChevronDown
					className={`w-4 h-4 text-muted-foreground shrink-0 transition-transform ${
						expanded ? 'rotate-180' : ''
					}`}
				/>
			</button>

			{/* Collapsed quick actions */}
			{!expanded && !isPaused && (
				<div className="flex items-center justify-end gap-2 px-5 pb-4">
					{decision === 'pending' ? (
						<>
							<button
								type="button"
								onClick={() => onDecision('rejected')}
								aria-label="Reject this page"
								className="inline-flex items-center justify-center w-10 h-10 rounded-md border border-border text-muted-foreground hover:text-red-600 hover:border-red-200 transition-colors cursor-pointer"
							>
								<X className="w-4 h-4" />
							</button>
							<Button
								onClick={() => onDecision('approved')}
								className="bg-foreground text-background! hover:bg-foreground/90"
							>
								<Check />
								Approve
							</Button>
						</>
					) : (
						<button
							type="button"
							onClick={() => onDecision('pending')}
							className="small-medium text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
						>
							Undo
						</button>
					)}
				</div>
			)}

			{/* Expanded editor */}
			{expanded && (
				<div className="px-5 pb-5 border-t border-border pt-5">
					{/* H1 */}
					<p className="small-semibold uppercase tracking-wide text-muted-foreground mb-2">
						Page heading (H1)
					</p>
					<TextInput
						value={item.h1}
						onChange={(e) => onChange({ h1: e.target.value })}
						error={!item.h1.trim()}
						placeholder="Page heading"
						className="text-2xl! font-bold! h-auto! py-2.5!"
					/>

					{/* Content */}
					<p className="small-semibold uppercase tracking-wide text-muted-foreground mt-5 mb-2">
						Page content
					</p>
					<RichTextEditor
						value={item.content_html}
						onChange={(html) => onChange({ content_html: html })}
					/>

					{/* FAQ */}
					<div className="flex items-center gap-2 mt-6 mb-4">
						<p className="small-semibold uppercase tracking-wide text-muted-foreground my-0!">
							FAQ section
						</p>
						<span className="small-regular text-muted-foreground/70">
							optional
						</span>
						<span className="ml-auto small-regular text-muted-foreground">
							{item.faq_pairs.length} / {MAX_FAQ}
						</span>
						{item.faq_pairs.length > 0 && (
							<button
								type="button"
								onClick={() => onChange({ faq_pairs: [] })}
								className="small-medium text-muted-foreground hover:text-red-600 transition-colors cursor-pointer"
							>
								Remove section
							</button>
						)}
					</div>
					{item.faq_pairs.length > 0 && (
						<TextInput
							value={item.faq_heading}
							onChange={(e) =>
								onChange({ faq_heading: e.target.value })
							}
							placeholder="FAQ heading"
							className="text-xl! font-bold! h-auto! py-2! mb-7!"
						/>
					)}
					<div className="space-y-6">
						{item.faq_pairs.map((f) => (
							<div key={f.id} className="flex items-start gap-2">
								<div className="flex-1 min-w-0">
									<div className="flex items-start gap-2.5">
										<span className="shrink-0 w-5 h-10 inline-flex items-center justify-center small-semibold text-muted-foreground/50">
											Q
										</span>
										<TextInput
											value={f.question}
											onChange={(e) =>
												updateFaq(
													f.id,
													'question',
													e.target.value
												)
											}
											error={!f.question.trim()}
											placeholder="Question"
											className="font-semibold! flex-1 min-w-0"
										/>
									</div>
									<div className="flex items-start gap-2.5 mt-3">
										<span className="shrink-0 w-5 pt-2.5 text-center small-semibold text-muted-foreground/50">
											A
										</span>
										<Textarea
											value={f.answer}
											onChange={(e) =>
												updateFaq(
													f.id,
													'answer',
													e.target.value
												)
											}
											error={!f.answer.trim()}
											rows={2}
											placeholder="Answer"
											className="flex-1 min-w-0"
										/>
									</div>
								</div>
								<button
									type="button"
									onClick={() => removeFaq(f.id)}
									aria-label="Remove question"
									className="inline-flex items-center justify-center w-8 h-8 rounded-md text-muted-foreground hover:bg-muted/60 hover:text-foreground transition-colors cursor-pointer mt-1"
								>
									<Trash2 className="w-4 h-4" />
								</button>
							</div>
						))}
					</div>
					{item.faq_pairs.length < MAX_FAQ && (
						<button
							type="button"
							onClick={onAddFaq}
							className="mt-3 w-full inline-flex items-center justify-center gap-1.5 rounded-xl border border-dashed border-border px-4 py-2.5 small-medium text-muted-foreground hover:bg-muted/40 hover:text-foreground transition-colors cursor-pointer"
						>
							<Plus className="w-4 h-4" />
							Add{item.faq_pairs.length ? ' another' : ''} question
						</button>
					)}

					<div className="flex items-start gap-2 mt-4 small-regular text-muted-foreground">
						<Sparkles className="w-4 h-4 shrink-0 mt-0.5" />
						<span>
							If you keep questions, I'll add FAQPage schema so this
							page can show as a rich result in Google.
						</span>
					</div>

					{/* Per-card decision */}
					{!isPaused && (
						<div className="flex items-center justify-between gap-3 mt-6 pt-5 border-t border-border">
							<span className="small-regular text-muted-foreground">
								Decide whether to publish this page.
							</span>
							<div className="flex items-center gap-2">
								<Button
									onClick={() => onDecision('rejected')}
									variant="outline"
									className={
										decision === 'rejected'
											? 'border-red-300! text-red-600!'
											: ''
									}
								>
									<X />
									Reject this page
								</Button>
								<Button
									onClick={() => onDecision('approved')}
									className="bg-foreground text-background! hover:bg-foreground/90"
								>
									<Check />
									Approve this page
								</Button>
							</div>
						</div>
					)}
				</div>
			)}
		</div>
	);
};

export default LocationPageCard;
