// app/admin/contact/page.tsx
'use client';

import * as React from 'react';
import { motion } from 'framer-motion';

import {
	useGetAllContactInfoQuery,
	useDeleteContactInfoMutation,
} from '@/store/slice/contactInfoApi';
import { ContactInfo } from '@/lib/modules/contact-info/contact-info.types';
import { toast } from 'sonner';
import ContactDisplay from './ContactInfor';
import ContactFormDialog from './ContactFormDialog';
import SocialMedia from './SocialMedia';

export default function ContactPage() {
	const [isDialogOpen, setIsDialogOpen] = React.useState(false);
	const [selectedContact, setSelectedContact] =
		React.useState<ContactInfo | null>(null);
	const [isEditing, setIsEditing] = React.useState(false);
	const [deleteConfirm, setDeleteConfirm] = React.useState<string | null>(
		null
	);

	// Fetch contact info from API
	const {
		data: contacts = [],
		isLoading,
		error,
		refetch,
	} = useGetAllContactInfoQuery();

	const [deleteContact] = useDeleteContactInfoMutation();

	const handleEdit = (contact: ContactInfo) => {
		setSelectedContact(contact);
		setIsEditing(true);
		setIsDialogOpen(true);
	};

	const handleAdd = () => {
		setSelectedContact(null);
		setIsEditing(false);
		setIsDialogOpen(true);
	};

	const handleDelete = async (contact: ContactInfo) => {
		if (deleteConfirm === contact.id) {
			try {
				await deleteContact(contact.id).unwrap();
				toast.success('Contact deleted successfully');
				setDeleteConfirm(null);
			} catch (error) {
				toast.error(`Failed to delete contact ${error}`);
			}
		} else {
			setDeleteConfirm(contact.id);
			// Auto-clear after 3 seconds
			setTimeout(() => setDeleteConfirm(null), 3000);
		}
	};

	const handleSuccess = () => {
		refetch(); // Refresh data after successful operation
	};

	// Get unique sections count for display
	const uniqueSections = new Set(contacts.map((c) => c.section)).size;

	return (
		<div className="min-h-screen bg-background">
			{/* Main Container with proper padding */}
			<div className="max-w-[1600px] mx-auto px-4 sm:px-6 lg:px-8 py-6 lg:py-8">
				{/* Header Section */}
				<motion.div
					initial={{ opacity: 0, y: -20 }}
					animate={{ opacity: 1, y: 0 }}
					className="mb-8 lg:mb-10"
				>
					<div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4">
						<div>
							<h1 className="text-3xl lg:text-4xl font-serif font-bold text-foreground/90">
								Contact Management
							</h1>
							<p className="mt-4 text-sm text-[#A89A72] max-w-xl leading-relaxed">
								Manage your business contact information across
								different sections and social media links
							</p>
						</div>

						{/* Stats Badge */}
						<div className="flex items-center gap-3">
							<div className="luxury-line w-16 hidden lg:block" />
							<div className="bg-secondary/30 border border-primary/10 rounded-lg px-4 py-2">
								<span className="text-sm text-foreground/60">
									<span className="text-primary font-semibold">
										{uniqueSections}
									</span>{' '}
									of {allSectionOptions.length} sections used
								</span>
							</div>
						</div>
					</div>

					{/* Decorative line */}
					<div className="luxury-line w-32 mt-4" />
				</motion.div>

				{/* Two Column Grid Layout */}
				<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8">
					{/* Left Column - Contact Information */}
					<motion.div
						initial={{ opacity: 0, x: -20 }}
						animate={{ opacity: 1, x: 0 }}
						transition={{ delay: 0.1 }}
						className="h-full"
					>
						<ContactDisplay
							contacts={contacts}
							isLoading={isLoading}
							error={!!error}
							onEdit={handleEdit}
							onDelete={handleDelete}
							onAdd={handleAdd}
							onRetry={refetch}
						/>
					</motion.div>

					{/* Right Column - Social Media */}
					<motion.div
						initial={{ opacity: 0, x: 20 }}
						animate={{ opacity: 1, x: 0 }}
						transition={{ delay: 0.2 }}
						className="h-full"
					>
						<SocialMedia />
					</motion.div>
				</div>

				{/* Contact Form Dialog */}
				<ContactFormDialog
					isOpen={isDialogOpen}
					onClose={() => setIsDialogOpen(false)}
					contact={selectedContact}
					isEditing={isEditing}
					onSuccess={handleSuccess}
					existingContacts={contacts}
				/>

				{/* Delete Confirmation Toast */}
				{deleteConfirm && (
					<motion.div
						initial={{ opacity: 0, y: 20 }}
						animate={{ opacity: 1, y: 0 }}
						exit={{ opacity: 0, y: 20 }}
						className="fixed bottom-4 right-4 z-50"
					>
						<div className="bg-destructive/10 border border-destructive/20 rounded-lg p-4 shadow-lg backdrop-blur-sm">
							<p className="text-sm text-destructive mb-2">
								Click again to confirm deletion
							</p>
							<div className="flex items-center gap-2">
								<button
									onClick={() => {
										const contact = contacts.find(
											(c) => c.id === deleteConfirm
										);
										if (contact) handleDelete(contact);
									}}
									className="px-3 py-1.5 bg-destructive text-destructive-foreground rounded-lg text-sm hover:bg-destructive/90 transition-colors"
								>
									Confirm Delete
								</button>
								<button
									onClick={() => setDeleteConfirm(null)}
									className="px-3 py-1.5 bg-secondary/50 border border-primary/20 rounded-lg text-sm hover:bg-secondary/70 transition-colors"
								>
									Cancel
								</button>
							</div>
						</div>
					</motion.div>
				)}
			</div>
		</div>
	);
}

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