import { AddOutlined, DeleteOutline, ArrowUpward, ArrowDownward } from "@mui/icons-material";
import {
	Accordion,
	AccordionDetails,
	AccordionSummary,
	Box,
	Button,
	Stack,
	TextField,
	Typography,
} from "@mui/material";
import { useFormikContext } from "formik";
import { useTranslation } from "react-i18next";

import {
	CheckListTemplateItemModel,
	CheckListTemplateModel,
} from "@/contracts/client.schemas";
import { LANGUAGES } from "@/i18n/config";

interface CheckListItemsEditorProps {
	isEdit?: boolean;
}

export const CheckListItemsEditor = ({
	isEdit = false,
}: CheckListItemsEditorProps) => {
	const { values, setFieldValue } =
		useFormikContext<CheckListTemplateModel>();
	const { t } = useTranslation("translation");

	const handleAddItem = () => {
		const newItem: CheckListTemplateItemModel = {
			index: values.items.length,
			translations: LANGUAGES.map((lang) => ({
				languageCode: lang,
				name: "",
				description: "",
			})),
		} as CheckListTemplateItemModel;
		setFieldValue("items", [...values.items, newItem]);
	};

	const handleRemoveItem = (index: number) => {
		const updatedItems = values.items
			.filter((_, i) => i !== index)
			.map((item, i) => ({ ...item, index: i }));
		setFieldValue("items", updatedItems);
	};

	const handleMoveUp = (index: number) => {
		if (index > 0) {
			const updatedItems = [...values.items];
			[updatedItems[index], updatedItems[index - 1]] = [updatedItems[index - 1], updatedItems[index]];
			updatedItems.forEach((item, i) => item.index = i);
			setFieldValue("items", updatedItems);
		}
	};

	const handleMoveDown = (index: number) => {
		if (index < values.items.length - 1) {
			const updatedItems = [...values.items];
			[updatedItems[index], updatedItems[index + 1]] = [updatedItems[index + 1], updatedItems[index]];
			updatedItems.forEach((item, i) => item.index = i);
			setFieldValue("items", updatedItems);
		}
	};

	const handleTranslationChange = (
		itemIndex: number,
		languageCode: string,
		field: "name" | "description",
		value: string,
	) => {
		const updatedItems = [...values.items];
		const translation = updatedItems[itemIndex].translations.find(
			(t) => t.languageCode === languageCode,
		);
		if (translation) {
			translation[field] = value;
			setFieldValue("items", updatedItems);
		}
	};

	return (
		<Stack spacing={2}>
			<Box
				display="flex"
				justifyContent="space-between"
				alignItems="center"
			>
				<Typography variant="h6">Items</Typography>
				{isEdit && (
					<Button
						variant="contained"
						startIcon={<AddOutlined />}
						onClick={handleAddItem}
					>
						{t("Add Item")}
					</Button>
				)}
			</Box>

			{values.items.map((item, itemIndex) => (
				<Accordion key={item.id}>
					<AccordionSummary>
						<Box
							display="flex"
							justifyContent="space-between"
							alignItems="center"
							width="100%"
						>
							<Typography>
								{t("Item #{{index}}", { index: itemIndex + 1 })}
							</Typography>
							{isEdit && (
								<Box display="flex" alignItems="center" gap={1}>
									<Box
										component="span"
										onClick={(e: React.MouseEvent) => {
											e.stopPropagation();
											handleMoveUp(itemIndex);
										}}
										sx={{
											cursor: itemIndex > 0 ? "pointer" : "not-allowed",
											display: "flex",
											alignItems: "center",
											padding: "4px",
											borderRadius: "50%",
											"&:hover": itemIndex > 0 ? {
												backgroundColor: "rgba(0, 0, 0, 0.04)",
											} : {},
											opacity: itemIndex > 0 ? 1 : 0.5,
										}}
									>
										<ArrowUpward fontSize="small" />
									</Box>
									<Box
										component="span"
										onClick={(e: React.MouseEvent) => {
											e.stopPropagation();
											handleMoveDown(itemIndex);
										}}
										sx={{
											cursor: itemIndex < values.items.length - 1 ? "pointer" : "not-allowed",
											display: "flex",
											alignItems: "center",
											padding: "4px",
											borderRadius: "50%",
											"&:hover": itemIndex < values.items.length - 1 ? {
												backgroundColor: "rgba(0, 0, 0, 0.04)",
											} : {},
											opacity: itemIndex < values.items.length - 1 ? 1 : 0.5,
										}}
									>
										<ArrowDownward fontSize="small" />
									</Box>
									<Box
										component="span"
										onClick={(e: React.MouseEvent) => {
											e.stopPropagation();
											handleRemoveItem(itemIndex);
										}}
										sx={{
											cursor: "pointer",
											display: "flex",
											alignItems: "center",
											padding: "4px",
											borderRadius: "50%",
											"&:hover": {
												backgroundColor:
													"rgba(0, 0, 0, 0.04)",
											},
										}}
									>
										<DeleteOutline fontSize="small" />
									</Box>
								</Box>
							)}
						</Box>
					</AccordionSummary>
					<AccordionDetails>
						<Stack spacing={2}>
							<Typography variant="subtitle1">
								{t("Translations")}
							</Typography>

							{LANGUAGES.map((lang) => {
								const translation = item.translations.find(
									(t) => t.languageCode === lang,
								);
								return (
									<Box
										key={lang}
										sx={{
											p: 2,
											border: "1px solid #e0e0e0",
											borderRadius: 1,
										}}
									>
										<Stack spacing={2}>
											<Typography
												variant="body2"
												fontWeight="bold"
											>
												{lang.toUpperCase()}
											</Typography>
											<TextField
												label={t("name")}
												fullWidth
												size="small"
												value={translation?.name || ""}
												disabled={!isEdit}
												onChange={(e) =>
													handleTranslationChange(
														itemIndex,
														lang,
														"name",
														e.target.value,
													)
												}
											/>
											<TextField
												label={t("description")}
												fullWidth
												size="small"
												multiline
												rows={2}
												value={
													translation?.description ||
													""
												}
												disabled={!isEdit}
												onChange={(e) =>
													handleTranslationChange(
														itemIndex,
														lang,
														"description",
														e.target.value,
													)
												}
											/>
										</Stack>
									</Box>
								);
							})}
						</Stack>
					</AccordionDetails>
				</Accordion>
			))}
		</Stack>
	);
};
