'use client';

import { Text, View, StyleSheet } from '@react-pdf/renderer';
import { ReactNode } from 'react';
import type { PdfColumn } from './types';

const styles = StyleSheet.create({
  tableRow: {
    flexDirection: 'row',
  },
  tableHeader: {
    backgroundColor: '#F5F5F5',
  },
  tableCellHeader: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 7,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
    textAlign: 'center',
  },
  tableCellHeaderRight: {
    flex: 1,
    borderRightWidth: 1,
    borderRightColor: '#000000',
    borderRightStyle: 'solid',
    padding: 4,
    fontSize: 7,
    fontWeight: 'bold',
    backgroundColor: '#F5F5F5',
    textAlign: 'right',
    borderBottomWidth: 1,
    borderBottomColor: '#000000',
    borderBottomStyle: 'solid',
    paddingVertical: 12,
  },
});

interface PdfTheadProps<TData = Record<string, unknown>> {
  columns: PdfColumn<TData>[];
  data?: TData[];
}

export const PdfThead = <TData = Record<string, unknown>,>({
  columns,
  data,
}: PdfTheadProps<TData>) => {
  return (
    <View style={[styles.tableRow, styles.tableHeader]}>
      {columns.map((column, index) => {
        const isLastColumn = index === columns.length - 1;

        // Get header content from column definition
        let headerContent: ReactNode;
        if (typeof column.header === 'function') {
          headerContent = column.header(data || []);
        } else {
          headerContent = column.header || column.key;
        }

        // Determine alignment - columns align right by default for numeric data
        const align = column.align || 'left';

        const cellStyle =
          align === 'right'
            ? [
                styles.tableCellHeaderRight,
                {
                  flex: column.flex || 1,
                  textAlign: 'right' as const,
                  borderRightWidth: isLastColumn ? 0 : 1,
                },
              ]
            : [
                styles.tableCellHeader,
                {
                  flex: column.flex || 1,
                  textAlign: align as 'left' | 'center' | 'right',
                  borderRightWidth: isLastColumn ? 0 : 1,
                },
              ];

        return (
          <View key={column.key} style={cellStyle}>
            {typeof headerContent === 'string' ? (
              <Text>{headerContent}</Text>
            ) : (
              headerContent
            )}
          </View>
        );
      })}
    </View>
  );
};

export type { PdfColumn };
