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

export function useParkingRecords(filterClientId = null) {
  const [records, setRecords] = useState([]);
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();
  const { user, userRole } = useAuth();

  const fetchRecords = useCallback(async () => {
    setLoading(true);
    try {
      let query = supabase
        .from('parking_records')
        .select(`
          *,
          users:created_by (full_name),
          clients (name)
        `)
        .order('date', { ascending: false })
        .order('created_at', { ascending: false });

      if (filterClientId && filterClientId !== 'all') {
        query = query.eq('client_id', filterClientId);
      } 
      else {
        const userConstraintId = getParkingRecordsForUser({ ...user, ...userRole });
        if (userConstraintId) {
          query = query.eq('client_id', userConstraintId);
        }
      }

      const { data, error } = await query;

      if (error) throw error;
      setRecords(data || []);
    } catch (error) {
      console.error('Error fetching parking records:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to load parking records."
      });
    } finally {
      setLoading(false);
    }
  }, [filterClientId, user, userRole, toast]);

  const addRecord = useCallback(async (recordData) => {
    setLoading(true);
    try {
      const userConstraintId = getParkingRecordsForUser({ ...user, ...userRole });
      
      const payload = {
        ...recordData,
        client_id: userConstraintId || recordData.client_id, 
        created_by: user.id,
        warning_level: 'first_warning'
      };

      const { data, error } = await supabase
        .from('parking_records')
        .insert([payload])
        .select()
        .single();

      if (error) throw error;

      setRecords(prev => [data, ...prev]);
      toast({
        title: "Success",
        description: "Parking record added successfully."
      });
      return data;
    } catch (error) {
      console.error('Error adding parking record:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: error.message
      });
      return null;
    } finally {
      setLoading(false);
    }
  }, [user, userRole, toast]);

  const escalateRecord = useCallback(async (id, currentLevel) => {
    try {
      const effectiveLevel = currentLevel || 'first_warning';
      
      let nextLevel;
      switch (effectiveLevel) {
        case 'first_warning':
          nextLevel = 'second_warning';
          break;
        case 'second_warning':
          nextLevel = 'final_warning';
          break;
        default:
          console.warn(`Cannot escalate from level: ${effectiveLevel}`);
          throw new Error('Cannot escalate further.');
      }

      const { error } = await supabase
        .from('parking_records')
        .update({ warning_level: nextLevel })
        .eq('id', id);

      if (error) throw error;

      setRecords(prev => prev.map(rec => 
        rec.id === id ? { ...rec, warning_level: nextLevel } : rec
      ));
      
      toast({
        title: "Escalated",
        description: `Warning level updated to ${nextLevel.replace('_', ' ')}.`
      });
      return true;
    } catch (error) {
      console.error('Error updating warning level:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to escalate warning level."
      });
      return false;
    }
  }, [toast]);

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

      if (error) throw error;

      setRecords(prev => prev.filter(rec => rec.id !== id));
      toast({
        title: "Deleted",
        description: "Parking record removed."
      });
      return true;
    } catch (error) {
      console.error('Error deleting record:', error);
      toast({
        variant: "destructive",
        title: "Error",
        description: "Failed to delete record."
      });
      return false;
    }
  }, [toast]);

  return {
    records,
    loading,
    fetchRecords,
    addRecord,
    escalateRecord,
    deleteRecord
  };
}
