<template>
  <div class="flex gap-2">
    <button
      class="btn btn-sm btn-outline"
      @click="exportToCSV"
      :disabled="!data || data.length === 0"
    >
      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
        <path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
      </svg>
      Export CSV
    </button>
    <button
      class="btn btn-sm btn-outline"
      @click="copyToClipboard"
      :disabled="!data || data.length === 0"
    >
      <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
        <path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184" />
      </svg>
      Copy
    </button>
  </div>
</template>

<script setup lang="ts">
import { useNotification } from "@kyvg/vue3-notification";

interface Props {
  data: Record<string, unknown>[];
  filename?: string;
  columns?: string[];
}

const props = withDefaults(defineProps<Props>(), {
  filename: 'stats-export',
  columns: () => []
});

const { notify } = useNotification();

function getHeaders(): string[] {
  if (props.columns.length > 0) {
    return props.columns;
  }
  if (props.data.length > 0) {
    return Object.keys(props.data[0]);
  }
  return [];
}

function convertToCSV(): string {
  const headers = getHeaders();
  const headerRow = headers.join(',');

  const rows = props.data.map(row => {
    return headers.map(header => {
      const value = row[header];
      // Escape quotes and wrap in quotes if contains comma
      if (typeof value === 'string' && (value.includes(',') || value.includes('"'))) {
        return `"${value.replace(/"/g, '""')}"`;
      }
      return value ?? '';
    }).join(',');
  });

  return [headerRow, ...rows].join('\n');
}

function exportToCSV() {
  const csv = convertToCSV();
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  link.setAttribute('href', url);
  link.setAttribute('download', `${props.filename}-${new Date().toISOString().split('T')[0]}.csv`);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);

  notify({
    title: 'Export Complete',
    text: 'CSV file downloaded successfully',
    type: 'success'
  });
}

async function copyToClipboard() {
  const csv = convertToCSV();

  try {
    await navigator.clipboard.writeText(csv);
    notify({
      title: 'Copied',
      text: 'Data copied to clipboard',
      type: 'success'
    });
  } catch {
    notify({
      title: 'Error',
      text: 'Failed to copy to clipboard',
      type: 'error'
    });
  }
}
</script>
