// components/admin/social/SocialMedia.tsx
'use client';

import * as React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Globe, Plus, Check, X, Edit2, Trash2, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { SocialPlatform } from '@/app/generated/prisma/enums';
import { SocialMedia as SocialMediaType } from '@/lib/modules/social-media/social-media.types';
import {
	useGetAllSocialMediaQuery,
	useCreateSocialMediaMutation,
	useUpdateSocialMediaMutation,
	useDeleteSocialMediaMutation,
	useToggleSocialMediaStatusMutation,
} from '@/store/slice/socialMediaApi';
import {
	platformColors,
	platformIcons,
	platformOptions,
} from '../_const/social-media';
import { useSelector } from 'react-redux';
import { isAdminSelector } from '@/store/authSlice';

export default function SocialMedia() {
	const isAdmin = useSelector(isAdminSelector);
	// Queries and Mutations
	const { data: socialLinks = [] } = useGetAllSocialMediaQuery();

	const [createSocialMedia, { isLoading: isCreating }] =
		useCreateSocialMediaMutation();
	const [updateSocialMedia, { isLoading: isUpdating }] =
		useUpdateSocialMediaMutation();
	const [deleteSocialMedia, { isLoading: isDeleting }] =
		useDeleteSocialMediaMutation();
	const [toggleStatus, { isLoading: isToggling }] =
		useToggleSocialMediaStatusMutation();
	// Form state
	const [newPlatform, setNewPlatform] = React.useState<SocialPlatform>(
		SocialPlatform.FACEBOOK
	);
	const [newUrl, setNewUrl] = React.useState('');

	// Edit state
	const [editingId, setEditingId] = React.useState<string | null>(null);
	const [editingUrl, setEditingUrl] = React.useState('');

	// Delete confirmation
	const [deleteConfirm, setDeleteConfirm] = React.useState<string | null>(
		null
	);

	const isSubmitting = isCreating || isUpdating || isDeleting || isToggling;

	// Check if platform already exists
	const isPlatformExists = (platform: SocialPlatform, excludeId?: string) => {
		if (socialLinks.length <= 0) return false;

		return socialLinks.some(
			(link) => link.platform === platform && link.id !== excludeId
		);
	};

	// Get available platforms (not used yet)
	const getAvailablePlatforms = () => {
		const usedPlatforms =
			socialLinks.length > 0 ? socialLinks?.map((l) => l.platform) : [];
		return platformOptions.filter(
			(option) => !usedPlatforms.includes(option.value)
		);
	};

	// Handle Add
	const handleAddSocial = async (e: React.FormEvent) => {
		e.preventDefault();

		if (!newUrl) {
			toast.error('Please enter a URL');
			return;
		}

		if (!newUrl.startsWith('http')) {
			toast.error(
				'Please enter a valid URL starting with http:// or https://'
			);
			return;
		}

		if (isPlatformExists(newPlatform)) {
			toast.error(`A ${newPlatform.toLowerCase()} link already exists`);
			return;
		}

		try {
			// Store the current platform before resetting
			const addedPlatform = newPlatform;

			await createSocialMedia({
				platform: addedPlatform,
				url: newUrl,
				isActive: true,
			}).unwrap();

			// Clear the URL input
			setNewUrl('');

			// Calculate next available platform based on current socialLinks + the one we just added
			const updatedUsedPlatforms = [
				...socialLinks.map((l) => l.platform),
				addedPlatform,
			];
			const nextAvailablePlatform = platformOptions.find(
				(option) => !updatedUsedPlatforms.includes(option.value)
			);

			// Set to next available platform if any
			if (nextAvailablePlatform) {
				setNewPlatform(nextAvailablePlatform.value);
			}

			toast.success('Social media link added successfully!');
		} catch (err) {
			toast.error(`Failed to add social media link ${err}`);
		}
	};

	// Handle Edit
	const handleEdit = (link: SocialMediaType) => {
		setEditingId(link.id);
		setEditingUrl(link.url);
	};

	const handleUpdateSocial = async (id: string) => {
		if (!editingUrl) {
			toast.error('Please enter a URL');
			return;
		}

		if (!editingUrl.startsWith('http')) {
			toast.error(
				'Please enter a valid URL starting with http:// or https://'
			);
			return;
		}

		const linkToUpdate = socialLinks.find((l) => l.id === id);
		if (!linkToUpdate) return;

		try {
			await updateSocialMedia({
				id,
				data: { url: editingUrl },
			}).unwrap();

			setEditingId(null);
			toast.success('Social media link updated successfully!');
		} catch (err) {
			toast.error(`Failed to update social media link ${err}`);
		}
	};

	// Handle Delete
	const handleDeleteSocial = async (id: string) => {
		if (deleteConfirm === id) {
			try {
				await deleteSocialMedia(id).unwrap();
				setDeleteConfirm(null);

				// After deletion, find the next available platform to potentially show the form again
				// No need to update newPlatform as the form will reappear with available platforms
				toast.success('Social media link deleted successfully!');
			} catch (err) {
				toast.error(`Failed to delete social media link ${err}`);
			}
		} else {
			setDeleteConfirm(id);
			setTimeout(() => setDeleteConfirm(null), 3000);
		}
	};

	// Handle Toggle Status
	const handleToggleSocial = async (id: string) => {
		try {
			await toggleStatus(id).unwrap();
			// Success message is handled by the mutation's onSuccess or you can add toast here
		} catch (err) {
			toast.error(`Failed to update status ${err}`);
		}
	};

	const availablePlatforms = getAvailablePlatforms();

	// Set initial platform to first available when component loads or socialLinks change
	React.useEffect(() => {
		if (availablePlatforms.length > 0) {
			setNewPlatform(availablePlatforms[0].value);
		}
	}, [socialLinks.length]); // Only run when socialLinks length changes

	return (
		<motion.div
			initial={{ opacity: 0, x: 20 }}
			animate={{ opacity: 1, x: 0 }}
			transition={{ delay: 0.2 }}
		>
			<div className="bg-card border border-primary/10 rounded-2xl overflow-hidden backdrop-blur-sm">
				{/* Card Header */}
				<div className="px-6 py-4 border-b border-primary/10 bg-linear-to-r from-primary/5 to-transparent">
					<div className="flex items-center justify-between">
						<div className="flex items-center gap-3">
							<div className="p-2 bg-primary/10 rounded-lg">
								<Globe className="w-5 h-5 text-primary" />
							</div>
							<div>
								<h2 className="text-lg font-serif font-semibold text-foreground/90">
									Social Media Links
								</h2>
								<p className="text-xs text-foreground/40">
									Add and manage your social media presence
								</p>
							</div>
						</div>
						{availablePlatforms.length === 0 &&
							socialLinks.length > 0 && (
								<span className="text-xs text-yellow-500 bg-yellow-500/10 px-2 py-1 rounded-full">
									All platforms added
								</span>
							)}
					</div>
				</div>

				{/* Card Body */}
				<div className="p-6">
					{/* Add New Form - Compact Inline (only show if platforms available) */}
					{availablePlatforms.length > 0 && (
						<form onSubmit={handleAddSocial} className="flex gap-2 mb-6">
							<select
								value={newPlatform}
								onChange={(e) =>
									setNewPlatform(e.target.value as SocialPlatform)
								}
								className="w-32 px-3 py-2 bg-secondary border border-primary/20 rounded-lg 
			   						text-foreground text-sm font-sans
			   						focus:border-primary focus:ring-1 focus:ring-primary/30 
			   						hover:border-primary/40
			   						outline-none transition-all duration-200
			   						disabled:opacity-50 disabled:cursor-not-allowed
			   						appearance-none bg-[url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiNDQkIyNkEiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cG9seWxpbmUgcG9pbnRzPSI2IDkgMTIgMTUgMTggOSI+PC9wb2x5bGluZT48L3N2Zz4=')] bg-no-repeat bg-[center_right_0.5rem] pr-8"
								disabled={isSubmitting}
							>
								{availablePlatforms.map((option) => (
									<option
										key={option.value}
										value={option.value}
										className="bg-card text-foreground"
									>
										{option.label}
									</option>
								))}
							</select>

							<input
								type="url"
								value={newUrl}
								onChange={(e) => setNewUrl(e.target.value)}
								placeholder="https://..."
								className="flex-1 px-3 py-2 bg-secondary/30 border border-primary/20 rounded-lg focus:border-primary/40 focus:ring-1 focus:ring-primary/30 outline-none transition-all text-sm"
								disabled={isSubmitting}
							/>

							<button
								type="submit"
								disabled={isSubmitting}
								className="px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center gap-2 text-sm whitespace-nowrap"
							>
								{isSubmitting ? (
									<Loader2 className="w-4 h-4 animate-spin" />
								) : (
									<Plus className="w-4 h-4" />
								)}
								Add
							</button>
						</form>
					)}

					{/* Social Links List */}
					<div className="space-y-2">
						<AnimatePresence>
							{socialLinks.length > 0 &&
								socialLinks.map((link) => {
									const Icon = platformIcons[link.platform];
									const platformInfo = platformOptions.find(
										(p) => p.value === link.platform
									);

									return (
										<motion.div
											key={link.id}
											initial={{ opacity: 0, y: 10 }}
											animate={{ opacity: 1, y: 0 }}
											exit={{ opacity: 0, scale: 0.9 }}
											className={`flex items-center gap-2 p-2 rounded-lg group transition-colors ${
												deleteConfirm === link.id
													? 'bg-red-500/10 border border-red-500/30'
													: 'bg-secondary/30 hover:bg-secondary/50'
											}`}
										>
											{/* Platform Icon with Color */}
											<div
												className={`w-8 h-8 rounded-lg ${platformColors[link.platform]} bg-opacity-20 flex items-center justify-center shrink-0`}
											>
												<Icon
													className={`w-4 h-4 ${platformColors[link.platform].replace('bg-', 'text-')}`}
												/>
											</div>

											{/* Platform Name & URL */}
											{editingId === link.id ? (
												<form
													onSubmit={(e) => {
														e.preventDefault();
														handleUpdateSocial(link.id);
													}}
													className="flex-1 flex items-center gap-1"
												>
													<input
														type="url"
														value={editingUrl}
														onChange={(e) =>
															setEditingUrl(e.target.value)
														}
														className="flex-1 px-2 py-1 bg-background border border-primary/20 rounded text-sm focus:border-primary/40 focus:ring-1 focus:ring-primary/30 outline-none"
														placeholder="https://..."
														autoFocus
														disabled={isSubmitting}
													/>
													<button
														type="submit"
														disabled={isSubmitting}
														className="p-1 hover:bg-primary/10 rounded disabled:opacity-50"
													>
														<Check className="w-4 h-4 text-green-500" />
													</button>
													<button
														type="button"
														onClick={() => setEditingId(null)}
														disabled={isSubmitting}
														className="p-1 hover:bg-primary/10 rounded disabled:opacity-50"
													>
														<X className="w-4 h-4 text-red-500" />
													</button>
												</form>
											) : (
												<>
													<div className="flex-1 min-w-0">
														<p className="text-xs font-medium text-foreground/90">
															{platformInfo?.label}
														</p>
														<a
															href={link.url}
															target="_blank"
															rel="noopener noreferrer"
															className="text-xs text-primary/60 hover:text-primary truncate block"
														>
															{link.url.replace(
																/^https?:\/\//,
																''
															)}
														</a>
													</div>

													{/* Status Indicator */}
													<button
														onClick={() =>
															handleToggleSocial(link.id)
														}
														disabled={isSubmitting}
														className={`w-2 h-2 rounded-full ${
															link.isActive
																? 'bg-green-500 hover:bg-green-600'
																: 'bg-gray-500 hover:bg-gray-600'
														} transition-colors`}
														title={
															link.isActive
																? 'Active'
																: 'Inactive'
														}
													/>

													{/* Action Buttons */}
													<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
														<button
															onClick={() => handleEdit(link)}
															disabled={isSubmitting}
															className="p-1 hover:bg-primary/10 rounded disabled:opacity-50"
															title="Edit"
														>
															<Edit2 className="w-3 h-3 text-foreground/60" />
														</button>
														{isAdmin && (
															<button
																onClick={() =>
																	handleDeleteSocial(link.id)
																}
																disabled={isSubmitting}
																className="p-1 hover:bg-red-500/10 rounded disabled:opacity-50 relative"
																title={
																	deleteConfirm === link.id
																		? 'Click again to confirm'
																		: 'Delete'
																}
															>
																{deleteConfirm === link.id && (
																	<span className="absolute -top-8 left-1/2 -translate-x-1/2 bg-destructive text-destructive-foreground text-xs px-2 py-1 rounded whitespace-nowrap z-10">
																		Confirm?
																	</span>
																)}
																<Trash2 className="w-3 h-3 text-red-500" />
															</button>
														)}
													</div>
												</>
											)}
										</motion.div>
									);
								})}
						</AnimatePresence>

						{/* Empty State */}
						{socialLinks.length === 0 && (
							<div className="text-center py-12">
								<div className="w-16 h-16 mx-auto bg-secondary/50 rounded-full flex items-center justify-center mb-4">
									<Globe className="w-8 h-8 text-foreground/40" />
								</div>
								<p className="text-sm text-foreground/60 mb-2">
									No social media links added yet.
								</p>
								<p className="text-xs text-foreground/40">
									Add your first social media link using the form
									above.
								</p>
							</div>
						)}
					</div>
				</div>
			</div>
		</motion.div>
	);
}
