'use client';

import {useCallback, useEffect, useState} from 'react';
import type {CommerceFilterState} from '../types/commerce';
import {
  BUSINESS_ALERTS,
  COMMERCE_KPIS,
  PAYMENT_BREAKDOWN_DATA,
  TOP_PRODUCTS_DATA,
} from '../services/commerceService';
import {exportData} from '@/shared/utils/export/exportManager';

const STORAGE_WIDTH_KEY = 'loyaly.commerce.pulsePanelWidth';
const DEFAULT_PANEL_WIDTH = 340;

export function useCommerce() {
  const [filters, setFilters] = useState<CommerceFilterState>({
    dateRange: 'today',
    storeId: 'all',
    category: 'all',
    paymentMethod: 'all',
    salesChannel: 'all',
  });

  const [isPanelOpen, setIsPanelOpen] = useState(true);
  const [panelWidth, setPanelWidth] = useState(DEFAULT_PANEL_WIDTH);

  useEffect(() => {
    try {
      const saved = localStorage.getItem(STORAGE_WIDTH_KEY);
      if (saved) {
        const parsed = parseInt(saved, 10);
        if (!isNaN(parsed) && parsed >= 280 && parsed <= 500) {
          setPanelWidth(parsed);
        }
      }
    } catch {
      /* ignore */
    }
  }, []);

  const updatePanelWidth = useCallback((width: number) => {
    const clamped = Math.max(280, Math.min(width, 500));
    setPanelWidth(clamped);
    try {
      localStorage.setItem(STORAGE_WIDTH_KEY, clamped.toString());
    } catch {
      /* ignore */
    }
  }, []);

  const handleExport = useCallback(async (format: 'pdf' | 'excel' | 'csv') => {
    const dataRows = [
      {metric: 'Total Revenue', value: COMMERCE_KPIS.revenue.value, change: COMMERCE_KPIS.revenue.change},
      {metric: 'Total Orders', value: COMMERCE_KPIS.orders.value, change: COMMERCE_KPIS.orders.change},
      {metric: 'Average Order Value', value: COMMERCE_KPIS.aov.value, change: COMMERCE_KPIS.aov.change},
      {metric: 'Net Sales', value: COMMERCE_KPIS.netSales.value, change: COMMERCE_KPIS.netSales.change},
      {metric: 'Refunds', value: COMMERCE_KPIS.refunds.value, change: COMMERCE_KPIS.refunds.change},
      {metric: 'Conversion Rate', value: COMMERCE_KPIS.conversion.value, change: COMMERCE_KPIS.conversion.change},
    ];

    await exportData({
      filename: `Commerce_Analytics_${new Date().toISOString().slice(0, 10)}`,
      title: 'Loyaly Commerce Business Intelligence Report',
      subtitle: `Generated on ${new Date().toLocaleDateString()} • Date Range: ${filters.dateRange.toUpperCase()}`,
      columns: [
        {key: 'metric', header: 'Metric Name'},
        {key: 'value', header: 'Current Value'},
        {key: 'change', header: 'Trend / Delta'},
      ],
      data: dataRows,
      format,
    });
  }, [filters]);

  return {
    filters,
    setFilters,
    isPanelOpen,
    setIsPanelOpen,
    panelWidth,
    updatePanelWidth,
    handleExport,
    kpis: COMMERCE_KPIS,
    alerts: BUSINESS_ALERTS,
    topProducts: TOP_PRODUCTS_DATA,
    paymentSplits: PAYMENT_BREAKDOWN_DATA,
  };
}
