import { Square, CheckSquare } from "lucide-react";
import { FC, useEffect } from "react";
import { useTranslation } from "react-i18next";

import {
	useGetCheckListByAlarmScope,
	useCheckCheckListItem,
	useUncheckCheckListItem,
} from "@/contracts/check-list";
import { useGetCheckListTemplateById } from "@/contracts/check-list-template";
import { CheckListType } from "@/contracts/client.schemas";

import { useCheckListStatus } from "../../lib/useCheckListStatus";

const alarmColors = {
	bgColor: "bg-red-50",
	borderColor: "border-red-200",
	hoverColor: "hover:bg-red-100",
	textColor: "text-red-900",
};
const falseAlarmColors = {
	bgColor: "bg-yellow-50",
	borderColor: "border-yellow-200",
	hoverColor: "hover:bg-yellow-100",
	textColor: "text-yellow-900",
};

function getColors(type: CheckListType) {
	if (type === CheckListType.ByFalseAlarm) {
		return falseAlarmColors;
	}
	return alarmColors;
}

type CheckListWidgetProps = {
	alarmScopeId: string;
	type: CheckListType;
	onChange: (allChecked: boolean) => void;
};

export const CheckListWidget: FC<CheckListWidgetProps> = ({
	alarmScopeId,
	type,
	onChange,
}) => {
	const { i18n, t } = useTranslation();

	const mutationConfig = {
		mutation: {
			onSuccess: () => refetchCheckList(),
		},
	};
	const checkItem = useCheckCheckListItem(mutationConfig);
	const uncheckItem = useUncheckCheckListItem(mutationConfig);

	const { data: checkList, refetch: refetchCheckList } =
		useGetCheckListByAlarmScope(alarmScopeId);

	const checkListTemplateId = checkList?.templateId;
	const { data: template } = useGetCheckListTemplateById(
		checkListTemplateId!,
		{
			query: {
				enabled: !!checkListTemplateId,
			},
		},
	);

	const allItemsChecked = useCheckListStatus(checkList);
	useEffect(() => {
		onChange(allItemsChecked);
	}, [allItemsChecked, onChange]);

	const handleToggleCheckListItem = async (
		itemId: string,
		isChecked: boolean,
	) => {
		try {
			if (isChecked) {
				await uncheckItem.mutateAsync({ itemId });
			} else {
				await checkItem.mutateAsync({ itemId });
			}
			await refetchCheckList();
		} catch (error) {
			console.error("Failed to toggle checklist item", error);
		}
	};

	if (!checkList || !template) {
		return null;
	}

	const colors = getColors(type);

	return (
		<div
			className={`${colors.bgColor} border ${colors.borderColor} rounded-lg p-4`}
		>
			<p className={`text-sm font-medium mb-3 ${colors.textColor}`}>
				{t("operatorActions")}
			</p>
			<div className="space-y-2">
				{checkList.items.map((item, index) => {
					const templateItem = template?.items.find(
						(x) => x.id === item.templateItemId,
					);
					const translation =
						templateItem?.translations.find(
							(tr) => tr.languageCode === i18n.language,
						) || templateItem?.translations[0];

					return (
						<button
							key={item.id}
							onClick={() =>
								handleToggleCheckListItem(
									item.id,
									item.isChecked,
								)
							}
							className={`flex items-center gap-3 w-full p-2 rounded ${colors.hoverColor} transition-colors text-left`}
						>
							{item.isChecked ? (
								<CheckSquare className="w-5 h-5 text-green-600 flex-shrink-0" />
							) : (
								<Square className="w-5 h-5 text-gray-400 flex-shrink-0" />
							)}
							<span
								className={
									item.isChecked
										? "text-gray-500 line-through"
										: "text-gray-900"
								}
							>
								{index + 1}.{" "}
								{translation?.name || t("defaultCheckListItem")}
							</span>
						</button>
					);
				})}
			</div>
		</div>
	);
};

export interface CheckListItem {
	isChecked: boolean;
}

export interface CheckListData {
	items?: CheckListItem[];
}
