'use client';

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { useToast } from '@/hooks/use-toast';
import { Megaphone, Plus, Edit, Trash2, Calendar, AlertCircle, CheckCircle, Clock } from 'lucide-react';

interface Announcement {
	id: string;
	title: string;
	content: string;
	priority: 'low' | 'medium' | 'high';
	isActive: boolean;
	expiresAt?: string;
	createdAt: string;
	updatedAt: string;
}

interface AnnouncementFormData {
	title: string;
	content: string;
	priority: 'low' | 'medium' | 'high';
	isActive: boolean;
	expiresAt: string;
}

export function AdminAnnouncementManagement() {
	const [announcements, setAnnouncements] = useState<Announcement[]>([]);
	const [loading, setLoading] = useState(true);
	const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
	const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
	const [editingAnnouncement, setEditingAnnouncement] = useState<Announcement | null>(null);
	const [formData, setFormData] = useState<AnnouncementFormData>({
		title: '',
		content: '',
		priority: 'medium',
		isActive: true,
		expiresAt: '',
	});
	const { toast } = useToast();

	useEffect(() => {
		fetchAnnouncements();
	}, []);

	const fetchAnnouncements = async () => {
		try {
			setLoading(true);
			const response = await fetch('/api/admin/announcements');
			if (response.ok) {
				const data = await response.json();
				setAnnouncements(data.announcements);
			} else {
				throw new Error('Failed to fetch announcements');
			}
		} catch (error) {
			console.error('Error fetching announcements:', error);
			toast({
				title: 'Error',
				description: 'Failed to fetch announcements',
				variant: 'destructive',
			});
		} finally {
			setLoading(false);
		}
	};

	const handleCreateAnnouncement = async () => {
		try {
			if (!formData.title || !formData.content) {
				toast({
					title: 'Error',
					description: 'Please fill in title and content',
					variant: 'destructive',
				});
				return;
			}

			const submitData = {
				...formData,
				expiresAt: formData.expiresAt || null,
			};

			const response = await fetch('/api/admin/announcements', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify(submitData),
			});

			const data = await response.json();

			if (response.ok) {
				toast({
					title: 'Success',
					description: 'Announcement created successfully',
				});
				setIsCreateDialogOpen(false);
				resetForm();
				fetchAnnouncements();
			} else {
				toast({
					title: 'Error',
					description: data.error || 'Failed to create announcement',
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Error creating announcement:', error);
			toast({
				title: 'Error',
				description: 'Failed to create announcement',
				variant: 'destructive',
			});
		}
	};

	const handleEditAnnouncement = async () => {
		try {
			if (!editingAnnouncement || !formData.title || !formData.content) {
				toast({
					title: 'Error',
					description: 'Please fill in title and content',
					variant: 'destructive',
				});
				return;
			}

			const submitData = {
				...formData,
				expiresAt: formData.expiresAt || null,
			};

			const response = await fetch(`/api/admin/announcements/${editingAnnouncement.id}`, {
				method: 'PUT',
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify(submitData),
			});

			const data = await response.json();

			if (response.ok) {
				toast({
					title: 'Success',
					description: 'Announcement updated successfully',
				});
				setIsEditDialogOpen(false);
				setEditingAnnouncement(null);
				resetForm();
				fetchAnnouncements();
			} else {
				toast({
					title: 'Error',
					description: data.error || 'Failed to update announcement',
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Error updating announcement:', error);
			toast({
				title: 'Error',
				description: 'Failed to update announcement',
				variant: 'destructive',
			});
		}
	};

	const handleDeleteAnnouncement = async (announcementId: string) => {
		try {
			if (!confirm('Are you sure you want to delete this announcement?')) {
				return;
			}

			const response = await fetch(`/api/admin/announcements/${announcementId}`, {
				method: 'DELETE',
			});

			const data = await response.json();

			if (response.ok) {
				toast({
					title: 'Success',
					description: 'Announcement deleted successfully',
				});
				fetchAnnouncements();
			} else {
				toast({
					title: 'Error',
					description: data.error || 'Failed to delete announcement',
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Error deleting announcement:', error);
			toast({
				title: 'Error',
				description: 'Failed to delete announcement',
				variant: 'destructive',
			});
		}
	};

	const openEditDialog = (announcement: Announcement) => {
		setEditingAnnouncement(announcement);
		setFormData({
			title: announcement.title,
			content: announcement.content,
			priority: announcement.priority,
			isActive: announcement.isActive,
			expiresAt: announcement.expiresAt ? announcement.expiresAt.split('T')[0] : '',
		});
		setIsEditDialogOpen(true);
	};

	const resetForm = () => {
		setFormData({
			title: '',
			content: '',
			priority: 'medium',
			isActive: true,
			expiresAt: '',
		});
	};

	const getPriorityColor = (priority: string) => {
		switch (priority) {
			case 'high':
				return 'text-red-600 bg-red-50';
			case 'medium':
				return 'text-yellow-600 bg-yellow-50';
			case 'low':
				return 'text-green-600 bg-green-50';
			default:
				return 'text-gray-600 bg-gray-50';
		}
	};

	const getPriorityIcon = (priority: string) => {
		switch (priority) {
			case 'high':
				return <AlertCircle className='h-4 w-4' />;
			case 'medium':
				return <Clock className='h-4 w-4' />;
			case 'low':
				return <CheckCircle className='h-4 w-4' />;
			default:
				return <CheckCircle className='h-4 w-4' />;
		}
	};

	const isExpired = (expiresAt?: string) => {
		if (!expiresAt) return false;
		return new Date(expiresAt) < new Date();
	};

	if (loading) {
		return (
			<Card>
				<CardContent className='flex justify-center items-center py-8'>
					<div className='animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900'></div>
				</CardContent>
			</Card>
		);
	}

	return (
		<div className='space-y-6'>
			{/* Header */}
			<div className='flex items-center justify-between'>
				<div className='flex items-center gap-2'>
					<Megaphone className='h-6 w-6' />
					<h2 className='text-2xl font-bold'>Announcement Management</h2>
				</div>
				<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
					<DialogTrigger asChild>
						<Button onClick={() => resetForm()}>
							<Plus className='h-4 w-4 mr-2' />
							Create Announcement
						</Button>
					</DialogTrigger>
					<DialogContent className='max-w-2xl'>
						<DialogHeader>
							<DialogTitle>Create New Announcement</DialogTitle>
						</DialogHeader>
						<div className='space-y-4'>
							<div>
								<Label htmlFor='title'>Title</Label>
								<Input
									id='title'
									value={formData.title}
									onChange={(e) => setFormData({ ...formData, title: e.target.value })}
									placeholder='Announcement title'
								/>
							</div>
							<div>
								<Label htmlFor='content'>Content</Label>
								<Textarea
									id='content'
									value={formData.content}
									onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
										setFormData({ ...formData, content: e.target.value })
									}
									placeholder='Announcement content'
									rows={4}
								/>
							</div>
							<div className='grid grid-cols-2 gap-4'>
								<div>
									<Label htmlFor='priority'>Priority</Label>
									<Select
										value={formData.priority}
										onValueChange={(value: 'low' | 'medium' | 'high') =>
											setFormData({ ...formData, priority: value })
										}
									>
										<SelectTrigger>
											<SelectValue placeholder='Select priority' />
										</SelectTrigger>
										<SelectContent>
											<SelectItem value='low'>Low</SelectItem>
											<SelectItem value='medium'>Medium</SelectItem>
											<SelectItem value='high'>High</SelectItem>
										</SelectContent>
									</Select>
								</div>
								<div>
									<Label htmlFor='expiresAt'>Expires On (Optional)</Label>
									<Input
										id='expiresAt'
										type='date'
										value={formData.expiresAt}
										onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
									/>
								</div>
							</div>
							<div className='flex items-center space-x-2'>
								<input
									type='checkbox'
									id='isActive'
									checked={formData.isActive}
									onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
									className='rounded'
								/>
								<Label htmlFor='isActive'>Active (visible to users)</Label>
							</div>
							<div className='flex gap-2 justify-end'>
								<Button variant='outline' onClick={() => setIsCreateDialogOpen(false)}>
									Cancel
								</Button>
								<Button onClick={handleCreateAnnouncement}>Create Announcement</Button>
							</div>
						</div>
					</DialogContent>
				</Dialog>
			</div>

			{/* Announcements Table */}
			<Card>
				<CardHeader>
					<CardTitle>All Announcements ({announcements.length})</CardTitle>
				</CardHeader>
				<CardContent>
					<Table>
						<TableHeader>
							<TableRow>
								<TableHead>Title</TableHead>
								<TableHead>Priority</TableHead>
								<TableHead>Status</TableHead>
								<TableHead>Expires</TableHead>
								<TableHead>Created</TableHead>
								<TableHead>Actions</TableHead>
							</TableRow>
						</TableHeader>
						<TableBody>
							{announcements.map((announcement) => (
								<TableRow key={announcement.id}>
									<TableCell>
										<div>
											<div className='font-medium'>{announcement.title}</div>
											<div className='text-sm text-gray-500 truncate max-w-xs'>
												{announcement.content}
											</div>
										</div>
									</TableCell>
									<TableCell>
										<Badge className={getPriorityColor(announcement.priority)}>
											<div className='flex items-center gap-1'>
												{getPriorityIcon(announcement.priority)}
												{announcement.priority}
											</div>
										</Badge>
									</TableCell>
									<TableCell>
										<Badge
											variant={
												isExpired(announcement.expiresAt)
													? 'destructive'
													: announcement.isActive
													? 'default'
													: 'secondary'
											}
										>
											{isExpired(announcement.expiresAt)
												? 'Expired'
												: announcement.isActive
												? 'Active'
												: 'Inactive'}
										</Badge>
									</TableCell>
									<TableCell>
										<div className='flex items-center gap-2'>
											<Calendar className='h-4 w-4 text-gray-500' />
											{announcement.expiresAt
												? new Date(announcement.expiresAt).toLocaleDateString()
												: 'Never'}
										</div>
									</TableCell>
									<TableCell>
										<div className='flex items-center gap-2'>
											<Calendar className='h-4 w-4 text-gray-500' />
											{new Date(announcement.createdAt).toLocaleDateString()}
										</div>
									</TableCell>
									<TableCell>
										<div className='flex gap-2'>
											<Button
												variant='outline'
												size='sm'
												onClick={() => openEditDialog(announcement)}
											>
												<Edit className='h-4 w-4' />
											</Button>
											<Button
												variant='outline'
												size='sm'
												onClick={() => handleDeleteAnnouncement(announcement.id)}
												className='text-red-600 hover:text-red-700'
											>
												<Trash2 className='h-4 w-4' />
											</Button>
										</div>
									</TableCell>
								</TableRow>
							))}
						</TableBody>
					</Table>
					{announcements.length === 0 && (
						<div className='text-center py-8 text-gray-500'>
							No announcements found. Create your first announcement!
						</div>
					)}
				</CardContent>
			</Card>

			{/* Edit Announcement Dialog */}
			<Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
				<DialogContent className='max-w-2xl'>
					<DialogHeader>
						<DialogTitle>Edit Announcement</DialogTitle>
					</DialogHeader>
					<div className='space-y-4'>
						<div>
							<Label htmlFor='edit-title'>Title</Label>
							<Input
								id='edit-title'
								value={formData.title}
								onChange={(e) => setFormData({ ...formData, title: e.target.value })}
								placeholder='Announcement title'
							/>
						</div>
						<div>
							<Label htmlFor='edit-content'>Content</Label>
							<Textarea
								id='edit-content'
								value={formData.content}
								onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
									setFormData({ ...formData, content: e.target.value })
								}
								placeholder='Announcement content'
								rows={4}
							/>
						</div>
						<div className='grid grid-cols-2 gap-4'>
							<div>
								<Label htmlFor='edit-priority'>Priority</Label>
								<Select
									value={formData.priority}
									onValueChange={(value: 'low' | 'medium' | 'high') =>
										setFormData({ ...formData, priority: value })
									}
								>
									<SelectTrigger>
										<SelectValue placeholder='Select priority' />
									</SelectTrigger>
									<SelectContent>
										<SelectItem value='low'>Low</SelectItem>
										<SelectItem value='medium'>Medium</SelectItem>
										<SelectItem value='high'>High</SelectItem>
									</SelectContent>
								</Select>
							</div>
							<div>
								<Label htmlFor='edit-expiresAt'>Expires On (Optional)</Label>
								<Input
									id='edit-expiresAt'
									type='date'
									value={formData.expiresAt}
									onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
								/>
							</div>
						</div>
						<div className='flex items-center space-x-2'>
							<input
								type='checkbox'
								id='edit-isActive'
								checked={formData.isActive}
								onChange={(e) => setFormData({ ...formData, isActive: e.target.checked })}
								className='rounded'
							/>
							<Label htmlFor='edit-isActive'>Active (visible to users)</Label>
						</div>
						<div className='flex gap-2 justify-end'>
							<Button variant='outline' onClick={() => setIsEditDialogOpen(false)}>
								Cancel
							</Button>
							<Button onClick={handleEditAnnouncement}>Update Announcement</Button>
						</div>
					</div>
				</DialogContent>
			</Dialog>
		</div>
	);
}
