'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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Switch } from '@/components/ui/switch';
import { Plus, Edit, Trash2, Clock } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { getWeekDays } from '@/lib/utils';

interface TimeSlot {
	id: string;
	dayOfWeek: number;
	startTime: string;
	endTime: string;
	isActive: boolean;
	createdAt: string;
	updatedAt: string;
}

// Use Irish week order (Monday first)
const DAYS = getWeekDays().map((day) => day.label);
const IRISH_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0]; // Monday-Sunday in JS getDay() values

export function AdminTimeSlotManagement() {
	const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([]);
	const [loading, setLoading] = useState(false);
	const [showDialog, setShowDialog] = useState(false);
	const [editingSlot, setEditingSlot] = useState<TimeSlot | null>(null);
	const [formData, setFormData] = useState({
		dayOfWeek: 1, // Default to Monday (Irish standard)
		startTime: '',
		endTime: '',
		isActive: true,
	});
	const { toast } = useToast();

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

	const fetchTimeSlots = async () => {
		try {
			setLoading(true);
			const response = await fetch('/api/admin/time-slots');
			if (response.ok) {
				const data = await response.json();
				setTimeSlots(data.timeSlots);
			} else {
				toast({
					title: 'Error',
					description: 'Failed to fetch time slots',
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Error fetching time slots:', error);
			toast({
				title: 'Error',
				description: 'Failed to fetch time slots',
				variant: 'destructive',
			});
		} finally {
			setLoading(false);
		}
	};

	const handleSubmit = async (e: React.FormEvent) => {
		e.preventDefault();

		try {
			setLoading(true);

			const url = editingSlot ? `/api/admin/time-slots/${editingSlot.id}` : '/api/admin/time-slots';

			const method = editingSlot ? 'PUT' : 'POST';

			const response = await fetch(url, {
				method,
				headers: {
					'Content-Type': 'application/json',
				},
				body: JSON.stringify(formData),
			});

			if (response.ok) {
				toast({
					title: 'Success',
					description: editingSlot ? 'Time slot updated successfully' : 'Time slot created successfully',
				});
				fetchTimeSlots();
				setShowDialog(false);
				resetForm();
			} else {
				const error = await response.json();
				toast({
					title: 'Error',
					description: error.error || 'Failed to save time slot',
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Error saving time slot:', error);
			toast({
				title: 'Error',
				description: 'Failed to save time slot',
				variant: 'destructive',
			});
		} finally {
			setLoading(false);
		}
	};

	const handleDelete = async (id: string) => {
		if (!confirm('Are you sure you want to delete this time slot?')) {
			return;
		}

		try {
			setLoading(true);
			const response = await fetch(`/api/admin/time-slots/${id}`, {
				method: 'DELETE',
			});

			if (response.ok) {
				toast({
					title: 'Success',
					description: 'Time slot deleted successfully',
				});
				fetchTimeSlots();
			} else {
				const error = await response.json();
				toast({
					title: 'Error',
					description: error.error || 'Failed to delete time slot',
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Error deleting time slot:', error);
			toast({
				title: 'Error',
				description: 'Failed to delete time slot',
				variant: 'destructive',
			});
		} finally {
			setLoading(false);
		}
	};

	const handleWipeDay = async (dayOfWeek: number) => {
		const dayName = DAYS[dayOfWeek];
		if (!confirm(`Are you sure you want to delete ALL time slots for ${dayName}? This action cannot be undone.`)) {
			return;
		}

		try {
			setLoading(true);
			const slotsToDelete = timeSlots.filter((slot) => slot.dayOfWeek === dayOfWeek);

			// Delete all slots for this day
			const deletePromises = slotsToDelete.map((slot) =>
				fetch(`/api/admin/time-slots/${slot.id}`, {
					method: 'DELETE',
				})
			);

			const responses = await Promise.all(deletePromises);
			const successCount = responses.filter((response) => response.ok).length;

			if (successCount === slotsToDelete.length) {
				toast({
					title: 'Success',
					description: `All ${dayName} time slots deleted successfully`,
				});
				fetchTimeSlots();
			} else {
				toast({
					title: 'Partial Success',
					description: `${successCount} of ${slotsToDelete.length} slots deleted`,
					variant: 'destructive',
				});
			}
		} catch (error) {
			console.error('Error wiping day slots:', error);
			toast({
				title: 'Error',
				description: 'Failed to delete day slots',
				variant: 'destructive',
			});
		} finally {
			setLoading(false);
		}
	};

	const handleEdit = (slot: TimeSlot) => {
		setEditingSlot(slot);
		setFormData({
			dayOfWeek: slot.dayOfWeek,
			startTime: slot.startTime,
			endTime: slot.endTime,
			isActive: slot.isActive,
		});
		setShowDialog(true);
	};

	const resetForm = () => {
		setEditingSlot(null);
		setFormData({
			dayOfWeek: 1, // Default to Monday (Irish standard)
			startTime: '',
			endTime: '',
			isActive: true,
		});
	};

	const groupedTimeSlots = timeSlots.reduce((acc, slot) => {
		if (!acc[slot.dayOfWeek]) {
			acc[slot.dayOfWeek] = [];
		}
		acc[slot.dayOfWeek].push(slot);
		return acc;
	}, {} as Record<number, TimeSlot[]>);

	return (
		<Card>
			<CardHeader>
				<div className='flex justify-between items-center'>
					<CardTitle className='flex items-center gap-2'>
						<Clock className='h-5 w-5' />
						Time Slot Management
					</CardTitle>
					<Dialog open={showDialog} onOpenChange={setShowDialog}>
						<DialogTrigger asChild>
							<Button onClick={resetForm}>
								<Plus className='h-4 w-4 mr-2' />
								Add Time Slot
							</Button>
						</DialogTrigger>
						<DialogContent>
							<DialogHeader>
								<DialogTitle>{editingSlot ? 'Edit Time Slot' : 'Add New Time Slot'}</DialogTitle>
							</DialogHeader>
							<form onSubmit={handleSubmit} className='space-y-4'>
								<div>
									<Label htmlFor='dayOfWeek'>Day of Week</Label>
									<Select
										value={formData.dayOfWeek.toString()}
										onValueChange={(value) =>
											setFormData({ ...formData, dayOfWeek: parseInt(value) })
										}
									>
										<SelectTrigger>
											<SelectValue placeholder='Select day' />
										</SelectTrigger>
										<SelectContent>
											{IRISH_DAY_ORDER.map((jsDayOfWeek, displayIndex) => (
												<SelectItem key={jsDayOfWeek} value={jsDayOfWeek.toString()}>
													{DAYS[displayIndex]}
												</SelectItem>
											))}
										</SelectContent>
									</Select>
								</div>
								<div>
									<Label htmlFor='startTime'>Start Time</Label>
									<Input
										id='startTime'
										type='time'
										value={formData.startTime}
										onChange={(e) => setFormData({ ...formData, startTime: e.target.value })}
										required
									/>
								</div>
								<div>
									<Label htmlFor='endTime'>End Time</Label>
									<Input
										id='endTime'
										type='time'
										value={formData.endTime}
										onChange={(e) => setFormData({ ...formData, endTime: e.target.value })}
										required
									/>
								</div>
								<div className='flex items-center space-x-2'>
									<Switch
										id='isActive'
										checked={formData.isActive}
										onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
									/>
									<Label htmlFor='isActive'>Active</Label>
								</div>
								<div className='flex justify-end space-x-2'>
									<Button type='button' variant='outline' onClick={() => setShowDialog(false)}>
										Cancel
									</Button>
									<Button type='submit' disabled={loading}>
										{loading ? 'Saving...' : editingSlot ? 'Update' : 'Create'}
									</Button>
								</div>
							</form>
						</DialogContent>
					</Dialog>
				</div>
			</CardHeader>
			<CardContent>
				{loading && timeSlots.length === 0 ? (
					<div className='text-center py-4'>Loading time slots...</div>
				) : (
					<div className='space-y-6'>
						{IRISH_DAY_ORDER.map((jsDayOfWeek, displayIndex) => {
							const dayName = DAYS[displayIndex];
							return (
								<div key={jsDayOfWeek} className='space-y-2'>
									<div className='flex justify-between items-center'>
										<h3 className='font-semibold text-lg'>{dayName}</h3>
										{groupedTimeSlots[jsDayOfWeek]?.length > 0 && (
											<Button
												size='sm'
												variant='outline'
												onClick={() => handleWipeDay(jsDayOfWeek)}
												className='text-destructive hover:text-destructive/80 hover:bg-destructive/10'
												disabled={loading}
											>
												<Trash2 className='h-4 w-4 mr-1' />
												Wipe All
											</Button>
										)}
									</div>
									{groupedTimeSlots[jsDayOfWeek]?.length > 0 ? (
										<div className='grid gap-2'>
											{groupedTimeSlots[jsDayOfWeek]
												.sort((a, b) => a.startTime.localeCompare(b.startTime))
												.map((slot) => (
													<div
														key={slot.id}
														className={`flex items-center justify-between p-3 border rounded-lg ${
															slot.isActive
																? 'bg-green-50 border-green-200 dark:bg-green-950 dark:border-green-800'
																: 'bg-muted border-border'
														}`}
													>
														<div className='flex items-center space-x-3'>
															<div className='font-medium'>
																{slot.startTime} - {slot.endTime}
															</div>
															<div
																className={`px-2 py-1 rounded-full text-xs ${
																	slot.isActive
																		? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
																		: 'bg-muted text-muted-foreground'
																}`}
															>
																{slot.isActive ? 'Active' : 'Inactive'}
															</div>
														</div>
														<div className='flex space-x-2'>
															<Button
																size='sm'
																variant='outline'
																onClick={() => handleEdit(slot)}
															>
																<Edit className='h-4 w-4' />
															</Button>
															<Button
																size='sm'
																variant='outline'
																onClick={() => handleDelete(slot.id)}
																className='text-destructive hover:text-destructive/80'
															>
																<Trash2 className='h-4 w-4' />
															</Button>
														</div>
													</div>
												))}
										</div>
									) : (
										<p className='text-muted-foreground italic'>
											No time slots configured for {dayName}
										</p>
									)}
								</div>
							);
						})}
					</div>
				)}
			</CardContent>
		</Card>
	);
}
