import { useState, useEffect, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { useToast } from '@/hooks/use-toast';
import { addMinutes, addHours, addDays, addWeeks } from 'date-fns';

export function useReminders() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [reminders, setReminders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchReminders = useCallback(async () => {
    if (!user) return;
    
    try {
      setLoading(true);
      const { data, error } = await supabase
        .from('reminders')
        .select('*')
        .neq('status', 'completed')
        .eq('assigned_to', user.id)
        .order('due_date', { ascending: true });

      if (error) throw error;
      setReminders(data || []);
      setError(null);
    } catch (err) {
      console.error('Error fetching reminders:', err);
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, [user]);

  useEffect(() => {
    fetchReminders();

    const channel = supabase
      .channel('reminders-realtime')
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'reminders',
          filter: `assigned_to=eq.${user?.id}`
        },
        (payload) => {
          if (payload.eventType === 'INSERT') {
            if (payload.new.status !== 'completed') {
              setReminders(prev => [...prev, payload.new].sort((a, b) => new Date(a.due_date) - new Date(b.due_date)));
            }
          } else if (payload.eventType === 'UPDATE') {
            setReminders(prev => {
              if (payload.new.status === 'completed') {
                return prev.filter(r => r.id !== payload.new.id);
              }
              return prev.map(r => r.id === payload.new.id ? payload.new : r)
                         .sort((a, b) => new Date(a.due_date) - new Date(b.due_date));
            });
          } else if (payload.eventType === 'DELETE') {
            setReminders(prev => prev.filter(r => r.id !== payload.old.id));
          }
        }
      )
      .subscribe();

    return () => {
      supabase.removeChannel(channel);
    };
  }, [user, fetchReminders]);

  const markComplete = async (reminderId) => {
    try {
      const { error } = await supabase
        .from('reminders')
        .update({ 
          status: 'completed', 
          updated_at: new Date().toISOString()
        })
        .eq('id', reminderId);

      if (error) throw error;
      return true;
    } catch (err) {
      console.error('Error completing reminder:', err);
      toast({ variant: "destructive", title: "Error", description: "Failed to complete reminder." });
      return false;
    }
  };

  const snoozeReminder = async (reminderId, durationType) => {
    try {
      const reminder = reminders.find(r => r.id === reminderId);
      if (!reminder) return false;

      const currentDue = new Date(reminder.due_date);
      let newDate;

      switch(durationType) {
        case '1h': newDate = addHours(currentDue, 1); break;
        case '1d': newDate = addDays(currentDue, 1); break;
        case '1w': newDate = addWeeks(currentDue, 1); break;
        default: newDate = addMinutes(currentDue, 15);
      }

      const { error } = await supabase
        .from('reminders')
        .update({ 
          due_date: newDate.toISOString(), 
          updated_at: new Date().toISOString() 
        })
        .eq('id', reminderId);

      if (error) throw error;
      return true;
    } catch (err) {
      console.error('Error snoozing reminder:', err);
      toast({ variant: "destructive", title: "Error", description: "Failed to snooze reminder." });
      return false;
    }
  };
  
  const deleteReminder = async (reminderId) => {
    try {
      const { error } = await supabase
        .from('reminders')
        .delete()
        .eq('id', reminderId);

      if (error) throw error;
      return true;
    } catch (err) {
      console.error('Error deleting reminder:', err);
      toast({ variant: "destructive", title: "Error", description: "Failed to delete reminder." });
      return false;
    }
  };

  const now = new Date();
  const overdueReminders = reminders.filter(r => new Date(r.due_date) < now);
  const upcomingReminders = reminders.filter(r => new Date(r.due_date) >= now);

  return {
    reminders,
    overdueReminders,
    upcomingReminders,
    loading,
    error,
    refresh: fetchReminders,
    markComplete,
    snoozeReminder,
    deleteReminder
  };
}
