import React, { useState, useEffect } from "react";
import { useParams, useNavigate, useSearchParams } from "react-router-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { ArrowLeft, Plus, Trash2, GripVertical, LoaderCircle, AlertCircle } from "lucide-react";
import { ReactSortable } from "react-sortablejs";
import StatusBadge from "../common/StatusBadge";
import { __ } from "@wordpress/i18n";

/**
 * EditPoll - Page for editing a poll
 */
export const EditPoll = ({
	polls,
	handleSavePoll,
	handlePollChange,
	handleOptionChange,
	addOption,
	removeOption,
	handleOptionSort,
	setEditedPoll,
	editedPoll,
}) => {
	const { pollId } = useParams();
	const navigate = useNavigate();
	const [searchParams] = useSearchParams();
	const [isLoading, setIsLoading] = useState(false);
	const [poll, setPoll] = useState(null);

	// Find the poll by ID and set it up for editing
	useEffect(() => {
		if (polls && pollId) {
			const foundPoll = polls.find((p) => p.id.toString() === pollId);
			if (foundPoll) {
				setPoll(foundPoll);
				setEditedPoll({ ...foundPoll });
			} else {
				// Poll not found, redirect to main page
				navigate("/");
			}
		}
	}, [polls, pollId, navigate, setEditedPoll]);

	const handleBackClick = () => {
		navigate(-1);
	};

	const handleSave = async () => {
		if (!editedPoll.name || editedPoll.options.some((opt) => !opt.option_text)) {
			return;
		}

		setIsLoading(true);
		try {
			const savedPoll = await handleSavePoll();
			// Update the local poll state with the saved data to reflect published status
			if (savedPoll) {
				setPoll(savedPoll);
			}
			// Navigate back to dashboard with preserved pagination
			const params = searchParams.toString();
			navigate(`/${params ? `?${params}` : ''}`);
		} catch (error) {
			console.error("Error saving poll:", error);
			// Error is already handled by the hook (toast shown)
		} finally {
			setIsLoading(false);
		}
	};

	if (!poll || !editedPoll) {
		return (
			<div className="flex justify-center items-center h-64">
				<LoaderCircle className="animate-spin h-8 w-8 text-primary" />
			</div>
		);
	}

	return (
		<div className="socialpoll-admin-app mt-5 mr-5 ml-1">
			<div className="bg-white p-5 rounded-xl flex flex-col gap-5">
				{/* Header with back button */}
				<div className="flex items-center gap-4">
					<Button variant="outline" size="icon" onClick={handleBackClick}>
						<ArrowLeft />
					</Button>
					<div>
						<h1 className="!text-2xl font-bold !mb-0 !mt-0">
							{__("Edit Poll", "socialpoll")} - {poll.name}
						</h1>
					</div>
				</div>

				{/* Edit form */}
				<div className="grid gap-6 max-w-2xl">
					<div className="grid grid-cols-4 items-center gap-4">
						<Label htmlFor="name" className="text-right">
							{__("Question", "socialpoll")}
						</Label>
						<Input
							id="name"
							value={editedPoll.name}
							onChange={(e) => handlePollChange("name", e.target.value)}
							className="col-span-3"
							disabled={editedPoll.is_published}
						/>
					</div>

					<div className="grid grid-cols-4 items-center gap-4">
						<Label htmlFor="description" className="text-right">
							{__("Description", "socialpoll")}
						</Label>
						<Textarea
							id="description"
							value={editedPoll.description}
							onChange={(e) => handlePollChange("description", e.target.value)}
							className="col-span-3"
							disabled={editedPoll.is_published}
						/>
					</div>

					<div className="grid grid-cols-4 items-center gap-4">
						<Label htmlFor="visibility_status" className="text-right">
							{__("Visibility Status", "socialpoll")}
						</Label>
						<Select
							value={editedPoll.visibility_status || editedPoll.status}
							onValueChange={(value) => handlePollChange("visibility_status", value)}
							className="col-span-3">
							<SelectTrigger className="col-span-3 w-full">
								<SelectValue placeholder={__("Select visibility status", "socialpoll")} />
							</SelectTrigger>
							<SelectContent>
								<SelectItem value="visible">{__("Visible", "socialpoll")}</SelectItem>
								<SelectItem value="hidden">{__("Hidden", "socialpoll")}</SelectItem>
							</SelectContent>
						</Select>
					</div>

					<div className="grid grid-cols-4 items-start gap-4 p-4 bg-yellow-50 rounded-lg border !border-yellow-200">
						<Label className="text-right font-semibold text-yellow-900">{__("Publish Poll", "socialpoll")}</Label>
						<div className="col-span-3 space-y-3">
							<div className="flex items-center space-x-3">
								<Switch
									id="is_published"
									checked={editedPoll.is_published || false}
									onCheckedChange={(checked) => handlePollChange("is_published", checked)}
									disabled={poll.is_published}
								/>
								<Label htmlFor="is_published" className="text-sm font-medium">
									{poll.is_published ? __("Published", "socialpoll") : __("Publish on Save", "socialpoll")}
								</Label>
							</div>
							{poll.is_published && (
								<div className="text-sm text-yellow-900 font-semibold">
									{__("Published on", "socialpoll")} {new Date(poll.published_date).toLocaleString()}
								</div>
							)}
							<div className="flex items-start space-x-3 text-sm text-yellow-900">
								<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
								<div className="space-y-2">
									<p className="font-semibold !mt-0">
										{__(
											"Once published, the poll question and options cannot be edited to maintain data integrity.",
											"socialpoll"
										)}
									</p>
									<p>
										{__(
											"Published polls are locked from editing to prevent vote manipulation. Only visibility can be changed.",
											"socialpoll"
										)}
									</p>
								</div>
							</div>
						</div>
					</div>

					<div className="grid grid-cols-4 items-center gap-4 mt-3">
						<Label className="text-right col-span-4 font-bold">{__("Poll Options", "socialpoll")}</Label>
					</div>

					<ReactSortable
						list={editedPoll.options}
						setList={(newState) => handleOptionSort(newState)}
						handle=".drag-handle"
						animation={150}
						className="space-y-2">
						{editedPoll.options.map((option, index) => (
							<div key={option.id} className="grid grid-cols-[24px_1fr_32px] items-center gap-2 py-1">
								<div className="flex items-center">
									<div className="drag-handle cursor-grab mr-1">
										<GripVertical className="h-5 w-5 text-gray-400" />
									</div>
								</div>
								<Input
									value={option.option_text}
									onChange={(e) => handleOptionChange(index, "option_text", e.target.value)}
									className=""
									placeholder={__("Option name", "socialpoll")}
									disabled={editedPoll.is_published}
								/>
								<div className="flex justify-end gap-1">
									<Button
										variant="ghost"
										size="icon"
										onClick={() => removeOption(index, false)}
										className="h-8 w-8"
										disabled={editedPoll.options.length <= 1 || editedPoll.is_published}>
										<Trash2 className="h-4 w-4 text-red-500" />
									</Button>
								</div>
							</div>
						))}
					</ReactSortable>

					<Button
						variant="outline"
						onClick={() => addOption(false)}
						className="flex items-center justify-center gap-2 max-w-fit"
						disabled={editedPoll.is_published}>
						<Plus className="h-4 w-4" /> {__("Add Option", "socialpoll")}
					</Button>
				</div>

				{/* Action buttons */}
				<div className="flex gap-3">
					<Button variant="outline" onClick={handleBackClick}>
						{__("Cancel", "socialpoll")}
					</Button>
					<Button onClick={handleSave} disabled={isLoading}>
						{isLoading && <LoaderCircle className="animate-spin mr-2" />}
						{isLoading ? __("Saving...", "socialpoll") : __("Save Poll", "socialpoll")}
					</Button>
				</div>
			</div>
		</div>
	);
};

export default EditPoll;
