import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } 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 { Switch } from "@/components/ui/switch";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from '@/contexts/AuthContext';
import { Lock, Loader2, Trash2, Clock } from 'lucide-react';
import { format } from 'date-fns';
import { supabase } from '@/integrations/supabase/client';

export default function CalendarBlockedDateDialog({ 
  open, 
  onOpenChange, 
  eventToEdit, 
  onSuccess 
}) {
  const { user } = useAuth();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  
  const [formData, setFormData] = useState({
    title: 'Blocked Date',
    description: '',
    date: format(new Date(), 'yyyy-MM-dd'),
    allDay: true,
    startTime: '09:00',
    endTime: '17:00',
  });

  useEffect(() => {
    if (open) {
      if (eventToEdit) {
        setFormData({
          title: eventToEdit.title || 'Blocked Date',
          description: eventToEdit.reason || eventToEdit.description || '',
          date: eventToEdit.start_date || format(new Date(), 'yyyy-MM-dd'),
          allDay: true,
          startTime: '09:00',
          endTime: '17:00',
        });
      } else {
        setFormData({
          title: 'Blocked Date',
          description: '',
          date: format(new Date(), 'yyyy-MM-dd'),
          allDay: true,
          startTime: '09:00',
          endTime: '17:00',
        });
      }
    }
  }, [open, eventToEdit]);

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

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

      if (eventToEdit) {
        const { error } = await supabase.from('blocked_dates').update({
          title: formData.title,
          reason: formData.description,
          start_date: formData.date,
          end_date: formData.date,
        }).eq('id', eventToEdit.id);
        if (error) throw error;
      } else {
        // Need an association_id - we'll require it or use a default
        const { data: assocs } = await supabase.from('associations').select('id').eq('status', 'active').limit(1);
        const assocId = assocs?.[0]?.id;
        if (!assocId) throw new Error("No association found");

        const { error } = await supabase.from('blocked_dates').insert({
          title: formData.title,
          reason: formData.description,
          start_date: formData.date,
          end_date: formData.date,
          association_id: assocId,
          created_by: user?.id,
        });
        if (error) throw error;
      }

      toast({ title: 'Date Blocked', description: `Date ${formData.date} has been blocked.` });
      if (onSuccess) onSuccess();
      onOpenChange(false);

    } catch (error) {
      console.error("Error saving blocked date:", error);
      toast({ variant: "destructive", title: "Error", description: error.message || "Failed to save blocked date" });
    } finally {
      setLoading(false);
    }
  };

  const handleUnblock = async () => {
    if (!eventToEdit) return;
    setLoading(true);
    try {
       const { error } = await supabase.from('blocked_dates').delete().eq('id', eventToEdit.id);
       if (error) throw error;
       toast({ title: "Date Unblocked", description: "The blocked event has been removed." });
       if (onSuccess) onSuccess();
       onOpenChange(false);
    } catch (error) {
        toast({ variant: "destructive", title: "Error", description: error.message });
    } finally {
        setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2 text-destructive">
            <Lock className="w-5 h-5" /> 
            {eventToEdit ? 'Edit Blocked Date' : 'Block a Date'}
          </DialogTitle>
          <DialogDescription>Blocking a date prevents scheduling on this day.</DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-4 py-4">
          <div className="space-y-2">
            <Label htmlFor="date">Date to Block</Label>
            <Input id="date" type="date" value={formData.date} onChange={(e) => setFormData({ ...formData, date: e.target.value })} required />
          </div>

          <div className="flex items-center space-x-2 border p-3 rounded-md bg-muted/30">
            <Switch id="all-day" checked={formData.allDay} onCheckedChange={(checked) => setFormData({ ...formData, allDay: checked })} />
            <Label htmlFor="all-day" className="flex-1 cursor-pointer font-medium">Block Entire Day</Label>
          </div>

          {!formData.allDay && (
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="start-time" className="flex items-center gap-1.5"><Clock className="w-3.5 h-3.5" /> Start Time</Label>
                <Input id="start-time" type="time" value={formData.startTime} onChange={(e) => setFormData({ ...formData, startTime: e.target.value })} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="end-time" className="flex items-center gap-1.5"><Clock className="w-3.5 h-3.5" /> End Time</Label>
                <Input id="end-time" type="time" value={formData.endTime} onChange={(e) => setFormData({ ...formData, endTime: e.target.value })} required />
              </div>
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="title">Label</Label>
            <Input id="title" value={formData.title} onChange={(e) => setFormData({ ...formData, title: e.target.value })} placeholder="e.g. Holiday, Closed" />
          </div>

          <div className="space-y-2">
            <Label htmlFor="description">Internal Note (Optional)</Label>
            <Textarea id="description" value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value })} placeholder="Why is this blocked?" rows={3} />
          </div>

          <DialogFooter className="flex justify-between sm:justify-between pt-2 mt-4">
            {eventToEdit ? (
                <Button type="button" variant="outline" className="text-destructive border-destructive/20 hover:bg-destructive/5" onClick={handleUnblock} disabled={loading}>
                    <Trash2 className="w-4 h-4 mr-2" /> Unblock
                </Button>
            ) : <div />}
            <div className="flex gap-2">
                <Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>
                <Button type="submit" variant="destructive" disabled={loading}>
                    {loading && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                    {eventToEdit ? 'Update Block' : 'Block Date'}
                </Button>
            </div>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
