'use client';

import {useCallback, useEffect, useState} from 'react';
import type {CommerceFilterState} from '../types/commerce';
import {
  BUSINESS_ALERTS,
  getCommerceKpis,
  getPaymentBreakdownData,
  getTopProductsData,
} 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 kpis = getCommerceKpis(filters.storeId, filters.dateRange);

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

  return {
    filters,
    setFilters,
    isPanelOpen,
    setIsPanelOpen,
    panelWidth,
    updatePanelWidth,
    handleExport,
    kpis,
    alerts: BUSINESS_ALERTS,
    topProducts: getTopProductsData(filters.storeId, filters.dateRange),
    paymentSplits: getPaymentBreakdownData(filters.storeId, filters.dateRange),
  };
}
