'use client';

import {Button} from '@astryxdesign/core/Button';
import {Icon} from '@astryxdesign/core/Icon';
import {useToast} from '@astryxdesign/core/Toast';
import {useRouter} from 'next/navigation';
import {ICONS} from '@/shared/utils/icons';
import type {ReportAction} from '@/features/loyaly-ai/types/chat';

import {exportData} from '@/shared/utils/export/exportManager';

export function ActionToolbarBlock({actions}: {actions: ReportAction[]}) {
  const router = useRouter();
  const toast = useToast();

  if (!actions || actions.length === 0) return null;

  const handleActionClick = async (act: ReportAction) => {
    switch (act.actionType) {
      case 'open_dashboard':
        router.push('/dashboard');
        break;
      case 'compare_stores':
        router.push('/stores');
        break;
      case 'view_rewards':
        router.push('/lyts');
        break;
      case 'export_csv':
        try {
          await exportData({
            filename: 'Loyaly_AI_Report',
            title: 'Loyaly AI Business Report',
            subtitle: 'Exported from Loyaly AI Assistant',
            columns: [
              {key: 'metric', header: 'Metric Name'},
              {key: 'val', header: 'Value'},
            ],
            data: [
              {metric: 'Daily Revenue', val: '₹3,40,000'},
              {metric: 'Visitors', val: '1,284'},
              {metric: 'Purchases', val: '276'},
            ],
            format: 'csv',
          });
          toast({body: '✓ CSV downloaded successfully'});
        } catch {
          toast({body: '❌ Download failed'});
        }
        break;
      case 'download_report':
        try {
          await exportData({
            filename: 'Loyaly_AI_Report',
            title: 'Loyaly AI Business Report',
            subtitle: 'Exported from Loyaly AI Assistant',
            columns: [
              {key: 'metric', header: 'Metric Name'},
              {key: 'val', header: 'Value'},
            ],
            data: [
              {metric: 'Daily Revenue', val: '₹3,40,000'},
              {metric: 'Visitors', val: '1,284'},
              {metric: 'Purchases', val: '276'},
            ],
            format: 'pdf',
          });
          toast({body: '✓ PDF downloaded successfully'});
        } catch {
          toast({body: '❌ Download failed'});
        }
        break;
      default:
        toast({body: `Executed: ${act.label}`});
        break;
    }
  };

  return (
    <div className="pt-2 flex flex-wrap items-center gap-2 w-full">
      {actions.map((act) => (
        <Button
          key={act.id || act.label}
          size="sm"
          variant="secondary"
          label={act.label}
          icon={
            act.iconName ? (
              <Icon icon={(ICONS as any)[act.iconName] || 'externalLink'} size="sm" />
            ) : undefined
          }
          onClick={() => handleActionClick(act)}
        />
      ))}
    </div>
  );
}
