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

const DEFAULT_CATEGORIES = [
  { name: 'meeting', color: '#3b82f6', is_custom: false, label: 'Meeting' },
  { name: 'task', color: '#22c55e', is_custom: false, label: 'Task' },
  { name: 'deadline', color: '#ef4444', is_custom: false, label: 'Deadline' },
  { name: 'personal', color: '#a855f7', is_custom: false, label: 'Personal' },
  { name: 'blocked', color: '#64748b', is_custom: false, label: 'Blocked' },
];

export function useStaffCalendarCategories() {
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(true);
  const { user } = useAuth();
  const { toast } = useToast();

  const fetchCategories = useCallback(async () => {
    if (!user) return;
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('staff_calendar_category_preferences')
        .select('*')
        .eq('user_id', user.id);

      if (error) throw error;

      const mergedCategories = DEFAULT_CATEGORIES.map(def => {
        const existing = data.find(d => d.category_name === def.name);
        if (existing) {
          return { 
            ...existing, 
            label: def.label,
            is_custom: false
          };
        }
        return {
          category_name: def.name,
          color: def.color,
          is_visible: true,
          is_custom: false,
          label: def.label,
        };
      });

      const customCategories = data.filter(d => 
        d.is_custom === true
      ).map(c => ({
        ...c,
        label: c.category_name
      }));

      setCategories([...mergedCategories, ...customCategories]);

    } catch (err) {
      console.error('Error fetching categories:', err);
      toast({ variant: "destructive", title: "Error", description: "Failed to load category settings." });
    } finally {
      setLoading(false);
    }
  }, [user, toast]);

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

  const toggleCategory = async (category) => {
    const newVisibility = !category.is_visible;
    
    setCategories(prev => prev.map(c => 
      c.category_name === category.category_name ? { ...c, is_visible: newVisibility } : c
    ));

    try {
      const { data, error } = await supabase
        .from('staff_calendar_category_preferences')
        .upsert({
          user_id: user.id,
          category_name: category.category_name,
          is_visible: newVisibility,
          color: category.color,
          is_custom: category.is_custom
        }, { onConflict: 'user_id, category_name' })
        .select()
        .single();

      if (error) throw error;
      
      setCategories(prev => prev.map(c => 
        c.category_name === category.category_name ? { ...c, id: data.id } : c
      ));

    } catch (err) {
      console.error('Error toggling category:', err);
      toast({ variant: "destructive", title: "Error", description: "Failed to save preference." });
      fetchCategories();
    }
  };

  const addCustomCategory = async (name, color) => {
    if (!name) return;
    
    if (categories.some(c => c.category_name.toLowerCase() === name.toLowerCase())) {
      toast({ variant: "destructive", title: "Duplicate", description: "Category already exists." });
      return;
    }

    try {
      const { data, error } = await supabase
        .from('staff_calendar_category_preferences')
        .insert({
          user_id: user.id,
          category_name: name,
          is_visible: true,
          color: color,
          is_custom: true
        })
        .select()
        .single();

      if (error) throw error;

      setCategories(prev => [...prev, { ...data, label: data.category_name }]);
      toast({ title: "Success", description: "Category created." });
    } catch (err) {
      console.error('Error creating category:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
    }
  };

  const deleteCustomCategory = async (id) => {
    try {
      const { error } = await supabase
        .from('staff_calendar_category_preferences')
        .delete()
        .eq('id', id);

      if (error) throw error;

      setCategories(prev => prev.filter(c => c.id !== id));
      toast({ title: "Success", description: "Category deleted." });
    } catch (err) {
      console.error('Error deleting category:', err);
      toast({ variant: "destructive", title: "Error", description: err.message });
    }
  };

  return {
    categories,
    loading,
    toggleCategory,
    addCustomCategory,
    deleteCustomCategory,
    refreshCategories: fetchCategories
  };
}
