"use client";
import React, { useState, useEffect } from "react";
import { Button, Input, Select, Card, useToast } from "@/components";
import { FaTimes } from "react-icons/fa";
import Link from "next/link";
import { useRouter, useParams } from "next/navigation";
import { useUpdateLeaveMutation, useGetLeaveQuery } from "@/store/api/leaveApi";

const statusOptions = [
	{ value: "1", label: "Active" },
	{ value: "0", label: "Inactive" },
];

const EditLeavePage = () => {
	const toast = useToast();
	const router = useRouter();
	const params = useParams();
	const leaveId = params?.id;

	const [updateLeave] = useUpdateLeaveMutation();
	const { data: editData, isLoading: editLoading } = useGetLeaveQuery(leaveId);

	const [formData, setFormData] = useState({
		title: "",
		note: "",
		status: "0",
	});

	useEffect(() => {
		if (editData?.leaves) {
			setFormData({
				title: editData.leaves.title || "",
				note: editData.leaves.note || "",
				status: editData.leaves.status?.toString() || "0",
			});
		}
	}, [editData]);

	const handleInputChange = (e) => {
		const { name, value } = e.target;
		setFormData((prev) => ({ ...prev, [name]: value }));
	};

	const handleSubmit = async (e) => {
		e.preventDefault();
		if (!formData.title || !formData.note) {
			toast.showToast({
				title: "Validation Error",
				description: "Please fill all required fields",
				status: "error",
			});
			return;
		}
		try {
			const loadingToast = toast.loading({
				title: "Updating Leave",
				description: "Please wait while we process your request...",
			});
			await updateLeave({ id: leaveId, data: formData }).unwrap();
			loadingToast.update({
				title: "Success",
				description: "Leave updated successfully!",
				status: "success",
				duration: 3000,
			});
			router.push("/leave");
		} catch (error) {
			toast.showToast({
				title: "Error",
				description: error?.data?.message || "Failed to update leave. Please try again.",
				status: "error",
				duration: 5000,
			});
		}
	};

	return (
		<div>
			<div className='flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4'>
				<h1 className='text-2xl font-bold'>Edit Leave</h1>
				<div className='flex flex-col sm:flex-row items-start sm:items-center gap-4 w-full sm:w-auto'>
					<Link href='/leave' className='w-full sm:w-auto'>
						<Button variant='outline' className='w-full sm:w-auto'>
							<FaTimes className='w-4 h-4 mr-2' />
							Cancel
						</Button>
					</Link>
				</div>
			</div>

			{editLoading && !editData?.leaves ? (
				<div className='p-8 text-center'>
					<div className='flex justify-center items-center'>
						<svg className='animate-spin h-8 w-8 text-primary-600' xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24'>
							<circle className='opacity-25' cx='12' cy='12' r='10' stroke='currentColor' strokeWidth='4'></circle>
							<path className='opacity-75' fill='currentColor' d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'></path>
						</svg>
					</div>
					<p className='mt-2 text-gray-600'>Loading leave data...</p>
				</div>
			) : (
				<form onSubmit={handleSubmit}>
					<Card className='mb-6 overflow-hidden'>
						<div className='grid grid-cols-1 gap-6 mt-6 items-start max-w-xl'>
							<div>
								<Input
									name='title'
									label='Title'
									value={formData.title}
									onChange={handleInputChange}
									placeholder='Enter Title'
									required
								/>
							</div>
							<div>
								<Input
									name='note'
									label='Note'
									value={formData.note}
									onChange={handleInputChange}
									placeholder='Enter note'
									required
								/>
							</div>
							<div>
								<Select
									name='status'
									label='Status'
									value={formData.status}
									onChange={handleInputChange}
									options={statusOptions}
									required
								/>
							</div>
							<div className='flex flex-col sm:flex-row justify-start mt-6 gap-3'>
								<Button
									type='submit'
									isLoading={editLoading}
									className='w-full sm:w-auto bg-green-500 hover:bg-green-600'>
									Update
								</Button>
							</div>
						</div>
					</Card>
				</form>
			)}
		</div>
	);
};

export default EditLeavePage;
