import { useState, useEffect } from 'react';
import { taskService } from '../services/taskService';
import { projectService } from '../services/projectService';
import { apiClient } from '../services/apiClient';
import { API_BASE_URL } from '../services/apiConfig'; // 👈 Import base path

export function useProjectBoard(projectId) {
  const [project, setProject] = useState(null);
  const [sections, setSections] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  // 1. Fetch initial board data
  const fetchBoardData = async () => {
    try {
      setIsLoading(true);

      const [projRes, secRes, taskRes] = await Promise.all([
        projectService.getProjectDetail(projectId).catch(() => null),
        apiClient(`/sections/list.php?project=${projectId}`).catch(() => []),
        taskService.getTasks(projectId).catch(() => []),
      ]);

      // Set Dynamic Project Info
      if (projRes) {
        setProject(projRes.project || projRes);
      }

      // Default fallback sections if none exist yet
      const defaultSections = [
        { id: 1, name: 'To Do' },
        { id: 2, name: 'In Progress' },
        { id: 3, name: 'Done' },
      ];

      setSections(Array.isArray(secRes) && secRes.length > 0 ? secRes : defaultSections);

      const rawTasks = Array.isArray(taskRes) ? taskRes : taskRes?.tasks || taskRes?.data || [];
      setTasks(rawTasks);
    } catch (err) {
      console.error('Failed to load board data:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    if (projectId) fetchBoardData();
  }, [projectId]);

  // 2. Real-time SSE Stream Connection
  useEffect(() => {
    if (!projectId) return;

    // 🔑 Full URL ensures stream.php points to /HZ-ProjectHub-v2/backend/api/tasks/stream.php
    const streamUrl = `${API_BASE_URL}/tasks/stream.php?project_id=${projectId}`;

    const eventSource = new EventSource(streamUrl, {
      withCredentials: true, // Passes PHP session cookies
    });

    eventSource.addEventListener('connected', () => {
      console.log(`[SSE Connected] Listening for updates on project ${projectId}`);
    });

    // Handle real-time updates pushed from backend stream.php
    eventSource.addEventListener('task_update', (event) => {
      try {
        const updatedTasks = JSON.parse(event.data);
        if (Array.isArray(updatedTasks) && updatedTasks.length > 0) {
          setTasks((prevTasks) => {
            const currentTasks = Array.isArray(prevTasks) ? [...prevTasks] : [];

            updatedTasks.forEach((updatedTask) => {
              const existingIndex = currentTasks.findIndex((t) => t.id === updatedTask.id);
              if (existingIndex > -1) {
                // Update existing task
                currentTasks[existingIndex] = { ...currentTasks[existingIndex], ...updatedTask };
              } else {
                // Add new task
                currentTasks.push(updatedTask);
              }
            });

            return currentTasks;
          });
        }
      } catch (err) {
        console.error('Failed to parse SSE task update payload:', err);
      }
    });

    eventSource.onerror = (err) => {
      console.warn('SSE stream connection interrupted. Retrying...', err);
    };

    // Clean up event connection when leaving board page or changing projects
    return () => {
      eventSource.close();
    };
  }, [projectId]);

  // 3. Add task action
  const addTask = async (sectionId, newTaskData) => {
    try {
      const payload = {
        project_id: parseInt(projectId, 10),
        section_id: parseInt(sectionId, 10),
        title: newTaskData.title.trim(),
      };

      const res = await taskService.createTask(payload);

      if (res?.task) {
        setTasks((prev) => [...(Array.isArray(prev) ? prev : []), res.task]);
        return res.task;
      } else {
        await fetchBoardData();
      }
    } catch (err) {
      console.error('Failed to save task to backend:', err);
      throw err;
    }
  };

  return {
    project,
    sections,
    setSections,
    tasks: Array.isArray(tasks) ? tasks : [],
    setTasks,
    isLoading,
    addTask,
    refreshBoard: fetchBoardData,
  };
}