import {
	Box,
	Button, Dialog, DialogActions, DialogContent,
	DialogContentText,
	DialogTitle,
	IconButton,
	Link,
	Paper,
	Radio,
	Table,
	TableBody,
	TableCell,
	TableContainer,
	TableHead,
	TableRow,
	TextField,
	Typography
} from "@mui/material";
import {useMutation, useQueryClient, useSuspenseQuery} from "@tanstack/react-query";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import {useEffect, useState} from "react";
import PDFViewer from "../components/pdfViewer";
import { kpiQueryOptions } from "../util/query";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import {fetchPutKPI} from "../util/api";
import { redirect } from "@tanstack/react-router";

export const Route = createFileRoute("/extractedResult_/$pitchBook/$kpi")({
	component: ExtractedResultsPage,
	loader: async ({ context: { queryClient }, params: { pitchBook } }) => {
		try {
			return await queryClient.ensureQueryData(kpiQueryOptions(pitchBook));
		} catch (err) {
			throw redirect({
				to: "/"
			});
		}
	},
});

function ExtractedResultsPage() {
	const params = Route.useParams() as { pitchBook: string; kpi: string };
	const { pitchBook, kpi } = params;
	const navigate = useNavigate();
	const queryClient = useQueryClient();

	const {
		data: kpiData
	} = useSuspenseQuery(kpiQueryOptions(pitchBook));

	const kpiValues = kpiData[kpi.toUpperCase()] || [];
	const [selectedIndex, setSelectedIndex] = useState(0);
	const [currentPage, setCurrentPage] = useState(kpiValues[0]?.page || 1);
	const [showConfirmDialog, setShowConfirmDialog] = useState(false);
	const [hasChanges, setHasChanges] = useState(false);
	const [customValue, setCustomValue] = useState('');
	const originalValue = kpiValues[0]?.entity || '';
	const selectedValue = selectedIndex === -1 ? customValue : (kpiValues[selectedIndex]?.entity || '');

	useEffect(() => {
		setHasChanges(selectedValue !== originalValue);
	}, [selectedValue, originalValue]);

	const { mutate: updateKPI } = useMutation({
		mutationFn: () => {
			const updatedData = { ...kpiData };
			updatedData[kpi.toUpperCase()] = [{
				...kpiValues[0],
				entity: selectedValue
			}];
			return fetchPutKPI(Number(pitchBook), updatedData);
		},
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: ["pitchBookKPI", pitchBook],
			});
			navigate({
				to: "/extractedResult/$pitchBook",
				params: { pitchBook }
			});
		},
		onError: (error) => {
			console.error('Error updating KPI:', error);
		}
	});

	const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
		const value = event.target.value;
		if (value === 'custom') {
			setSelectedIndex(-1);
		} else {
			const index = parseInt(value);
			setSelectedIndex(index);
			setCustomValue('');
		}
	};

	const handleCustomValueChange = (event: React.ChangeEvent<HTMLInputElement>) => {
		const value = event.target.value;
		setCustomValue(value);
		setSelectedIndex(-1);
	};

	const handleRowClick = (index: number) => {
		setSelectedIndex(index);
		setCustomValue('');
	};

	const handleBackClick = () => {
		if (hasChanges) {
			setShowConfirmDialog(true);
		} else {
			navigate({
				to: "/extractedResult/$pitchBook",
				params: { pitchBook }
			});
		}
	};

	const handleConfirmDiscard = () => {
		setShowConfirmDialog(false);
		navigate({
			to: "/extractedResult/$pitchBook",
			params: { pitchBook }
		});
	};

	const handleCancelDiscard = () => {
		setShowConfirmDialog(false);
	};

	const handleAcceptReview = () => {
		updateKPI();
	};

	return (
		<Box p={4}>
			<Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
				<IconButton onClick={handleBackClick} sx={{ mr: 2 }}>
					<ArrowBackIcon fontSize="large" sx={{ color: '#383838' }} />
				</IconButton>
				<Typography variant="h5" fontWeight="bold">
					Überprüfung der Kennzahl: {kpi}
				</Typography>
			</Box>

			<Box
				display="flex"
				gap={4}
				sx={{
					width: "100vw",
					maxWidth: "100%",
					height: "85vh",
					mt: 4,
				}}
			>
				<Paper
					elevation={2}
					sx={{
						width: "45%",
						maxHeight: "100%",
						height: "fit-content",
						borderRadius: 2,
						backgroundColor: "#eeeeee",
						padding: 2,
						overflow: "auto",
					}}
				>
					<TableContainer component={Paper}>
						<Table>
							<TableHead>
								<TableRow>
									<TableCell>
										<strong>Gefundene Werte</strong>
									</TableCell>
									<TableCell align="center">
										<strong>Seite</strong>
									</TableCell>
								</TableRow>
							</TableHead>
							<TableBody>
								{kpiValues.map((item, index) => (
									<TableRow
										key={`${item.entity}_${item.page}_${index}`}
										sx={{
											'&:hover': { backgroundColor: '#f9f9f9' },
											cursor: 'pointer'
										}}
										onClick={() => handleRowClick(index)}
									>
										<TableCell>
											<Box
												sx={{
													borderRadius: 1,
													padding: '4px 8px',
													display: 'flex',
													alignItems: 'center',
													width: '100%',
													cursor: 'pointer',
													'&:hover': {
														borderColor: '#ccc'
													}
												}}
											>
												<Radio
													value={index.toString()}
													checked={selectedIndex === index}
													onChange={handleRadioChange}
													sx={{
														color: '#383838',
														'&.Mui-checked': { color: '#383838' },
														padding: '4px',
														marginRight: 1,
														'&:focus': {
															outline: 'none'
														}
													}}
												/>
												<span>{item.entity}</span>
											</Box>
										</TableCell>
										<TableCell align="center">
											<Link
												component="button"
												onClick={(e: React.MouseEvent) => {
													e.stopPropagation();
													setCurrentPage(item.page);
												}}
												sx={{ cursor: 'pointer' }}
											>
												{item.page}
											</Link>
										</TableCell>
									</TableRow>
								))}

								<TableRow>
									<TableCell>
										<Box
											sx={{
												padding: '4px 8px',
												display: 'flex',
												alignItems: 'center',
												width: '100%',
												cursor: 'pointer',
												'&:hover': {
													borderColor: '#ccc'
												}
											}}
											onClick={() => {
												setSelectedIndex(-1);
											}}
										>
											<Radio
												value="custom"
												checked={selectedIndex === -1 && customValue !== ''}
												onChange={handleRadioChange}
												sx={{
													color: '#383838',
													'&.Mui-checked': { color: '#383838' },
													padding: '4px',
													marginRight: 1,
													'&:focus': {
														outline: 'none'
													}
												}}
											/>
											<TextField
												placeholder="Einen abweichenden Wert eingeben..."
												value={customValue}
												onChange={handleCustomValueChange}
												variant="standard"
												fullWidth
												InputProps={{
													disableUnderline: true,
												}}
												sx={{
													'& .MuiInput-input': {
														padding: 0,
													}
												}}
												onClick={(e: React.MouseEvent) => {
													e.stopPropagation();
												}}
											/>
										</Box>
									</TableCell>
								</TableRow>
							</TableBody>
						</Table>
					</TableContainer>
				</Paper>
				<Box
					display="flex"
					flexDirection="column"
					justifyContent="space-between"
					gap={3}
					sx={{ width: "55%", height: "95%" }}
				>
					<Paper
						elevation={2}
						sx={{
							width: "100%",
							height: "fit-content",
							maxHeight: "100%",
							borderRadius: 2,
							backgroundColor: "#eeeeee",
							display: "flex",
							flexDirection: "column",
							overflow: "auto",
							padding: 2
						}}
					>
						<PDFViewer
							pitchBookId={pitchBook}
							currentPage={currentPage}
							onPageChange={setCurrentPage}
						/>
					</Paper>
					<Box mt={2} display="flex" justifyContent="flex-end" gap={2}>
						<Button
							variant="contained"
							onClick={handleAcceptReview}
							disabled={!selectedValue}
							sx={{
								backgroundColor: '#383838',
								'&:hover': { backgroundColor: '#2e2e2e' },
								'&.Mui-disabled': { backgroundColor: '#ccc' }
							}}
						>
							Überprüfung Annehmen
						</Button>
					</Box>
				</Box>
			</Box>

			<Dialog
				open={showConfirmDialog}
				onClose={handleCancelDiscard}
				maxWidth="sm"
				fullWidth
			>
				<DialogTitle sx={{ fontSize: '1.25rem', fontWeight: 'bold' }}>
					Achtung
				</DialogTitle>
				<DialogContent>
					<DialogContentText sx={{ fontSize: '1rem' }}>
						Alle vorgenommenen Änderungen werden verworfen.
					</DialogContentText>
				</DialogContent>
				<DialogActions sx={{ p: 3, gap: 2 }}>
					<Button
						onClick={handleCancelDiscard}
						variant="outlined"
						sx={{
							color: '#666',
							borderColor: '#ddd',
							'&:hover': { backgroundColor: '#f5f5f5' }
						}}
					>
						Abbrechen
					</Button>
					<Button
						onClick={handleConfirmDiscard}
						variant="contained"
						sx={{
							backgroundColor: '#383838',
							'&:hover': { backgroundColor: '#2e2e2e' }
						}}
					>
						Bestätigen
					</Button>
				</DialogActions>
			</Dialog>
		</Box>
	);
}