import React, { useState, useMemo } from 'react';
import { ExcelRow } from '../types';

interface MatrixViewProps {
  data: ExcelRow[];
  headers: string[];
}

export function MatrixView({ data, headers }: MatrixViewProps) {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(25);

  const paginatedData = useMemo(() => {
    const start = (page - 1) * pageSize;
    return data.slice(start, start + pageSize);
  }, [data, page, pageSize]);

  const formatCellValue = (val: any, header: string = '') => {
    if (val === undefined || val === null || val === '') return '';
    
    // Convert header to lowercase for checks
    const h = header.toLowerCase();
    
    // Do NOT format columns that are clearly IDs, barcodes, or codes
    if (h.includes('id') || h.includes('no') || h.includes('code') || h.includes('art.') || h.includes('barcode') || h.includes('article')) {
      return val;
    }

    // List of keywords that typically indicate a price or numeric value to format
    const priceKeywords = ['price', 'eur', 'cost', 'msrp', 'net', 'gross', 'netto', 'brutto', 'pp', 'pph', 'uvp', 'vpe', 'stk'];
    const isPriceCol = priceKeywords.some(kw => h.includes(kw));

    // Handle numbers
    if (typeof val === 'number') {
      return val.toFixed(2);
    }

    // Handle strings that represent numbers
    if (typeof val === 'string') {
      // Normalize decimals (handle comma as decimal separator)
      const normalized = val.trim().replace(',', '.');
      const num = parseFloat(normalized);
      
      if (!isNaN(num)) {
        // Format if it's a price column OR if it already has a decimal separator (.)
        if (isPriceCol || val.includes('.') || val.includes(',')) {
          return num.toFixed(2);
        }
      }
    }

    return val;
  };

  const totalPages = Math.ceil(data.length / pageSize);

  return (
    <div className="flex flex-col h-full bg-slate-800 rounded-xl border border-slate-700 shadow-xl overflow-hidden">
      <div className="p-4 border-b border-slate-700 bg-slate-800/50">
        <h2 className="text-lg font-semibold text-white">Matrix View</h2>
        <p className="text-sm text-slate-400">All data fields formatted to 2 decimal places for numbers/prices.</p>
      </div>
      
      <div className="overflow-auto flex-1">
        <table className="w-full text-left text-sm whitespace-nowrap">
          <thead className="bg-slate-900/50 text-slate-400 sticky top-0 z-10">
            <tr>
              {headers.map((header, index) => (
                <th key={index} className="px-4 py-3 font-medium border-b border-slate-700">
                  {header}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-700/50">
            {paginatedData.map((row, rowIndex) => (
              <tr key={rowIndex} className="hover:bg-slate-700/30 transition-colors">
                {headers.map((header, colIndex) => {
                  const formattedValue = formatCellValue(row[colIndex], header);
                  return (
                    <td 
                      key={colIndex} 
                      className="px-4 py-3 text-slate-300 max-w-[200px] truncate" 
                      title={String(row[colIndex] || '')}
                    >
                      {formattedValue}
                    </td>
                  );
                })}
              </tr>
            ))}
            {paginatedData.length === 0 && (
              <tr>
                <td colSpan={headers.length} className="px-4 py-8 text-center text-slate-500">
                  No data available.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <div className="bg-slate-900 border-t border-slate-700 p-4 flex items-center justify-between text-sm text-slate-400">
        <div className="flex items-center gap-4">
          <span>Showing {Math.min((page - 1) * pageSize + 1, data.length)} to {Math.min(page * pageSize, data.length)} of {data.length} entries</span>
          <select
            value={pageSize}
            onChange={e => { setPageSize(Number(e.target.value)); setPage(1); }}
            className="bg-slate-800 border border-slate-700 rounded px-2 py-1 focus:outline-none focus:border-blue-500"
          >
            <option value={25}>25 per page</option>
            <option value={50}>50 per page</option>
            <option value={100}>100 per page</option>
          </select>
        </div>
        <div className="flex items-center gap-2">
          <button
            disabled={page === 1}
            onClick={() => setPage(p => p - 1)}
            className="px-3 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            Previous
          </button>
          <span className="px-3 py-1 font-medium text-white">Page {page} of {totalPages || 1}</span>
          <button
            disabled={page === totalPages || totalPages === 0}
            onClick={() => setPage(p => p + 1)}
            className="px-3 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            Next
          </button>
        </div>
      </div>
    </div>
  );
}
