// components/admin/contact/ContactFormDialog.tsx
'use client';

import * as React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useEffect } from 'react';
import FormProvider from '@/components/forms/FormProvider';
import RHFTextField from '@/components/forms/RHFTextField';
import RHFSelect from '@/components/forms/RHFSelect';
import RHFCheckbox from '@/components/forms/RHFChekBox';
import PrimaryButton from '@/components/button/PrimaryButton';
import CustomResponsiveDialog from '@/components/dialog/CustomResponsiveDialog';
import LoadingSpinner from '@/components/loader/LoadingSpinner';
import useFormSubmitHandler from '@/hooks/formHandler';
import { AlertCircle } from 'lucide-react';

// Types and Validation
import { GallerySection } from '@/lib/modules/gallery/gallery.types';
import {
	CreateContactInfoInput,
	CreateContactInfoSchema,
	UpdateContactInfoSchema,
	createContactInfoInputDefault,
} from '@/lib/modules/contact-info/contact-info.validation';
import { ContactInfo } from '@/lib/modules/contact-info/contact-info.types';
import {
	useCreateContactInfoMutation,
	useUpdateContactInfoMutation,
} from '@/store/slice/contactInfoApi';

const allSectionOptions = [
	{ value: GallerySection.HERO, label: 'Hero Section' },
	{ value: GallerySection.ABOUT_US, label: 'About Us' },
	{ value: GallerySection.ABOUT_BANNER, label: 'About Banner' },
	{ value: GallerySection.SERVICES_BANNER, label: 'Services Banner' },
	{ value: GallerySection.FLEET_BANNER, label: 'Fleet Banner' },
	{ value: GallerySection.BOOK_BANNER, label: 'Book Banner' },
	{ value: GallerySection.CONTACT_BANNER, label: 'Contact Banner' },
	{ value: GallerySection.SAFETY_SERVICE, label: 'Safety Service' },
	{ value: GallerySection.LUXURY_FLEET, label: 'Luxury Fleet' },
];

interface ContactFormDialogProps {
	isOpen: boolean;
	onClose: () => void;
	contact?: ContactInfo | null;
	isEditing?: boolean;
	onSuccess?: () => void;
	existingContacts?: ContactInfo[]; // Add this prop to get existing contacts
}

export default function ContactFormDialog({
	isOpen,
	onClose,
	contact,
	isEditing = false,
	onSuccess,
	existingContacts = [], // Default to empty array
}: ContactFormDialogProps) {
	const [createContact, { isLoading: isCreatingLoading }] =
		useCreateContactInfoMutation();
	const [updateContact, { isLoading: isUpdatingLoading }] =
		useUpdateContactInfoMutation();

	const schema = isEditing ? UpdateContactInfoSchema : CreateContactInfoSchema;

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

	const { reset } = methods;

	// Filter section options to only show available sections (not used by other contacts)
	const availableSectionOptions = React.useMemo(() => {
		if (isEditing && contact) {
			// When editing, include the current contact's section plus all unused sections
			const usedSections = existingContacts
				.filter((c) => c.id !== contact.id) // Exclude current contact
				.map((c) => c.section);

			return allSectionOptions.filter(
				(option) =>
					!usedSections.includes(option.value) ||
					option.value === contact.section
			);
		} else {
			// When creating new, only show unused sections
			const usedSections = existingContacts.map((c) => c.section);
			return allSectionOptions.filter(
				(option) => !usedSections.includes(option.value)
			);
		}
	}, [existingContacts, isEditing, contact]);

	// Check if there are any available sections
	const hasAvailableSections = availableSectionOptions.length > 0;

	// Reset form when dialog opens or contact changes
	useEffect(() => {
		if (isOpen) {
			if (contact && contact?.id) {
				reset({
					phone: contact.phone,
					email: contact.email,
					location: contact.location,
					section: contact.section,
					isActive: contact.isActive,
				});
			} else {
				// For new contact, auto-select the first available section if any
				if (hasAvailableSections) {
					reset({
						section: availableSectionOptions[0].value,
					});
				}
			}
		}
	}, [contact, isOpen, reset, availableSectionOptions, hasAvailableSections]);

	const handleSubmit = useFormSubmitHandler(
		async (data: CreateContactInfoInput) => {
			let result;

			if (isEditing && contact?.id) {
				// Update existing
				result = await updateContact({
					id: contact.id,
					data,
				}).unwrap();
			} else {
				// Create new
				result = await createContact(data).unwrap();
			}

			return { data: result };
		},
		() => {
			onClose();
			onSuccess?.();
		},
		isEditing
			? 'Contact information updated successfully!'
			: 'Contact information added successfully!'
	);

	const isLoading = isCreatingLoading || isUpdatingLoading;

	return (
		<CustomResponsiveDialog
			open={isOpen}
			setOpen={onClose}
			header={
				<div className="w-full">
					<h2 className="text-lg font-semibold text-foreground/90">
						{isEditing
							? 'Edit Contact Information'
							: 'Add Contact Information'}
					</h2>
					<p className="mt-1 text-sm text-foreground/60">
						{isEditing
							? 'Update your business contact details'
							: 'Add your business contact details to display on the website'}
					</p>
				</div>
			}
			classNameContent="m-0 p-0 max-w-[640px] p-4 rounded-lg bg-background border-none max-h-[90vh] overflow-y-scroll overflow-x-scroll scrollbar-x-hidden"
			classNameBody="px-2 py-6 sm:px-12 sm:py-6"
			classNameCloseBtn="absolute top-4 right-4 text-[#CD3232] cursor-pointer"
		>
			{/* Loading Overlay */}
			{isLoading && (
				<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center">
					<LoadingSpinner size="md" />
				</div>
			)}

			<FormProvider
				methods={methods}
				onSubmit={methods.handleSubmit(handleSubmit)}
			>
				<div className="grid w-full items-center gap-4">
					{/* Show warning if no sections available for new contact */}
					{!isEditing && !hasAvailableSections && (
						<div className="p-3 bg-yellow-500/10 border border-yellow-500/20 rounded-lg flex items-start gap-2">
							<AlertCircle className="w-5 h-5 text-yellow-500 shrink-0 mt-0.5" />
							<div>
								<p className="text-sm font-medium text-yellow-500">
									No sections available
								</p>
								<p className="text-xs text-foreground/60">
									All sections already have contact information. You
									can edit existing contacts instead.
								</p>
							</div>
						</div>
					)}

					{/* Phone */}
					<RHFTextField
						name="phone"
						label="Phone Number"
						leftIcon="phone"
						placeholder="+1 (555) 123-4567"
						isRequired={false}
					/>

					{/* Email */}
					<RHFTextField
						name="email"
						label="Email Address"
						leftIcon="mail"
						type="email"
						placeholder="contact@example.com"
						isRequired={false}
					/>

					{/* Location */}
					<RHFTextField
						name="location"
						label="Location"
						leftIcon="globe"
						placeholder="123 Luxury Lane, Beverly Hills, CA"
						isRequired={false}
					/>

					{/* Section Dropdown - Only show if there are available sections or editing */}
					{(hasAvailableSections || isEditing) && (
						<RHFSelect
							name="section"
							label="Section"
							options={availableSectionOptions}
							defaultValue={
								contact?.section || availableSectionOptions[0]?.value
							}
							isRequired
						/>
					)}

					{/* Active Status */}
					<RHFCheckbox
						name="isActive"
						label="Make this contact information active (visible on website)"
					/>

					{/* Submit Button - Disable if no sections available for new contact */}
					<PrimaryButton
						type="submit"
						title={isEditing ? 'Update Contact' : 'Add Contact'}
						className="mt-6 w-full"
						isLoading={isLoading}
						// disabled={!isEditing && !hasAvailableSections}
					/>
				</div>
			</FormProvider>
		</CustomResponsiveDialog>
	);
}
