"use client";

import { useSafeIntl } from "@kopexa/i18n";
import { CheckCirleIcon, EditIcon } from "@kopexa/icons";
import {
	Button,
	Card,
	Chip,
	Heading,
	Separator,
	Textarea,
} from "@kopexa/sight";
import { useState } from "react";
import { messages } from "./messages";
import type { RiskTreatment, RiskTreatmentValue } from "./types";

// ============================================
// Types
// ============================================

export interface RiskTreatmentCardProps {
	/** The current treatment value */
	value?: RiskTreatmentValue;
	/** Callback when the treatment changes */
	onChange?: (value: RiskTreatmentValue) => void;
	/** Make the component read-only */
	readOnly?: boolean;
	/** Custom title for the card */
	title?: string;
	/** Recommended treatment based on risk level */
	recommended?: RiskTreatment;
}

// ============================================
// Treatment Option Component
// ============================================

interface TreatmentOptionProps {
	id: RiskTreatment;
	label: string;
	description: string;
	hint?: string;
	isSelected: boolean;
	isRecommended: boolean;
	recommendedLabel: string;
	onSelect: (id: RiskTreatment) => void;
}

function TreatmentOption({
	id,
	label,
	description,
	hint,
	isSelected,
	isRecommended,
	recommendedLabel,
	onSelect,
}: TreatmentOptionProps) {
	return (
		<button
			type="button"
			onClick={() => onSelect(id)}
			className={`
				w-full text-left p-4 rounded-lg border-2 transition-all
				${
					isSelected
						? "border-primary bg-primary/5"
						: "border-border hover:border-primary/50 hover:bg-muted/50"
				}
			`}
		>
			<div className="flex items-start gap-3">
				{/* Radio indicator */}
				<div
					className={`
						mt-0.5 size-5 rounded-full border-2 flex items-center justify-center flex-shrink-0
						${isSelected ? "border-primary bg-primary" : "border-muted-foreground"}
					`}
				>
					{isSelected && (
						<div className="size-2 rounded-full bg-primary-foreground" />
					)}
				</div>

				{/* Content */}
				<div className="flex-1 min-w-0">
					<div className="flex items-center gap-2 flex-wrap">
						<span className="font-medium">{label}</span>
						{isRecommended && (
							<Chip size="sm" color="success" variant="flat">
								{recommendedLabel}
							</Chip>
						)}
					</div>
					<p className="text-sm text-muted-foreground mt-1">{description}</p>
					{hint && (
						<p className="text-xs text-muted-foreground mt-2 flex items-center gap-1">
							<span className="text-primary">→</span>
							{hint}
						</p>
					)}
				</div>
			</div>
		</button>
	);
}

// ============================================
// Main Component
// ============================================

const defaultValue: RiskTreatmentValue = {
	treatment: "not_defined",
	rationale: undefined,
};

export function RiskTreatmentCard({
	value,
	onChange,
	readOnly = false,
	title,
	recommended,
}: RiskTreatmentCardProps) {
	const intl = useSafeIntl();
	const [isEditing, setIsEditing] = useState(false);
	const [editValues, setEditValues] = useState<RiskTreatmentValue>(
		value || defaultValue,
	);

	// i18n labels
	const t = {
		title: intl.formatMessage(messages.title),
		strategyLabel: intl.formatMessage(messages.strategy_label),
		strategyPrompt: intl.formatMessage(messages.strategy_prompt),
		rationaleLabel: intl.formatMessage(messages.rationale_label),
		rationalePlaceholder: intl.formatMessage(messages.rationale_placeholder),
		noRationale: intl.formatMessage(messages.no_rationale),
		edit: intl.formatMessage(messages.edit),
		cancel: intl.formatMessage(messages.cancel),
		save: intl.formatMessage(messages.save),
		recommended: intl.formatMessage(messages.recommended),
		// Treatment labels
		acceptLabel: intl.formatMessage(messages.accept_label),
		mitigateLabel: intl.formatMessage(messages.mitigate_label),
		transferLabel: intl.formatMessage(messages.transfer_label),
		avoidLabel: intl.formatMessage(messages.avoid_label),
		notDefinedLabel: intl.formatMessage(messages.not_defined_label),
		// Treatment descriptions
		acceptDescription: intl.formatMessage(messages.accept_description),
		mitigateDescription: intl.formatMessage(messages.mitigate_description),
		transferDescription: intl.formatMessage(messages.transfer_description),
		avoidDescription: intl.formatMessage(messages.avoid_description),
		// Treatment hints
		acceptHint: intl.formatMessage(messages.accept_hint),
		mitigateHint: intl.formatMessage(messages.mitigate_hint),
		transferHint: intl.formatMessage(messages.transfer_hint),
		avoidHint: intl.formatMessage(messages.avoid_hint),
	};

	const treatmentLabels: Record<RiskTreatment, string> = {
		accept: t.acceptLabel,
		mitigate: t.mitigateLabel,
		transfer: t.transferLabel,
		avoid: t.avoidLabel,
		not_defined: t.notDefinedLabel,
	};

	const treatmentOptions: Array<{
		id: RiskTreatment;
		label: string;
		description: string;
		hint: string;
	}> = [
		{
			id: "accept",
			label: t.acceptLabel,
			description: t.acceptDescription,
			hint: t.acceptHint,
		},
		{
			id: "mitigate",
			label: t.mitigateLabel,
			description: t.mitigateDescription,
			hint: t.mitigateHint,
		},
		{
			id: "transfer",
			label: t.transferLabel,
			description: t.transferDescription,
			hint: t.transferHint,
		},
		{
			id: "avoid",
			label: t.avoidLabel,
			description: t.avoidDescription,
			hint: t.avoidHint,
		},
	];

	const cardTitle = title ?? t.title;
	const currentValue = isEditing ? editValues : value || defaultValue;
	const isNotDefined = currentValue.treatment === "not_defined";

	const handleSave = () => {
		onChange?.(editValues);
		setIsEditing(false);
	};

	const handleCancel = () => {
		setEditValues(value || defaultValue);
		setIsEditing(false);
	};

	const handleStartEdit = () => {
		setEditValues(value || defaultValue);
		setIsEditing(true);
	};

	const handleTreatmentSelect = (treatment: RiskTreatment) => {
		setEditValues((prev) => ({ ...prev, treatment }));
	};

	const handleRationaleChange = (rationale: string) => {
		setEditValues((prev) => ({ ...prev, rationale: rationale || undefined }));
	};

	return (
		<Card.Root variant="accent">
			<Card.Header className="flex flex-row items-center justify-between">
				<div className="flex items-center gap-2">
					<Heading level="h3" className="text-base">
						{cardTitle}
					</Heading>
					{isEditing && (
						<Chip size="sm" color="primary">
							{t.edit}
						</Chip>
					)}
				</div>
				{!readOnly &&
					(!isEditing ? (
						<Button
							variant="ghost"
							size="sm"
							isIconOnly
							onClick={handleStartEdit}
							aria-label={t.edit}
						>
							<EditIcon className="size-4" />
						</Button>
					) : (
						<div className="flex items-center gap-2">
							<Button variant="ghost" size="sm" onClick={handleCancel}>
								{t.cancel}
							</Button>
							<Button size="sm" onClick={handleSave}>
								{t.save}
							</Button>
						</div>
					))}
			</Card.Header>

			<Card.Body className="space-y-4">
				{isEditing ? (
					<>
						{/* Edit Mode: Treatment Selection */}
						<div className="space-y-3">
							<p className="text-sm text-muted-foreground">
								{t.strategyPrompt}
							</p>
							<div className="grid gap-3">
								{treatmentOptions.map((option) => (
									<TreatmentOption
										key={option.id}
										id={option.id}
										label={option.label}
										description={option.description}
										hint={option.hint}
										isSelected={editValues.treatment === option.id}
										isRecommended={recommended === option.id}
										recommendedLabel={t.recommended}
										onSelect={handleTreatmentSelect}
									/>
								))}
							</div>
						</div>

						<Separator />

						{/* Edit Mode: Rationale */}
						<div className="space-y-2">
							<label
								htmlFor="treatment-rationale"
								className="text-sm font-medium"
							>
								{t.rationaleLabel}
							</label>
							<Textarea
								id="treatment-rationale"
								value={editValues.rationale || ""}
								onChange={(e) => handleRationaleChange(e.target.value)}
								placeholder={t.rationalePlaceholder}
								rows={3}
								className="text-sm"
							/>
						</div>
					</>
				) : (
					<>
						{/* View Mode: Selected Strategy */}
						<div>
							<p className="text-sm font-medium mb-1">{t.strategyLabel}</p>
							<div className="flex items-center gap-2">
								{!isNotDefined && (
									<CheckCirleIcon className="size-4 text-success" />
								)}
								<p
									className={`text-sm ${isNotDefined ? "text-muted-foreground" : ""}`}
								>
									{treatmentLabels[currentValue.treatment]}
								</p>
							</div>
						</div>

						<Separator />

						{/* View Mode: Rationale */}
						<div>
							<p className="text-sm font-medium mb-1">{t.rationaleLabel}</p>
							<p className="text-sm text-muted-foreground">
								{currentValue.rationale || t.noRationale}
							</p>
						</div>
					</>
				)}
			</Card.Body>
		</Card.Root>
	);
}
