// components/admin/gallery/GalleryForm.tsx
'use client';

import * as React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import FormProvider from '@/components/forms/FormProvider';
import RHFUploadImage from '@/components/forms/RHFUploadImage';
import RHFSelect from '@/components/forms/RHFSelect';
import PrimaryButton from '@/components/button/PrimaryButton';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import { motion, AnimatePresence } from 'framer-motion';
import { X } from 'lucide-react';
import {
	CreateGalleryImageInput,
	createGalleryImageInputDefault,
	CreateGalleryImageSchema,
	UpdateGalleryImageSchema,
} from '@/lib/modules/gallery/gallery.validation';
import {
	GalleryImage,
	GalleryPriority,
} from '@/lib/modules/gallery/gallery.types';

import useFormSubmitHandler from '@/hooks/formHandler';
import {
	useCreateGalleryImageMutation,
	useUpdateGalleryImageMutation,
} from '@/store/slice/galleryApi';
import { GALLERY_PRIORITIES, GALLERY_SECTIONS } from '../_const/gallery';

interface GalleryFormProps {
	open: boolean;
	onOpenChange: (open: boolean) => void;
	image?: GalleryImage | null;
	onSuccess?: () => void;
}

export function GalleryForm({
	open,
	onOpenChange,
	image,
	onSuccess,
}: GalleryFormProps) {
	const [createImage, { isLoading: isCreating }] =
		useCreateGalleryImageMutation();
	const [updateImage, { isLoading: isUpdating }] =
		useUpdateGalleryImageMutation();

	const isEditing = !!image;
	const schema = isEditing
		? UpdateGalleryImageSchema
		: CreateGalleryImageSchema;

	const methods = useForm<CreateGalleryImageInput>({
		defaultValues: createGalleryImageInputDefault,
		resolver: zodResolver(schema) as any,
		mode: 'onChange',
	});

	const { watch, setValue, reset } = methods;
	const watchedIsActive = watch('isActive');

	// Reset form when opening/closing
	React.useEffect(() => {
		if (open) {
			if (image) {
				reset({
					section: image.section,
					priority: image.priority,
					isActive: image.isActive,
					image: image.image,
				});
			} else {
				reset(createGalleryImageInputDefault);
			}
		}
	}, [open, image, reset]);

	const handleSubmit = useFormSubmitHandler(
		async (data: CreateGalleryImageInput) => {
			const formData = new FormData();

			formData.append('section', data.section);
			formData.append('priority', data.priority || GalleryPriority.LOW);
			formData.append('isActive', String(data.isActive ?? true));

			if (data.image instanceof File) {
				formData.append('image', data.image);
			} else if (typeof data.image === 'string' && data.image) {
				formData.append('image', data.image);
			}

			let result;
			if (isEditing && image)
				result = await updateImage({ id: image.id, formData }).unwrap();
			else result = await createImage(formData).unwrap();

			return { data: result };
		},
		() => {
			onOpenChange(false);
			onSuccess?.();
		},
		isEditing ? 'Image updated successfully' : 'Image added successfully'
	);

	const isLoading = isEditing ? isUpdating : isCreating;

	if (!open) return null;

	return (
		<AnimatePresence>
			<motion.div
				initial={{ opacity: 0 }}
				animate={{ opacity: 1 }}
				exit={{ opacity: 0 }}
				className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
				onClick={() => onOpenChange(false)}
			>
				<motion.div
					initial={{ scale: 0.95, opacity: 0, y: 20 }}
					animate={{ scale: 1, opacity: 1, y: 0 }}
					exit={{ scale: 0.95, opacity: 0, y: 20 }}
					onClick={(e) => e.stopPropagation()}
					className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-full max-w-2xl"
				>
					<div className="bg-card border border-primary/10 rounded-2xl shadow-xl overflow-hidden">
						{/* Header */}
						<div className="relative px-6 py-4 border-b border-primary/10 bg-linear-to-r from-primary/5 to-transparent">
							<h2 className="text-xl font-serif font-semibold text-foreground/90">
								{isEditing
									? 'Edit Gallery Image'
									: 'Add New Gallery Image'}
							</h2>
							<p className="text-sm text-foreground/60 mt-1">
								{isEditing
									? 'Update image details below'
									: 'Upload a new image to your gallery'}
							</p>
							<button
								onClick={() => onOpenChange(false)}
								className="absolute right-4 top-4 p-1 rounded-lg hover:bg-primary/10 transition-colors"
							>
								<X className="w-5 h-5 text-foreground/60" />
							</button>
						</div>

						{/* Form */}
						<div className="p-6 max-h-[70vh] overflow-y-auto">
							<FormProvider
								methods={methods}
								onSubmit={methods.handleSubmit(handleSubmit)}
							>
								<div className="space-y-6">
									{/* Image Upload */}
									<RHFUploadImage
										name="image"
										label="Gallery Image"
										size={200}
									/>

									{/* Section Select */}
									<RHFSelect
										name="section"
										label="Section"
										defaultValue={image?.section}
										options={GALLERY_SECTIONS.map((s) => ({
											value: s.value,
											label: `${s.icon} ${s.label}`,
										}))}
										isRequired
									/>

									{/* Priority Select */}
									<RHFSelect
										name="priority"
										label="Priority"
										defaultValue={image?.priority}
										options={GALLERY_PRIORITIES.map((p) => ({
											value: p.value,
											label: `${p.icon} ${p.label}`,
										}))}
									/>

									{/* Active Status */}
									<div className="flex items-center justify-between p-4 bg-secondary/30 rounded-lg">
										<div className="space-y-1">
											<Label
												htmlFor="isActive"
												className="text-sm font-medium"
											>
												Active Status
											</Label>
											<p className="text-xs text-foreground/40">
												Toggle to show/hide this image on the
												website
											</p>
										</div>
										<div className="flex items-center gap-3">
											<span className="text-sm text-foreground/60">
												{watchedIsActive ? 'Active' : 'Inactive'}
											</span>
											<Switch
												id="isActive"
												checked={watchedIsActive}
												onCheckedChange={(checked) =>
													setValue('isActive', checked)
												}
												className="data-[state=checked]:bg-primary"
											/>
										</div>
									</div>

									{/* Submit Button */}
									<PrimaryButton
										type="submit"
										title={isEditing ? 'Update Image' : 'Add Image'}
										className="w-full h-12 bg-primary hover:bg-primary/90 text-primary-foreground font-medium rounded-xl gold-glow"
										isLoading={isLoading}
									/>
								</div>
							</FormProvider>
						</div>
					</div>
				</motion.div>
			</motion.div>
		</AnimatePresence>
	);
}
