import { DashboardVisibility, Treelogy } from '../models/index.js';
import { successResponse, errorResponse } from '../utils/response.js';

// Get all dashboard visibility settings for a project
const getDashboardVisibility = async (req, res) => {
  try {
    const { treelogy_id } = req.params;

    const visibilitySettings = await DashboardVisibility.findAll({
      where: { treelogy_id },
      order: [['card_name', 'ASC']]
    });

    return successResponse(res, 200, 'Dashboard visibility settings retrieved successfully', visibilitySettings);
  } catch (error) {
    console.error('Error getting dashboard visibility:', error);
    return errorResponse(res, 'Failed to retrieve dashboard visibility settings', 500);
  }
};

// Update dashboard visibility settings for a project
const updateDashboardVisibility = async (req, res) => {
  try {
    const { treelogy_id } = req.params;
    const { visibilitySettings } = req.body;

    if (!Array.isArray(visibilitySettings)) {
      return errorResponse(res, 'visibilitySettings must be an array', 400);
    }

    // Validate that the project exists
    const project = await Treelogy.findByPk(treelogy_id);
    if (!project) {
      return errorResponse(res, 'Project not found', 404);
    }

    // Update or create visibility settings
    for (const setting of visibilitySettings) {
      const { card_id, card_name, card_type, is_visible } = setting;

      if (!card_id || !card_name) {
        return errorResponse(res, 'card_id and card_name are required', 400);
      }

      await DashboardVisibility.upsert({
        treelogy_id,
        card_id,
        card_name,
        card_type: card_type || 'card',
        is_visible: is_visible !== undefined ? is_visible : true
      });
    }

    // Get updated settings
    const updatedSettings = await DashboardVisibility.findAll({
      where: { treelogy_id },
      order: [['card_name', 'ASC']]
    });

    return successResponse(res, 200, 'Dashboard visibility settings updated successfully', updatedSettings);
  } catch (error) {
    console.error('Error updating dashboard visibility:', error);
    return errorResponse(res, 'Failed to update dashboard visibility settings', 500);
  }
};

// Get all available dashboard cards/charts (for super admin to configure)
const getAvailableDashboardItems = async (req, res) => {
  try {
    // Define all available dashboard items - only the ones actually used in the dashboard
    const availableItems = [
      // Statistics Cards (6 cards)
      { card_id: 'total_trees', card_name: 'Total Trees Surveyed', card_type: 'card', description: 'Total number of trees surveyed in the project' },
      { card_id: 'qc_completed', card_name: 'QC Completed', card_type: 'card', description: 'Number of trees that have passed quality control' },
      { card_id: 'qc_pending', card_name: 'QC Pending', card_type: 'card', description: 'Number of trees awaiting quality control review' },
      { card_id: 'today_entries', card_name: 'Today Entries', card_type: 'card', description: 'Number of trees entered today' },
      { card_id: 'this_week_entries', card_name: 'This Week Entries', card_type: 'card', description: 'Number of trees entered this week' },
      { card_id: 'this_month_entries', card_name: 'This Month Entries', card_type: 'card', description: 'Number of trees entered this month' },
      
      // Charts (5 charts)
      { card_id: 'condition_chart', card_name: 'Condition wise Donut Chart', card_type: 'chart', description: 'Donut chart showing healthy, average, poor, and dead trees' },
      { card_id: 'remark_chart', card_name: 'Remark wise Tree Count', card_type: 'chart', description: 'Pyramid chart showing tree remarks like diseased, mechanically cut, etc.' },
      { card_id: 'ownership_chart', card_name: 'Ownership wise Pie Chart', card_type: 'chart', description: 'Pie chart showing tree ownership categories' },
      { card_id: 'species_chart', card_name: 'Species wise Tree Count (Top 15)', card_type: 'chart', description: 'Bar chart showing top 15 tree species' },
      { card_id: 'economic_importance_chart', card_name: 'Economic Importance wise Tree Count', card_type: 'chart', description: 'Bar chart showing economic importance categories' }
    ];

    return successResponse(res, 200, 'Available dashboard items retrieved successfully', availableItems);
  } catch (error) {
    console.error('Error getting available dashboard items:', error);
    return errorResponse(res, 'Failed to retrieve available dashboard items', 500);
  }
};

// Initialize dashboard visibility for a new project
const initializeDashboardVisibility = async (req, res) => {
  try {
    const { treelogy_id } = req.params;

    // Validate that the project exists
    const project = await Treelogy.findByPk(treelogy_id);
    if (!project) {
      return errorResponse(res, 'Project not found', 404);
    }

    // Check if visibility settings already exist
    const existingSettings = await DashboardVisibility.findOne({
      where: { treelogy_id }
    });

    if (existingSettings) {
      return errorResponse(res, 'Dashboard visibility settings already exist for this project', 400);
    }

    // Get available items - only the ones we're actually using
    const availableItems = [
      // Statistics Cards (6 cards)
      { card_id: 'total_trees', card_name: 'Total Trees Surveyed', card_type: 'card', is_visible: true },
      { card_id: 'qc_completed', card_name: 'QC Completed', card_type: 'card', is_visible: true },
      { card_id: 'qc_pending', card_name: 'QC Pending', card_type: 'card', is_visible: true },
      { card_id: 'today_entries', card_name: 'Today Entries', card_type: 'card', is_visible: true },
      { card_id: 'this_week_entries', card_name: 'This Week Entries', card_type: 'card', is_visible: true },
      { card_id: 'this_month_entries', card_name: 'This Month Entries', card_type: 'card', is_visible: true },
      
      // Charts (5 charts)
      { card_id: 'condition_chart', card_name: 'Condition wise Donut Chart', card_type: 'chart', is_visible: true },
      { card_id: 'remark_chart', card_name: 'Remark wise Tree Count', card_type: 'chart', is_visible: true },
      { card_id: 'ownership_chart', card_name: 'Ownership wise Pie Chart', card_type: 'chart', is_visible: true },
      { card_id: 'species_chart', card_name: 'Species wise Tree Count (Top 15)', card_type: 'chart', is_visible: true },
      { card_id: 'economic_importance_chart', card_name: 'Economic Importance wise Tree Count', card_type: 'chart', is_visible: true }
    ];

    // Create initial visibility settings
    const createdSettings = await DashboardVisibility.bulkCreate(
      availableItems.map(item => ({
        treelogy_id,
        ...item
      }))
    );

    return successResponse(res, 200, 'Dashboard visibility settings initialized successfully', createdSettings);
  } catch (error) {
    console.error('Error initializing dashboard visibility:', error);
    return errorResponse(res, 'Failed to initialize dashboard visibility settings', 500);
  }
};

export {
  getDashboardVisibility,
  updateDashboardVisibility,
  getAvailableDashboardItems,
  initializeDashboardVisibility
};
