import { useDatabase } from './useDatabase';
import { Q } from '@nozbe/watermelondb';
import { useEffect, useMemo, useState } from 'react';
import Task from '../models/Task';

export function useTasks(categoryId?: string, showCompleted = false) {
  const { collections } = useDatabase();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let mounted = true;
    const conditions: any[] = [];

    if (categoryId && categoryId !== 'all') {
      conditions.push(Q.where('category_id', categoryId));
    }

    if (!showCompleted) {
      conditions.push(Q.where('completed', false));
    }

    const query = conditions.length > 0
      ? collections.tasks.query(Q.and(...conditions))
      : collections.tasks.query();

    const subscription = query
      .observe()
      .subscribe({
        next: (result) => {
          if (mounted) {
            setTasks(result);
            setLoading(false);
          }
        },
        error: () => {
          if (mounted) setLoading(false);
        },
      });

    return () => {
      mounted = false;
      subscription.unsubscribe();
    };
  }, [collections, categoryId, showCompleted]);

  return { tasks, loading };
}

export function useTask(taskId: string) {
  const { collections } = useDatabase();
  return collections.tasks.find(taskId);
}

export function useTasksByDate(date: Date) {
  const { collections } = useDatabase();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);

  const startOfDay = new Date(date);
  startOfDay.setHours(0, 0, 0, 0);

  const endOfDay = new Date(date);
  endOfDay.setHours(23, 59, 59, 999);

  useEffect(() => {
    let mounted = true;
    const subscription = collections.tasks
      .query(
        Q.where('due_date', Q.between(startOfDay.getTime(), endOfDay.getTime())),
        Q.sortBy('due_date', 'asc')
      )
      .observe()
      .subscribe({
        next: (result) => {
          if (mounted) {
            setTasks(result);
            setLoading(false);
          }
        },
        error: () => {
          if (mounted) setLoading(false);
        },
      });

    return () => {
      mounted = false;
      subscription.unsubscribe();
    };
  }, [collections, startOfDay.getTime(), endOfDay.getTime()]);

  return { tasks, loading };
}

export function useOverdueTasks() {
  const { collections } = useDatabase();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);
  const now = useMemo(() => Date.now(), []);

  useEffect(() => {
    let mounted = true;
    const subscription = collections.tasks
      .query(
        Q.where('completed', false),
        Q.where('due_date', Q.lt(now)),
        Q.sortBy('due_date', 'asc')
      )
      .observe()
      .subscribe({
        next: (result) => {
          if (mounted) {
            setTasks(result);
            setLoading(false);
          }
        },
        error: () => {
          if (mounted) setLoading(false);
        },
      });

    return () => {
      mounted = false;
      subscription.unsubscribe();
    };
  }, [collections, now]);

  return { tasks, loading };
}

export function useTasksDueToday() {
  const { collections } = useDatabase();
  const [tasks, setTasks] = useState<Task[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);

    let mounted = true;
    const subscription = collections.tasks
      .query(
        Q.where('completed', false),
        Q.where('due_date', Q.between(today.getTime(), tomorrow.getTime() - 1)),
        Q.sortBy('due_date', 'asc')
      )
      .observe()
      .subscribe({
        next: (result) => {
          if (mounted) {
            setTasks(result);
            setLoading(false);
          }
        },
        error: () => {
          if (mounted) setLoading(false);
        },
      });

    return () => {
      mounted = false;
      subscription.unsubscribe();
    };
  }, [collections]);

  return { tasks, loading };
}
