import { useState } from 'react';
import {
	ArrowLeft,
	Crosshair,
	Store,
	Users,
	MapPin,
	Building2,
	CircleCheck,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import SpeechBubble from '@/components/ui/speech-bubble';
import AddressAutocompleteInput from '@/components/ui/address-autocomplete-input';
import { getWordPressConfig, post } from '@/api/client';
import { getGoalById } from '@/constants/goals';
import useOnboarding from '@/hooks/useOnboarding';
import { captureException } from '@/lib/errorMonitoring';

/**
 * Short labels for goal options in edit mode
 */
const GOAL_OPTIONS = [
	{
		id: 'visibility',
		title: 'Increase my visibility',
		subtitle: 'Get found on Google and AI assistants',
	},
	{
		id: 'customers',
		title: 'Get more new customers',
		subtitle: 'Especially local ones. Be discovered nearby',
	},
	{
		id: 'loyalty',
		title: 'Build loyalty & retention',
		subtitle: 'Strengthen relationships with current customers',
	},
];

/**
 * ProfileCard Component
 *
 * Card with icon, uppercase label, optional action link, and content.
 */
const ProfileCard = ({
	icon,
	label,
	action,
	onAction,
	editing,
	children,
	className,
}) => (
	<div
		className={`rounded-lg border bg-card p-6 transition-colors ${
			editing ? 'border-magenta-300' : 'border-border'
		} ${className || ''}`}
	>
		{/* Header row: icon + label + action */}
		<div className="flex items-center justify-between mb-4">
			<div className="flex items-center gap-3">
				<div className="flex items-center justify-center w-10 h-10 rounded-full bg-magenta-50">
					{icon}
				</div>
				<span className="label-semibold uppercase tracking-wider text-muted-foreground">
					{label}
				</span>
			</div>
			{action && (
				<button
					type="button"
					onClick={onAction}
					className="small-semibold text-magenta-500 hover:text-magenta-600 transition-colors cursor-pointer"
				>
					{action}
				</button>
			)}
		</div>

		{/* Content */}
		{children}
	</div>
);

/**
 * GoalOption Component
 *
 * Selectable goal row in edit mode.
 */
const GoalOption = ({ title, subtitle, selected, onClick }) => (
	<button
		type="button"
		onClick={onClick}
		className={`w-full flex items-center justify-between rounded-lg border px-4 py-3 text-left transition-all cursor-pointer ${
			selected
				? 'border-magenta-400 bg-magenta-50'
				: 'border-border bg-card hover:border-neutral-300'
		}`}
	>
		<div>
			<p className="small-semibold text-foreground">{title}</p>
			<p className="label-regular text-muted-foreground">
				{subtitle}
			</p>
		</div>
		{selected && (
			<CircleCheck className="w-5 h-5 text-magenta-500 shrink-0 ml-3" />
		)}
	</button>
);

/**
 * GoalProfilePage Component
 *
 * Card-based layout showing goal and business profile info.
 * Inline edit mode persists each field via POST /business-info.
 */
const GoalProfilePage = ({ onBack, transition }) => {
	const config = getWordPressConfig();
	const { data: profile } = useOnboarding();

	// Persist a partial profile update to the backend. Returns true on success.
	const saveProfile = async (patch) => {
		try {
			await post(config.endpoints.businessInfo, patch);
			return true;
		} catch (err) {
			captureException(err, { action: 'update_business_info', payload: patch });
			return false;
		}
	};

	// Goal state
	const [isEditingGoal, setIsEditingGoal] = useState(false);
	const [selectedGoal, setSelectedGoal] = useState(profile.goal);

	// Business description state
	const [isEditingBusiness, setIsEditingBusiness] = useState(false);
	const [businessDraft, setBusinessDraft] = useState(
		profile.businessDescription || ''
	);
	const [businessValue, setBusinessValue] = useState(
		profile.businessDescription || ''
	);

	// Ideal customers state
	const [isEditingCustomers, setIsEditingCustomers] = useState(false);
	const [customersDraft, setCustomersDraft] = useState(
		profile.targetCustomer || ''
	);
	const [customersValue, setCustomersValue] = useState(
		profile.targetCustomer || ''
	);

	// Location state
	const [isEditingLocation, setIsEditingLocation] = useState(false);
	const [locationDraft, setLocationDraft] = useState(profile.location || '');
	const [locationValue, setLocationValue] = useState(profile.location || '');
	const [isLocalDraft, setIsLocalDraft] = useState(profile.isLocal ?? false);
	const [isLocalValue, setIsLocalValue] = useState(profile.isLocal ?? false);
	// Full Google Place object (null for free-text addresses).
	const [locationCompleteDraft, setLocationCompleteDraft] = useState(
		profile.locationComplete || null
	);
	const [locationCompleteValue, setLocationCompleteValue] = useState(
		profile.locationComplete || null
	);

	const goal = getGoalById(selectedGoal);

	const transitionClass =
		transition === 'action-enter'
			? 'animate-slide-in-from-right'
			: transition === 'action-exit'
				? 'animate-slide-out-to-right'
				: '';

	return (
		<main className={`flex-1 pt-8 pb-24 ${transitionClass}`}>
			<div className="max-w-3xl mx-auto px-8">
				<button
					type="button"
					onClick={onBack}
					className="inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors cursor-pointer mb-6"
				>
					<ArrowLeft className="w-4 h-4" />
					Back
				</button>

				{/* Title */}
				<h1 className="heading-h1 leading-tight mb-2">
					About your business
				</h1>
				<p className="paragraph-regular text-muted-foreground mb-8">
					This is what I know about you. If something's wrong, just edit it and I'll adjust.
				</p>

				{/* Cards */}
				<div className="space-y-4">
					{/* Goal card */}
					<ProfileCard
						icon={
							<Crosshair className="w-5 h-5 text-magenta-500" />
						}
						label="Your goal"
						action={isEditingGoal ? 'Cancel' : 'Change'}
						onAction={() => setIsEditingGoal(!isEditingGoal)}
						editing={isEditingGoal}
					>
						{isEditingGoal ? (
							<>
								<p className="paragraph-semibold text-foreground mb-3">
									What's your top priority right now?
								</p>
								<div className="space-y-2">
									{GOAL_OPTIONS.map((option) => (
										<GoalOption
											key={option.id}
											title={option.title}
											subtitle={option.subtitle}
											selected={
												selectedGoal === option.id
											}
											onClick={() => {
												const prev = selectedGoal;
												setSelectedGoal(option.id);
												setIsEditingGoal(false);
												saveProfile({ goal: option.id }).then((ok) => {
													if (!ok) setSelectedGoal(prev);
												});
											}}
										/>
									))}
								</div>
							</>
						) : (
							<>
								<h3 className="heading-h4 mb-1">
									{goal?.title}
								</h3>
								<p className="small-regular text-muted-foreground">
									{goal?.tooltip
										? goal.tooltip.split('.')[0] +
											'.'
										: goal?.description}
								</p>
							</>
						)}
					</ProfileCard>

					{/* Business description card */}
					<ProfileCard
						icon={
							<Store className="w-5 h-5 text-magenta-500" />
						}
						label="What you do"
						action={isEditingBusiness ? 'Cancel' : 'Edit'}
						onAction={() => {
							if (isEditingBusiness) {
								setBusinessDraft(businessValue);
							}
							setIsEditingBusiness(!isEditingBusiness);
						}}
						editing={isEditingBusiness}
					>
						{isEditingBusiness ? (
							<>
								<textarea
									value={businessDraft}
									onChange={(e) =>
										setBusinessDraft(e.target.value)
									}
									rows={4}
									className="w-full rounded-lg border! border-border! bg-neutral-50! px-5! py-4! paragraph-regular text-foreground resize-none focus:outline-none focus:ring-2 focus:ring-ring"
								/>
								<div className="flex items-center justify-between mt-3">
									<p className="label-regular text-muted-foreground">
										Briefly describe what your business
										does and what makes it special.
									</p>
									<Button
										size="sm"
										onClick={async () => {
											const prev = businessValue;
											setBusinessValue(businessDraft);
											setIsEditingBusiness(false);
											const ok = await saveProfile({
												businessDescription: businessDraft,
											});
											if (!ok) setBusinessValue(prev);
										}}
									>
										Save
									</Button>
								</div>
							</>
						) : (
							<p className="paragraph-regular text-foreground">
								{businessValue}
							</p>
						)}
					</ProfileCard>

					{/* Ideal customers card */}
					<ProfileCard
						icon={
							<Users className="w-5 h-5 text-magenta-500" />
						}
						label="Who you serve"
						action={isEditingCustomers ? 'Cancel' : 'Edit'}
						onAction={() => {
							if (isEditingCustomers) {
								setCustomersDraft(customersValue);
							}
							setIsEditingCustomers(!isEditingCustomers);
						}}
						editing={isEditingCustomers}
					>
						{isEditingCustomers ? (
							<>
								<textarea
									value={customersDraft}
									onChange={(e) =>
										setCustomersDraft(e.target.value)
									}
									rows={4}
									className="w-full rounded-lg border! border-border! bg-neutral-50! px-5! py-4! paragraph-regular text-foreground resize-none focus:outline-none focus:ring-2 focus:ring-ring"
								/>
								<div className="flex items-center justify-between mt-3">
									<p className="label-regular text-muted-foreground">
										Describe who your ideal customers
										are and what they're looking for.
									</p>
									<Button
										size="sm"
										onClick={async () => {
											const prev = customersValue;
											setCustomersValue(customersDraft);
											setIsEditingCustomers(false);
											const ok = await saveProfile({
												targetCustomer: customersDraft,
											});
											if (!ok) setCustomersValue(prev);
										}}
									>
										Save
									</Button>
								</div>
							</>
						) : (
							<p className="paragraph-regular text-foreground">
								{customersValue}
							</p>
						)}
					</ProfileCard>

					{/* Location card */}
					{isEditingLocation ? (
						<ProfileCard
							icon={
								<MapPin className="w-5 h-5 text-magenta-500" />
							}
							label="Location"
							action="Cancel"
							onAction={() => {
								setLocationDraft(locationValue);
								setIsLocalDraft(isLocalValue);
								setLocationCompleteDraft(locationCompleteValue);
								setIsEditingLocation(false);
							}}
							editing
						>
							<p className="small-semibold text-foreground mb-2">
								Business address
							</p>
							<AddressAutocompleteInput
								value={locationDraft}
								onChange={(next) => {
									// Manual typing means it's no longer a
									// canonical selection; clear the Place object.
									setLocationDraft(next);
									setLocationCompleteDraft(null);
								}}
								onSelect={(place) => {
									if (place) {
										setLocationCompleteDraft(place);
										setIsLocalDraft(true);
									}
								}}
								placeholder="Start typing your business address…"
							/>
							<label className="flex items-center gap-3 mt-3 cursor-pointer">
								<button
									type="button"
									role="switch"
									aria-checked={isLocalDraft}
									onClick={() =>
										setIsLocalDraft(!isLocalDraft)
									}
									className={`relative inline-flex h-6 w-11 shrink-0 rounded-full transition-colors cursor-pointer ${
										isLocalDraft
											? 'bg-magenta-500'
											: 'bg-neutral-300'
									}`}
								>
									<span
										className={`pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-sm transition-transform mt-0.5 ${
											isLocalDraft
												? 'translate-x-[22px]'
												: 'translate-x-0.5'
										}`}
									/>
								</button>
								<span className="small-regular text-foreground">
									This is a local business
								</span>
							</label>
							<div className="flex items-center justify-between mt-3">
								<p className="label-regular text-muted-foreground">
									Enter your full business address so
									Flavio can optimize for local search.
								</p>
								<Button
									size="sm"
									onClick={async () => {
										const prevLocation = locationValue;
										const prevIsLocal = isLocalValue;
										const prevComplete =
											locationCompleteValue;
										setLocationValue(locationDraft);
										setIsLocalValue(isLocalDraft);
										setLocationCompleteValue(
											locationCompleteDraft
										);
										setIsEditingLocation(false);
										const ok = await saveProfile({
											location: locationDraft,
											isLocal: isLocalDraft,
											locationComplete:
												locationCompleteDraft,
										});
										if (!ok) {
											setLocationValue(prevLocation);
											setIsLocalValue(prevIsLocal);
											setLocationCompleteValue(
												prevComplete
											);
										}
									}}
								>
									Save
								</Button>
							</div>
						</ProfileCard>
					) : (
						<ProfileCard
							icon={
								<MapPin className="w-5 h-5 text-magenta-500" />
							}
							label="Location"
							action="Edit"
							onAction={() => setIsEditingLocation(true)}
						>
							{isLocalValue && (
								<p className="paragraph-semibold text-foreground mb-2">
									{locationValue}
								</p>
							)}
							<span
								className={`inline-flex items-center gap-1.5 text-xs font-medium ${
									isLocalValue
										? 'text-magenta-500'
										: 'text-neutral-400'
								}`}
							>
								<Building2 className="w-3.5 h-3.5" />
								{isLocalValue
									? 'Local business'
									: 'Not a local business'}
							</span>
						</ProfileCard>
					)}
				</div>

				{/* Mascot speech bubble */}
				<div className="flex items-start gap-2 mt-8">
					<img
						src={`${config?.pluginUrl || ''}js/public/onboarding.svg`}
						alt="Flavio"
						className="size-8 shrink-0"
						aria-hidden="true"
					/>
					<SpeechBubble arrow="left" className="ml-2">
						If you change anything here, I'll update my work to match.
					</SpeechBubble>
				</div>
			</div>
		</main>
	);
};

export default GoalProfilePage;
