
import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Loader2, Trash2, Lock, MapPin } from 'lucide-react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useStaffCalendarCategories } from '@/hooks/useStaffCalendarCategories';

export function StaffEventDialog({ open, onOpenChange, event, onSave, onDelete }) {
  const { categories, loading: categoriesLoading } = useStaffCalendarCategories();
  const { register, handleSubmit, reset, setValue, watch, formState: { errors, isSubmitting } } = useForm({
    defaultValues: {
      title: '',
      description: '',
      location: '',
      start_date: '',
      start_time: '',
      end_date: '',
      end_time: '',
      category: 'meeting',
    }
  });

  const selectedCategory = watch('category');

  useEffect(() => {
    if (open && event) {
      const start = new Date(event.start_time);
      const end = new Date(event.end_time);
      
      reset({
        title: event.title,
        description: event.description || '',
        location: event.location || '',
        start_date: start.toISOString().split('T')[0],
        start_time: start.toTimeString().slice(0, 5),
        end_date: end.toISOString().split('T')[0],
        end_time: end.toTimeString().slice(0, 5),
        category: event.category || 'meeting',
      });
    } else if (open) {
      const now = new Date();
      const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
      
      reset({
        title: '',
        description: '',
        location: '',
        start_date: now.toISOString().split('T')[0],
        start_time: now.toTimeString().slice(0, 5),
        end_date: oneHourLater.toISOString().split('T')[0],
        end_time: oneHourLater.toTimeString().slice(0, 5),
        category: 'meeting',
      });
    }
  }, [open, event, reset]);

  const onSubmit = async (data) => {
    if (data.category === 'client') return; 

    const startDateTime = new Date(`${data.start_date}T${data.start_time}`);
    const endDateTime = new Date(`${data.end_date}T${data.end_time}`);

    if (endDateTime <= startDateTime) {
      alert("End time must be after start time");
      return;
    }

    const payload = {
      title: data.title,
      description: data.description,
      location: data.location,
      start_time: startDateTime.toISOString(),
      end_time: endDateTime.toISOString(),
      category: data.category,
    };

    if (event?.id) {
      await onSave(event.id, payload);
    } else {
      await onSave(null, payload);
    }
    onOpenChange(false);
  };

  const activeCategory = categories.find(c => c.category_name === selectedCategory);
  const activeColor = activeCategory?.color || 'hsl(var(--primary))';

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            {event ? 'Edit Staff Event' : 'Create Staff Event'}
            {activeColor && (
               <span 
                 className="w-3 h-3 rounded-full border border-border ml-2 shadow-sm" 
                 style={{ backgroundColor: activeColor }} 
                 title={`Category: ${selectedCategory}`}
               />
            )}
          </DialogTitle>
        </DialogHeader>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 py-4">
          <div className="space-y-2">
            <Label>Event Title</Label>
            <Input {...register('title', { required: 'Title is required' })} placeholder="e.g. Staff Meeting" />
            {errors.title && <span className="text-xs text-destructive">{errors.title.message}</span>}
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>Start Date</Label>
              <Input type="date" {...register('start_date', { required: true })} />
            </div>
            <div className="space-y-2">
              <Label>Start Time</Label>
              <Input type="time" {...register('start_time', { required: true })} />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label>End Date</Label>
              <Input type="date" {...register('end_date', { required: true })} />
            </div>
            <div className="space-y-2">
              <Label>End Time</Label>
              <Input type="time" {...register('end_time', { required: true })} />
            </div>
          </div>

          <div className="grid grid-cols-2 gap-4">
             <div className="space-y-2">
                <Label>Category</Label>
                <Select onValueChange={(val) => setValue('category', val)} value={selectedCategory}>
                    <SelectTrigger>
                      <SelectValue placeholder="Select category" />
                    </SelectTrigger>
                    <SelectContent>
                        {categoriesLoading ? (
                          <div className="p-2 text-xs text-center text-muted-foreground">Loading...</div>
                        ) : (
                          categories.map((cat) => (
                            <SelectItem key={cat.category_name} value={cat.category_name}>
                              <div className="flex items-center gap-2">
                                <div className="w-2 h-2 rounded-full" style={{ backgroundColor: cat.color }} />
                                {cat.label || cat.category_name}
                              </div>
                            </SelectItem>
                          ))
                        )}
                    </SelectContent>
                </Select>
             </div>
             <div className="space-y-2">
                <Label>Location</Label>
                <div className="relative">
                  <Input {...register('location')} placeholder="e.g. Conference Room" className="pl-8" />
                  <MapPin className="w-4 h-4 absolute left-2 top-2.5 text-muted-foreground" />
                </div>
             </div>
          </div>

          <div className="space-y-2">
            <Label>Description</Label>
            <Textarea {...register('description')} placeholder="Internal details only..." className="h-20" />
          </div>

          {event?.category === 'client' && (
             <Alert variant="destructive" className="mt-2">
                 <Lock className="w-4 h-4" />
                 <AlertDescription>
                    This appears to be a client event. You cannot edit it here.
                 </AlertDescription>
             </Alert>
          )}

          <DialogFooter className="flex justify-between sm:justify-between items-center w-full">
             <div>
                {event && onDelete && event.category !== 'client' && (
                    <Button type="button" variant="destructive" size="sm" onClick={() => onDelete(event.id)}>
                        <Trash2 className="w-4 h-4 mr-1" /> Delete
                    </Button>
                )}
             </div>
             <div className="flex gap-2">
                <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
                <Button type="submit" disabled={isSubmitting || event?.category === 'client'}>
                    {isSubmitting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                    Save Event
                </Button>
             </div>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
