import React, { useState, useCallback, useEffect, useMemo } from 'react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  LineChart, Line, AreaChart, Area,
  PieChart, Pie, Cell, Legend
} from 'recharts';
import styles from './FormGeneratorReport.module.css';
import { useLanguage } from '../../../providers/language/LanguageContext';

import type {
  FormGeneratorReportProps,
  ReportSection,
  ReportSectionKpi,
  ReportSectionBarChart,
  ReportSectionHorizontalBar,
  ReportSectionLineChart,
  ReportSectionPieChart,
  ReportSectionTable,
  ReportSectionAreaChart,
  ReportFilterState,
  ReportPeriod,
  ReportFilterConfig,
  ReportTableColumn
} from './FormGeneratorReportTypes';

// =============================================================================
// CHART COLORS
// =============================================================================

const CHART_COLORS = [
  'var(--primary-color, #f25843)',
  '#4e79a7',
  '#59a14f',
  '#f28e2b',
  '#b07aa1',
  '#76b7b2',
  '#e15759',
  '#edc948',
  '#9c755f',
  '#bab0ac'
];

// =============================================================================
// HELPER FUNCTIONS
// =============================================================================

function _defaultFormatCurrency(value: number, currencyCode: string): string {
  return `${currencyCode} ${value.toFixed(2)}`;
}

function _createFormatDateLabel(t: (key: string) => string): (dateStr: string) => string {
  const monthLabels: Record<string, string> = {
    '01': t('Jan'), '02': t('Feb'), '03': t('Mär'), '04': t('Apr'),
    '05': t('Mai'), '06': t('Jun'), '07': t('Jul'), '08': t('Aug'),
    '09': t('Sep'), '10': t('Okt'), '11': t('Nov'), '12': t('Dez'),
  };
  return (dateStr: string) => {
    const parts = dateStr.split('-');
    if (parts.length === 3) {
      return `${parseInt(parts[2], 10)}.`;
    }
    if (parts.length === 2) {
      return monthLabels[parts[1]] || parts[1];
    }
    return dateStr;
  };
}

// =============================================================================
// CUSTOM TOOLTIP
// =============================================================================

interface CustomTooltipProps {
  active?: boolean;
  payload?: any[];
  label?: string;
  formatValue?: (value: number) => string;
  formatDateLabel: (dateStr: string) => string;
}

const _CustomTooltip: React.FC<CustomTooltipProps> = ({ active, payload, label, formatValue, formatDateLabel }) => {
  if (!active || !payload?.length) return null;
  
  const displayLabel = label ? formatDateLabel(String(label)) : '';
  
  return (
    <div className={styles.customTooltip}>
      {displayLabel && <div className={styles.tooltipLabel}>{displayLabel}</div>}
      {payload.map((entry: any, i: number) => (
        <div key={i} className={styles.tooltipValue}>
          {entry.name}: <span>{formatValue ? formatValue(entry.value) : entry.value}</span>
        </div>
      ))}
    </div>
  );
};

// =============================================================================
// SECTION RENDERERS
// =============================================================================

// --- KPI Grid ---

const _renderKpiGrid = (section: ReportSectionKpi): React.ReactNode => {
  return (
    <div className={styles.kpiGrid}>
      {section.items.map((item, i) => (
        <div key={i} className={styles.kpiCard} style={item.color ? { borderLeftColor: item.color, borderLeftWidth: 3 } : undefined}>
          <span className={styles.kpiLabel}>{item.label}</span>
          <span className={styles.kpiValue}>{item.value}</span>
          {item.subtitle && <span className={styles.kpiSubtitle}>{item.subtitle}</span>}
        </div>
      ))}
    </div>
  );
};

// --- Bar Chart (vertical) ---

const _renderBarChart = (
  section: ReportSectionBarChart,
  currencyCode: string,
  formatDateLabel: (dateStr: string) => string,
  t: (key: string) => string,
): React.ReactNode => {
  if (!section.data?.length) {
    return <div className={styles.noData}>{t('Keine Daten')}</div>;
  }

  const chartData = section.data.map(d => ({
    name: formatDateLabel(d.key),
    value: d.value,
    rawKey: d.key
  }));

  const formatter = section.formatValue || ((v: number) => _defaultFormatCurrency(v, currencyCode));

  return (
    <div className={styles.chartWrapper}>
      <ResponsiveContainer width="100%" height={260} minWidth={0}>
        <BarChart data={chartData} margin={{ top: 15, right: 10, left: 10, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border-color, #333)" />
          <XAxis 
            dataKey="name" 
            tick={{ fontSize: 11, fill: 'var(--text-secondary, #888)' }}
            axisLine={{ stroke: 'var(--border-color, #333)' }}
          />
          <YAxis 
            tick={{ fontSize: 11, fill: 'var(--text-secondary, #888)' }}
            axisLine={{ stroke: 'var(--border-color, #333)' }}
            tickFormatter={(v) => formatter(v)}
            width={70}
          />
          <Tooltip content={<_CustomTooltip formatValue={formatter} formatDateLabel={formatDateLabel} />} />
          <Bar 
            dataKey="value" 
            fill={section.color || CHART_COLORS[0]} 
            radius={[4, 4, 0, 0]}
            name={t('Wert')}
          />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
};

// --- Horizontal Bar Chart ---

const _renderHorizontalBar = (section: ReportSectionHorizontalBar, currencyCode: string, t: (key: string) => string): React.ReactNode => {
  if (!section.data?.length) {
    return <div className={styles.noData}>{t('Keine Daten')}</div>;
  }

  const maxValue = Math.max(...section.data.map(d => d.value), 0.01);
  const formatter = section.formatValue || ((v: number) => _defaultFormatCurrency(v, currencyCode));

  return (
    <div className={styles.horizontalBarList}>
      {section.data.map((item, i) => (
        <div key={item.key} className={styles.horizontalBarRow}>
          <span className={styles.horizontalBarLabel} title={item.key}>{item.key}</span>
          <div className={styles.horizontalBarTrack}>
            <div 
              className={styles.horizontalBarFill}
              style={{ 
                width: `${(item.value / maxValue) * 100}%`,
                background: item.color || CHART_COLORS[i % CHART_COLORS.length]
              }}
            />
          </div>
          <span className={styles.horizontalBarValue}>{formatter(item.value)}</span>
        </div>
      ))}
    </div>
  );
};

// --- Line Chart ---

const _renderLineChart = (
  section: ReportSectionLineChart,
  currencyCode: string,
  formatDateLabel: (dateStr: string) => string,
  t: (key: string) => string,
): React.ReactNode => {
  if (!section.data?.length) {
    return <div className={styles.noData}>{t('Keine Daten')}</div>;
  }

  const formatter = section.formatValue || ((v: number) => _defaultFormatCurrency(v, currencyCode));

  return (
    <div className={styles.chartWrapper}>
      <ResponsiveContainer width="100%" height={260} minWidth={0}>
        <LineChart data={section.data} margin={{ top: 15, right: 10, left: 10, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border-color, #333)" />
          <XAxis 
            dataKey="date" 
            tick={{ fontSize: 11, fill: 'var(--text-secondary, #888)' }}
            axisLine={{ stroke: 'var(--border-color, #333)' }}
            tickFormatter={formatDateLabel}
          />
          <YAxis 
            tick={{ fontSize: 11, fill: 'var(--text-secondary, #888)' }}
            axisLine={{ stroke: 'var(--border-color, #333)' }}
            tickFormatter={formatter}
            width={70}
          />
          <Tooltip content={<_CustomTooltip formatValue={formatter} formatDateLabel={formatDateLabel} />} />
          {section.series.map((s, i) => (
            <Line 
              key={s.key}
              type="monotone"
              dataKey={s.key}
              name={s.label}
              stroke={s.color || CHART_COLORS[i % CHART_COLORS.length]}
              strokeWidth={2}
              dot={{ r: 3 }}
              activeDot={{ r: 5 }}
            />
          ))}
          {section.series.length > 1 && <Legend />}
        </LineChart>
      </ResponsiveContainer>
    </div>
  );
};

// --- Area Chart ---

const _renderAreaChart = (
  section: ReportSectionAreaChart,
  currencyCode: string,
  formatDateLabel: (dateStr: string) => string,
  t: (key: string) => string,
): React.ReactNode => {
  if (!section.data?.length) {
    return <div className={styles.noData}>{t('Keine Daten')}</div>;
  }

  const formatter = section.formatValue || ((v: number) => _defaultFormatCurrency(v, currencyCode));

  return (
    <div className={styles.chartWrapper}>
      <ResponsiveContainer width="100%" height={260} minWidth={0}>
        <AreaChart data={section.data} margin={{ top: 15, right: 10, left: 10, bottom: 5 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border-color, #333)" />
          <XAxis 
            dataKey="date" 
            tick={{ fontSize: 11, fill: 'var(--text-secondary, #888)' }}
            axisLine={{ stroke: 'var(--border-color, #333)' }}
            tickFormatter={formatDateLabel}
          />
          <YAxis 
            tick={{ fontSize: 11, fill: 'var(--text-secondary, #888)' }}
            axisLine={{ stroke: 'var(--border-color, #333)' }}
            tickFormatter={formatter}
            width={70}
          />
          <Tooltip content={<_CustomTooltip formatValue={formatter} formatDateLabel={formatDateLabel} />} />
          {section.series.map((s, i) => (
            <Area
              key={s.key}
              type="monotone"
              dataKey={s.key}
              name={s.label}
              stroke={s.color || CHART_COLORS[i % CHART_COLORS.length]}
              fill={s.color || CHART_COLORS[i % CHART_COLORS.length]}
              fillOpacity={0.15}
              strokeWidth={2}
            />
          ))}
          {section.series.length > 1 && <Legend />}
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
};

// --- Pie Chart ---

const _renderPieChart = (section: ReportSectionPieChart, currencyCode: string, t: (key: string) => string): React.ReactNode => {
  if (!section.data?.length) {
    return <div className={styles.noData}>{t('Keine Daten')}</div>;
  }

  const formatter = section.formatValue || ((v: number) => _defaultFormatCurrency(v, currencyCode));

  const chartData = section.data.map((d, i) => ({
    name: d.key,
    value: d.value,
    color: d.color || CHART_COLORS[i % CHART_COLORS.length]
  }));

  return (
    <div className={styles.pieChartContainer}>
      <div className={styles.pieChartSvg}>
        <ResponsiveContainer width="100%" height={220} minWidth={0}>
          <PieChart margin={{ top: 10, right: 0, left: 0, bottom: 10 }}>
            <Pie
              data={chartData}
              cx="50%"
              cy="50%"
              innerRadius={section.donut ? '45%' : 0}
              outerRadius="80%"
              paddingAngle={2}
              dataKey="value"
              label={false}
              labelLine={false}
            >
              {chartData.map((entry, i) => (
                <Cell key={i} fill={entry.color} />
              ))}
            </Pie>
            <Tooltip
              formatter={(value: number | undefined, name: string | undefined) => [formatter(value ?? 0), name ?? '']}
            />
          </PieChart>
        </ResponsiveContainer>
      </div>
      <div className={styles.pieLegend}>
        {chartData.map((entry, i) => (
          <div key={i} className={styles.pieLegendItem}>
            <span className={styles.pieLegendDot} style={{ background: entry.color }} />
            <span className={styles.pieLegendLabel}>{entry.name}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// --- Table (proper component because it uses useState) ---

interface ReportTableSectionProps {
  section: ReportSectionTable;
  currencyCode: string;
}

const _ReportTableSection: React.FC<ReportTableSectionProps> = ({ section, currencyCode }) => {
  const { t } = useLanguage();
  const [showAll, setShowAll] = useState(false);

  if (!section.rows?.length) {
    return <div className={styles.noData}>{t('Keine Daten')}</div>;
  }

  const maxRows = section.maxRows || 0;
  const displayRows = maxRows > 0 && !showAll 
    ? section.rows.slice(0, maxRows) 
    : section.rows;
  const hasMore = maxRows > 0 && section.rows.length > maxRows;

  const _formatCellValue = (col: ReportTableColumn, value: any, row: Record<string, any>): string => {
    if (col.formatValue) return col.formatValue(value, row);
    if (value == null) return '—';
    
    switch (col.format) {
      case 'currency':
        return _defaultFormatCurrency(Number(value), currencyCode);
      case 'number':
        return Number(value).toLocaleString('de-CH');
      case 'percent':
        return `${(Number(value) * 100).toFixed(1)}%`;
      case 'date':
        return new Date(value).toLocaleDateString('de-CH');
      default:
        return String(value);
    }
  };

  return (
    <>
      <table className={styles.reportTable}>
        <thead>
          <tr>
            {section.columns.map(col => (
              <th 
                key={col.key} 
                className={col.align === 'right' ? styles.alignRight : col.align === 'center' ? styles.alignCenter : undefined}
              >
                {col.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {displayRows.map((row, rowIdx) => (
            <tr key={rowIdx}>
              {section.columns.map(col => (
                <td 
                  key={col.key}
                  className={[
                    col.align === 'right' ? styles.alignRight : col.align === 'center' ? styles.alignCenter : '',
                    col.format === 'currency' || col.format === 'number' ? styles.monoValue : ''
                  ].filter(Boolean).join(' ')}
                >
                  {_formatCellValue(col, row[col.key], row)}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      {hasMore && !showAll && (
        <div className={styles.showMoreRow}>
          <button className={styles.showMoreButton} onClick={() => setShowAll(true)}>
            {t('Alle {count} Einträge anzeigen', { count: String(section.rows.length) })}
          </button>
        </div>
      )}
    </>
  );
};

// =============================================================================
// SECTION WRAPPER
// =============================================================================

interface SectionWrapperProps {
  section: ReportSection;
  currencyCode: string;
}

const _SectionWrapper: React.FC<SectionWrapperProps> = ({ section, currencyCode }) => {
  const { t } = useLanguage();
  const formatDateLabel = useMemo(() => _createFormatDateLabel(t), [t]);

  const spanClass = section.type === 'kpiGrid' || section.span === 'full' 
    ? styles.sectionFull 
    : section.span === 'half' 
      ? styles.sectionHalf 
      : styles.sectionFull;

  // KPI grid renders without card wrapper
  if (section.type === 'kpiGrid') {
    return (
      <div className={spanClass}>
        {section.title && <h3 className={styles.sectionTitle}>{section.title}</h3>}
        {_renderKpiGrid(section)}
      </div>
    );
  }

  const renderContent = (): React.ReactNode => {
    switch (section.type) {
      case 'barChart':
        return _renderBarChart(section, currencyCode, formatDateLabel, t);
      case 'horizontalBar':
        return _renderHorizontalBar(section, currencyCode, t);
      case 'lineChart':
        return _renderLineChart(section, currencyCode, formatDateLabel, t);
      case 'areaChart':
        return _renderAreaChart(section, currencyCode, formatDateLabel, t);
      case 'pieChart':
        return _renderPieChart(section, currencyCode, t);
      case 'table':
        return <_ReportTableSection section={section} currencyCode={currencyCode} />;
      default:
        return <div className={styles.noData}>{t('Unbekannter Sektionstyp')}</div>;
    }
  };

  return (
    <div className={`${spanClass} ${styles.sectionCard}`}>
      {section.title && <h3 className={styles.sectionTitle}>{section.title}</h3>}
      {section.description && <p className={styles.sectionDescription}>{section.description}</p>}
      {renderContent()}
    </div>
  );
};

// =============================================================================
// TOOLBAR (FILTERS + PERIOD SELECTOR)
// =============================================================================

interface ToolbarProps {
  periodSelector?: FormGeneratorReportProps['periodSelector'];
  dateRangeSelector?: FormGeneratorReportProps['dateRangeSelector'];
  filters?: ReportFilterConfig[];
  filterState: ReportFilterState;
  onFilterStateChange: (state: ReportFilterState) => void;
}

const _Toolbar: React.FC<ToolbarProps> = ({ 
  periodSelector, dateRangeSelector, filters, filterState, onFilterStateChange 
}) => {
  const { t } = useLanguage();
  const hasPeriod = !!periodSelector;
  const hasDateRange = dateRangeSelector?.enabled;
  const hasFilters = filters && filters.length > 0;

  if (!hasPeriod && !hasDateRange && !hasFilters) return null;

  const _handlePeriodChange = (period: ReportPeriod) => {
    onFilterStateChange({ ...filterState, period });
  };

  const _handleYearChange = (year: number) => {
    onFilterStateChange({ ...filterState, year });
  };

  const _handleMonthChange = (month: number) => {
    onFilterStateChange({ ...filterState, month });
  };

  const _handleFilterChange = (key: string, value: string | string[]) => {
    onFilterStateChange({
      ...filterState,
      filters: { ...filterState.filters, [key]: value }
    });
  };

  const _handleDateRangeChange = (field: 'from' | 'to', dateStr: string) => {
    const dateRange = filterState.dateRange || { from: new Date(), to: new Date() };
    onFilterStateChange({
      ...filterState,
      dateRange: { ...dateRange, [field]: new Date(dateStr) }
    });
  };

  const currentYear = new Date().getFullYear();
  const yearOptions = Array.from({ length: 5 }, (_, i) => currentYear - i);

  const monthOptions = Array.from({ length: 12 }, (_, i) => ({
    value: i + 1,
    label: String(i + 1),
  }));

  const _renderPeriodLabel = (p: ReportPeriod): string => {
    const labels: Record<ReportPeriod, string> = {
      day: t('Tagesansicht'),
      week: t('Wochenansicht'),
      month: t('Monatsansicht'),
      quarter: t('Quartalsansicht'),
      year: t('Jahresansicht')
    };
    return labels[p] || p;
  };

  return (
    <div className={styles.toolbar}>
      {/* Period Selector */}
      {hasPeriod && (
        <div className={styles.toolbarGroup}>
          <span className={styles.toolbarLabel}>{t('Zeitraum')}</span>
          <select 
            className={styles.select}
            value={filterState.period || periodSelector!.defaultPeriod}
            onChange={(e) => _handlePeriodChange(e.target.value as ReportPeriod)}
          >
            {periodSelector!.periods.map(p => (
              <option key={p} value={p}>{_renderPeriodLabel(p)}</option>
            ))}
          </select>

          {periodSelector!.showYear !== false && (
            <select 
              className={styles.select}
              value={filterState.year || currentYear}
              onChange={(e) => _handleYearChange(Number(e.target.value))}
            >
              {yearOptions.map(y => (
                <option key={y} value={y}>{y}</option>
              ))}
            </select>
          )}

          {periodSelector!.showMonth !== false && filterState.period === 'day' && (
            <select
              className={styles.select}
              value={filterState.month || new Date().getMonth() + 1}
              onChange={(e) => _handleMonthChange(Number(e.target.value))}
            >
              {monthOptions.map(m => (
                <option key={m.value} value={m.value}>{m.label}</option>
              ))}
            </select>
          )}
        </div>
      )}

      {/* Separator */}
      {hasPeriod && (hasDateRange || hasFilters) && (
        <div className={styles.toolbarSeparator} />
      )}

      {/* Date Range */}
      {hasDateRange && (
        <div className={styles.toolbarGroup}>
          <span className={styles.toolbarLabel}>{t('Von')}</span>
          <input
            type="date"
            className={styles.dateInput}
            value={filterState.dateRange?.from?.toISOString().split('T')[0] || ''}
            onChange={(e) => _handleDateRangeChange('from', e.target.value)}
          />
          <span className={styles.toolbarLabel}>{t('Bis')}</span>
          <input
            type="date"
            className={styles.dateInput}
            value={filterState.dateRange?.to?.toISOString().split('T')[0] || ''}
            onChange={(e) => _handleDateRangeChange('to', e.target.value)}
          />
        </div>
      )}

      {/* Separator */}
      {hasDateRange && hasFilters && (
        <div className={styles.toolbarSeparator} />
      )}

      {/* Custom Filters */}
      {hasFilters && filters!.map(filter => (
        <div key={filter.key} className={styles.toolbarGroup}>
          <span className={styles.toolbarLabel}>{filter.label}</span>
          {filter.type === 'text' ? (
            <input
              type="text"
              className={styles.textInput}
              placeholder={filter.placeholder || ''}
              value={(filterState.filters[filter.key] as string) || ''}
              onChange={(e) => _handleFilterChange(filter.key, e.target.value)}
            />
          ) : (
            <select
              className={styles.select}
              value={(filterState.filters[filter.key] as string) || ''}
              onChange={(e) => _handleFilterChange(filter.key, e.target.value)}
            >
              <option value="">{filter.placeholder || t('Alle')}</option>
              {filter.options?.map(opt => (
                <option key={opt.value} value={opt.value}>{opt.label}</option>
              ))}
            </select>
          )}
        </div>
      ))}
    </div>
  );
};

// =============================================================================
// MAIN COMPONENT
// =============================================================================

export const FormGeneratorReport: React.FC<FormGeneratorReportProps> = ({
  title,
  subtitle,
  sections,
  loading = false,
  noDataMessage,
  periodSelector,
  dateRangeSelector,
  filters,
  onFilterChange,
  currencyCode = 'CHF',
  className
}) => {
  const { t } = useLanguage();
  // Build initial filter state
  const initialFilterState = useMemo((): ReportFilterState => {
    const state: ReportFilterState = { filters: {} };
    
    if (periodSelector) {
      state.period = periodSelector.defaultPeriod;
      state.year = periodSelector.defaultYear || new Date().getFullYear();
      state.month = periodSelector.defaultMonth || new Date().getMonth() + 1;
    }
    
    if (dateRangeSelector?.enabled) {
      state.dateRange = {
        from: dateRangeSelector.defaultFrom || new Date(new Date().getFullYear(), 0, 1),
        to: dateRangeSelector.defaultTo || new Date()
      };
    }
    
    if (filters) {
      for (const f of filters) {
        if (f.defaultValue !== undefined) {
          state.filters[f.key] = f.defaultValue;
        }
      }
    }
    
    return state;
  }, []); // intentionally empty - only compute once

  const [filterState, setFilterState] = useState<ReportFilterState>(initialFilterState);

  // Notify parent when filters change
  const _handleFilterStateChange = useCallback((newState: ReportFilterState) => {
    setFilterState(newState);
    onFilterChange?.(newState);
  }, [onFilterChange]);

  // Initial load: notify parent of default filter state
  useEffect(() => {
    onFilterChange?.(initialFilterState);
  }, []); // intentionally once on mount

  // Loading state
  if (loading) {
    return (
      <div className={`${styles.reportContainer} ${className || ''}`}>
        {title && (
          <div className={styles.reportHeader}>
            <h2 className={styles.reportTitle}>{title}</h2>
            {subtitle && <p className={styles.reportSubtitle}>{subtitle}</p>}
          </div>
        )}
        <_Toolbar
          periodSelector={periodSelector}
          dateRangeSelector={dateRangeSelector}
          filters={filters}
          filterState={filterState}
          onFilterStateChange={_handleFilterStateChange}
        />
        <div className={styles.loadingContainer}>{t('Daten laden')}</div>
      </div>
    );
  }

  // No sections
  if (!sections || sections.length === 0) {
    return (
      <div className={`${styles.reportContainer} ${className || ''}`}>
        {title && (
          <div className={styles.reportHeader}>
            <h2 className={styles.reportTitle}>{title}</h2>
            {subtitle && <p className={styles.reportSubtitle}>{subtitle}</p>}
          </div>
        )}
        <_Toolbar
          periodSelector={periodSelector}
          dateRangeSelector={dateRangeSelector}
          filters={filters}
          filterState={filterState}
          onFilterStateChange={_handleFilterStateChange}
        />
        <div className={styles.noData}>{noDataMessage || t('Keine Daten verfügbar')}</div>
      </div>
    );
  }

  return (
    <div className={`${styles.reportContainer} ${className || ''}`}>
      {title && (
        <div className={styles.reportHeader}>
          <h2 className={styles.reportTitle}>{title}</h2>
          {subtitle && <p className={styles.reportSubtitle}>{subtitle}</p>}
        </div>
      )}

      <_Toolbar
        periodSelector={periodSelector}
        dateRangeSelector={dateRangeSelector}
        filters={filters}
        filterState={filterState}
        onFilterStateChange={_handleFilterStateChange}
      />

      <div className={styles.sectionsGrid}>
        {sections.map((section, i) => (
          <_SectionWrapper key={i} section={section} currencyCode={currencyCode} />
        ))}
      </div>
    </div>
  );
};

export default FormGeneratorReport;
