import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-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 { Switch } from "@/components/ui/switch";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { format } from 'date-fns';
import { Loader2, Trash2, Lock, Search, Users, Globe, Clock } from 'lucide-react';
import { cn } from '@/lib/utils';

const isValidUUID = (uuid) => {
  const regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
  return typeof uuid === 'string' && regex.test(uuid);
};

export default function CalendarEventDialog({ 
  open, 
  onOpenChange, 
  selectedDate, 
  eventToEdit,
  event, 
  onSuccess
}) {
  const { user, isAdmin } = useAuth();
  const { toast } = useToast();
  
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [associations, setAssociations] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(false);

  const activeEvent = eventToEdit || event;

  const [formData, setFormData] = useState({
    title: '',
    description: '',
    date: '',
    startTime: '09:00',
    endTime: '10:00',
    type: 'meeting',
    allDay: false,
    associationId: '',
  });

  useEffect(() => {
    if (isAdmin && open) {
      const fetchAssociations = async () => {
        const { data, error } = await supabase.from('associations').select('id, name').eq('status', 'active').order('name');
        if (!error && data) setAssociations(data || []);
      };
      fetchAssociations();
    }
  }, [isAdmin, open]);

  useEffect(() => {
    if (open) {
      if (activeEvent) {
        const startDate = activeEvent.start_date ? new Date(activeEvent.start_date) : new Date();
        setFormData({
          title: activeEvent.title || '',
          description: activeEvent.description || '',
          date: format(startDate, 'yyyy-MM-dd'),
          startTime: '09:00',
          endTime: '10:00',
          type: activeEvent.event_type || 'meeting',
          allDay: activeEvent.all_day || false,
          associationId: activeEvent.association_id || '',
        });
      } else {
        const initialDate = selectedDate ? new Date(selectedDate) : new Date();
        setFormData({
          title: '',
          description: '',
          date: format(initialDate, 'yyyy-MM-dd'),
          startTime: '09:00',
          endTime: '10:00',
          type: 'meeting',
          allDay: false,
          associationId: '',
        });
      }
    }
  }, [open, selectedDate, activeEvent, isAdmin]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    try {
      if (!formData.date) throw new Error("Date is required.");
      if (!formData.title) throw new Error("Title is required.");

      const assocId = formData.associationId;
      if (!assocId) throw new Error("Please select an association.");

      let startDate = formData.date;
      let endDate = formData.date;

      const eventData = {
        title: formData.title,
        description: formData.description,
        start_date: startDate,
        end_date: endDate,
        event_type: formData.type,
        all_day: formData.allDay,
        association_id: assocId,
        created_by: user?.id,
      };

      if (activeEvent) {
        const { error } = await supabase.from('calendar_events').update(eventData).eq('id', activeEvent.id);
        if (error) throw error;
      } else {
        const { error } = await supabase.from('calendar_events').insert(eventData);
        if (error) throw error;
      }

      toast({
        title: activeEvent ? 'Event Updated' : 'Event Created',
        description: `Event successfully ${activeEvent ? 'updated' : 'created'}.`,
      });
      
      onSuccess?.();
      onOpenChange(false);

    } catch (error) {
      console.error("Error in CalendarEventDialog:", error);
      toast({ variant: 'destructive', title: 'Error', description: error.message || "Failed to save event" });
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async () => {
    if (!activeEvent) return;
    setLoading(true);
    try {
      const { error } = await supabase.from('calendar_events').delete().eq('id', activeEvent.id);
      if (error) throw error;
      toast({ title: "Event deleted" });
      onSuccess?.();
      onOpenChange(false);
    } catch (err) {
      toast({ variant: "destructive", title: "Error", description: "Failed to delete event" });
    } finally {
      setShowDeleteConfirm(false);
      setLoading(false);
    }
  };

  const filteredAssociations = associations.filter(c => 
    c.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              {activeEvent ? 'Edit Event' : 'New Event'}
            </DialogTitle>
          </DialogHeader>

          <form onSubmit={handleSubmit} className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Association</Label>
              <Select value={formData.associationId} onValueChange={(val) => setFormData({...formData, associationId: val})}>
                <SelectTrigger><SelectValue placeholder="Select Association" /></SelectTrigger>
                <SelectContent>
                  {associations.map(c => (
                    <SelectItem key={c.id} value={c.id}>{c.name}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="title">Event Title</Label>
              <Input id="title" value={formData.title} onChange={(e) => setFormData({ ...formData, title: e.target.value })} placeholder="e.g. Annual Meeting" required />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="date">Date</Label>
                <Input id="date" type="date" value={formData.date} onChange={(e) => setFormData({ ...formData, date: e.target.value })} required />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="type">Type</Label>
                <Select value={formData.type} onValueChange={(val) => setFormData({...formData, type: val})}>
                  <SelectTrigger><SelectValue placeholder="Select type" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="meeting">Meeting</SelectItem>
                    <SelectItem value="deadline">Deadline</SelectItem>
                    <SelectItem value="reminder">Reminder</SelectItem>
                    <SelectItem value="inspection">Inspection</SelectItem>
                    <SelectItem value="other">Other</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="flex items-center space-x-2 py-2">
              <Switch id="all-day" checked={formData.allDay} onCheckedChange={(checked) => setFormData({ ...formData, allDay: checked })} />
              <Label htmlFor="all-day" className="flex items-center gap-2 cursor-pointer"><Clock className="w-4 h-4" /> All Day Event</Label>
            </div>

            {!formData.allDay && (
              <div className="grid grid-cols-2 gap-4">
                <div className="grid gap-2">
                  <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 className="grid gap-2">
                  <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>
            )}

            <div className="grid gap-2">
              <Label htmlFor="description">Description</Label>
              <Textarea id="description" value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} placeholder="Add details..." rows={3} />
            </div>

            <DialogFooter className="gap-2 sm:gap-0 flex flex-col sm:flex-row sm:justify-between w-full mt-4">
              <div className="flex gap-2 order-2 sm:order-1">
                {activeEvent && (
                    <Button type="button" variant="destructive" onClick={() => setShowDeleteConfirm(true)} size="sm">
                        <Trash2 className="w-4 h-4 mr-2" /> Delete
                    </Button>
                )}
              </div>
              <div className="flex gap-2 justify-end order-1 sm:order-2">
                <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>Close</Button>
                <Button type="submit" disabled={loading}>
                  {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
                  {activeEvent ? 'Save Changes' : 'Create Event'}
                </Button>
              </div>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Event</AlertDialogTitle>
            <AlertDialogDescription>Are you sure you want to delete this event? This action cannot be undone.</AlertDialogDescription>
          </AlertDialogHeader>
          <div className="flex gap-3 justify-end">
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} disabled={loading} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              {loading ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null} Delete
            </AlertDialogAction>
          </div>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}
