import React, { useMemo, useState } from 'react';
import { ExcelRow, COLUMNS } from '../types';
import { ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '../lib/utils';

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

export function DataCompleteness({ data, headers }: DataCompletenessProps) {
  const [sortCol, setSortCol] = useState<number | 'score'>('score');
  const [sortDesc, setSortDesc] = useState(false);
  const [page, setPage] = useState(1);
  const pageSize = 50;

  const keyColumns = [
    COLUMNS.ARTICLE_NO,
    COLUMNS.ARTICLE_NAME,
    COLUMNS.BARCODE,
    COLUMNS.TARIFF_CODE,
    COLUMNS.COUNTRY_ORIGIN,
    COLUMNS.RECOMMENDED_AGE,
    COLUMNS.DETAILS_DE,
    COLUMNS.DETAILS_EN,
    COLUMNS.LONG_DE,
    COLUMNS.LONG_EN,
    COLUMNS.SHORT_DE,
    COLUMNS.SHORT_EN,
  ];

  const processedData = useMemo(() => {
    let result = data.map((row, index) => {
      let filledKeys = 0;
      keyColumns.forEach(col => {
        if (row[col]) filledKeys++;
      });
      const score = Math.round((filledKeys / keyColumns.length) * 100);
      return { row, index, score };
    });

    result.sort((a, b) => {
      if (sortCol === 'score') {
        return sortDesc ? b.score - a.score : a.score - b.score;
      } else {
        const valA = String(a.row[sortCol] || '');
        const valB = String(b.row[sortCol] || '');
        return sortDesc ? valB.localeCompare(valA) : valA.localeCompare(valB);
      }
    });

    return result;
  }, [data, sortCol, sortDesc]);

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

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

  const handleSort = (col: number | 'score') => {
    if (sortCol === col) {
      setSortDesc(!sortDesc);
    } else {
      setSortCol(col);
      setSortDesc(col === 'score' ? false : false); // default asc
    }
  };

  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">Data Completeness</h2>
        <p className="text-sm text-slate-400">Evaluating 12 key fields per product.</p>
      </div>
      
      <div className="overflow-x-auto flex-1">
        <table className="w-full text-left text-sm">
          <thead className="bg-slate-900/50 text-slate-400 sticky top-0 z-10">
            <tr>
              <th 
                className="px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors select-none"
                onClick={() => handleSort('score')}
              >
                <div className="flex items-center gap-1">
                  Score
                  {sortCol === 'score' && (
                    sortDesc ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />
                  )}
                </div>
              </th>
              <th 
                className="px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors select-none"
                onClick={() => handleSort(COLUMNS.ARTICLE_NO)}
              >
                <div className="flex items-center gap-1">
                  Article No.
                  {sortCol === COLUMNS.ARTICLE_NO && (
                    sortDesc ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />
                  )}
                </div>
              </th>
              <th 
                className="px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors select-none"
                onClick={() => handleSort(COLUMNS.ARTICLE_NAME)}
              >
                <div className="flex items-center gap-1">
                  Article Name
                  {sortCol === COLUMNS.ARTICLE_NAME && (
                    sortDesc ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />
                  )}
                </div>
              </th>
              {keyColumns.slice(2).map(col => (
                <th key={col} className="px-4 py-3 font-medium truncate max-w-[120px]" title={headers[col]}>
                  {headers[col]}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-700/50">
            {paginatedData.map(({ row, index, score }) => (
              <tr key={index} className="hover:bg-slate-700/30 transition-colors">
                <td className="px-4 py-3">
                  <div className="flex items-center gap-2">
                    <div className="w-12 bg-slate-700 rounded-full h-2 overflow-hidden">
                      <div 
                        className={cn("h-full", score === 100 ? "bg-green-500" : score >= 50 ? "bg-yellow-500" : "bg-red-500")} 
                        style={{ width: `${score}%` }} 
                      />
                    </div>
                    <span className="font-medium text-white">{score}%</span>
                  </div>
                </td>
                <td className="px-4 py-3 font-mono text-slate-300">{row[COLUMNS.ARTICLE_NO]}</td>
                <td className="px-4 py-3 font-medium text-white max-w-[200px] truncate" title={row[COLUMNS.ARTICLE_NAME]}>{row[COLUMNS.ARTICLE_NAME]}</td>
                {keyColumns.slice(2).map(col => (
                  <td key={col} className="px-4 py-3 text-center">
                    {row[col] ? (
                      <span className="inline-block w-2 h-2 rounded-full bg-green-500" title="Filled" />
                    ) : (
                      <span className="inline-block w-2 h-2 rounded-full bg-red-500" title="Missing" />
                    )}
                  </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">
        <span>Showing {Math.min((page - 1) * pageSize + 1, processedData.length)} to {Math.min(page * pageSize, processedData.length)} of {processedData.length} entries</span>
        <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>
  );
}
