import React, { useState, useEffect } from "react";
import { 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 { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { ArrowLeft, Plus, Trash2, GripVertical, LoaderCircle, AlertCircle } from "lucide-react";
import { ReactSortable } from "react-sortablejs";
import { __ } from "@wordpress/i18n";

/**
 * CreatePoll - Page for creating a new poll
 */
export const CreatePoll = ({
	handleCreatePoll,
	handlePollChange,
	handleOptionChange,
	addOption,
	removeOption,
	handleOptionSort,
	newPoll,
	setNewPoll,
}) => {
	const navigate = useNavigate();
	const [searchParams] = useSearchParams();
	const [isLoading, setIsLoading] = useState(false);

	// Initialize new poll when component mounts
	useEffect(() => {
		// Reset the poll when navigating to create page
		if (!newPoll || !newPoll.name) {
			// The newPoll should already be initialized by the hook
		}
	}, [newPoll]);

	const handleBackClick = () => {
		const params = searchParams.toString();
		navigate(`/${params ? `?${params}` : ''}`);
	};

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

		setIsLoading(true);
		try {
			await handleCreatePoll();
			// Navigate back to dashboard with preserved pagination
			const params = searchParams.toString();
			navigate(`/${params ? `?${params}` : ''}`);
		} catch (error) {
			console.error("Error creating poll:", error);
			// Error is already handled by the hook (toast shown)
		} finally {
			setIsLoading(false);
		}
	};

	if (!newPoll) {
		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">{__("Create New Poll", "socialpoll")}</h1>
					</div>
				</div>

				{/* Create form */}
				<div className="grid gap-6 max-w-2xl">
					<div className="grid grid-cols-4 items-center gap-4">
						<Label htmlFor="new-name" className="text-right">
							{__("Poll Question", "socialpoll")}
						</Label>
						<Input
							id="new-name"
							value={newPoll.name}
							onChange={(e) => handlePollChange("name", e.target.value, true)}
							className="col-span-3"
							placeholder={__("Enter poll name", "socialpoll")}
						/>
					</div>

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

					<div className="grid grid-cols-4 items-center gap-4">
						<Label htmlFor="new-visibility_status" className="text-right">
							{__("Visibility Status", "socialpoll")}
						</Label>
						<Select
							value={newPoll.visibility_status || "hidden"}
							onValueChange={(value) => handlePollChange("visibility_status", value, true)}
							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="new_is_published"
									checked={newPoll.is_published || false}
									onCheckedChange={(checked) => handlePollChange("is_published", checked, true)}
								/>
								<Label htmlFor="new_is_published" className="text-sm font-medium">
									{__("Publish on Save", "socialpoll")}
								</Label>
							</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={newPoll.options}
						setList={(newState) => handleOptionSort(newState, true)}
						handle=".drag-handle"
						animation={150}
						className="space-y-2">
						{newPoll.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, true)}
									className=""
									placeholder={__("Option name", "socialpoll")}
								/>
								<div className="flex justify-end gap-1">
									<Button
										variant="ghost"
										size="icon"
										onClick={() => removeOption(index, true)}
										className="h-8 w-8"
										disabled={newPoll.options.length <= 1}>
										<Trash2 className="h-4 w-4 text-red-500" />
									</Button>
								</div>
							</div>
						))}
					</ReactSortable>

					<Button
						variant="outline"
						onClick={() => addOption(true)}
						className="flex items-center justify-center gap-2 max-w-fit">
						<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={handleCreate}
						disabled={!newPoll.name || newPoll.options.some((opt) => !opt.option_text) || isLoading}>
						{isLoading && <LoaderCircle className="animate-spin mr-2" />}
						{isLoading ? __("Creating...", "socialpoll") : __("Create Poll", "socialpoll")}
					</Button>
				</div>
			</div>
		</div>
	);
};

export default CreatePoll;
