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

interface MissingDataViewProps {
  data: ExcelRow[];
  headers: string[];
  onEdit: (index: number) => void;
}

function formatDateValue(val: any): string {
  if (val === null || val === undefined || val === '') return '';
  if (typeof val === 'number') {
    if (val >= 25569 && val <= 60000) {
      const excelEpoch = new Date(1899, 11, 30);
      const date = new Date(excelEpoch.getTime() + val * 86400000);
      return date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' });
    }
    return '';
  }
  return String(val);
}

function isEmptyOrEpoch(val: any): boolean {
  if (val === null || val === undefined || val === '') return true;
  if (typeof val === 'number') {
    if (val === 0 || val === 1) return true;
    if (val >= 25569 && val <= 60000) {
      // valid date range — not empty
      return false;
    }
    // number outside date range — treat as empty
    return true;
  }
  const s = String(val).trim();
  if (s === '' || s === '0' || s === '1') return true;
  if (s.endsWith('/1900')) return true;
  return false;
}

type TabType = 'missingClass' | 'missingLaunch';

export function MissingDataView({ data, headers, onEdit }: MissingDataViewProps) {
  const [activeTab, setActiveTab] = useState<TabType>('missingClass');
  const [search, setSearch] = useState('');
  const [sortCol, setSortCol] = useState<number | null>(null);
  const [sortDesc, setSortDesc] = useState(false);
  const [page, setPage] = useState(1);
  const pageSize = 100;

  const launchDateCol = useMemo(() =>
    headers.findIndex(h => h.toLowerCase().includes('launch')), [headers]);
  const readyToOrderCol = useMemo(() =>
    headers.findIndex(h => h.toLowerCase().includes('ready')), [headers]);

  const filteredData = useMemo(() => {
    let result = data.map((row, index) => ({ row, index }));

    if (activeTab === 'missingClass') {
      result = result.filter(r => {
        const val = r.row[COLUMNS.CLASSIFICATION];
        return !val || String(val).trim() === '';
      });
    }

    if (activeTab === 'missingLaunch') {
      result = result.filter(r => {
        const val = launchDateCol >= 0 ? r.row[launchDateCol] : undefined;
        return isEmptyOrEpoch(val);
      });
    }

    if (search) {
      const s = search.toLowerCase();
      result = result.filter(r =>
        String(r.row[COLUMNS.ARTICLE_NO] || '').toLowerCase().includes(s) ||
        String(r.row[COLUMNS.ARTICLE_NAME] || '').toLowerCase().includes(s)
      );
    }

    if (sortCol !== null) {
      result.sort((a, b) => {
        const valA = a.row[sortCol];
        const valB = b.row[sortCol];
        if (typeof valA === 'number' && typeof valB === 'number') {
          return sortDesc ? valB - valA : valA - valB;
        }
        const sA = String(valA || '');
        const sB = String(valB || '');
        return sortDesc ? sB.localeCompare(sA) : sA.localeCompare(sB);
      });
    }

    return result;
  }, [data, activeTab, search, sortCol, sortDesc, launchDateCol]);

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

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

  const handleSort = (col: number) => {
    if (sortCol === col) setSortDesc(d => !d);
    else { setSortCol(col); setSortDesc(false); }
  };

  const tabs: { id: TabType; label: string }[] = [
    { id: 'missingClass', label: 'Missing Classification' },
    { id: 'missingLaunch', label: 'Missing Launch Date' },
  ];

  const launchHeader = launchDateCol >= 0 ? headers[launchDateCol] : 'Launch Date';
  const readyHeader = readyToOrderCol >= 0 ? headers[readyToOrderCol] : 'Ready to Order';

  const columns = [
    { col: COLUMNS.ARTICLE_NO, label: 'SKU', width: 100 },
    { col: COLUMNS.ARTICLE_NAME, label: 'Name', width: 220 },
    { col: COLUMNS.CLASSIFICATION, label: 'Classification', width: 130 },
    ...(launchDateCol >= 0 ? [{ col: launchDateCol, label: launchHeader, width: 130 }] : []),
    ...(readyToOrderCol >= 0 ? [{ col: readyToOrderCol, label: readyHeader, width: 130 }] : []),
  ];

  return (
    <div className="flex flex-col h-full">
      <div className="flex flex-wrap gap-2 mb-6">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => { setActiveTab(tab.id); setPage(1); }}
            className={cn(
              "px-4 py-2 rounded-md text-sm font-medium transition-colors",
              activeTab === tab.id
                ? "bg-indigo-600 text-white shadow-md"
                : "bg-slate-800 text-slate-400 hover:bg-slate-700 hover:text-white"
            )}
          >
            {tab.label}
          </button>
        ))}
      </div>

      <div className="flex flex-wrap gap-4 mb-6 bg-slate-800/50 p-4 rounded-xl border border-slate-700/50">
        <div className="flex-1 min-w-[200px] relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-500" />
          <input
            type="text"
            placeholder="Search SKU or Name..."
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1); }}
            className="w-full pl-9 pr-10 py-2 bg-slate-900/50 border border-slate-700 rounded-md text-sm text-white focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500"
          />
          {search && (
            <button
              onClick={() => { setSearch(''); setPage(1); }}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white"
            >
              <X className="w-4 h-4" />
            </button>
          )}
        </div>
        <div className="flex items-center text-xs text-slate-500">
          {filteredData.length} items
        </div>
      </div>

      <div className="flex-1 bg-slate-800 rounded-xl border border-slate-700 shadow-xl overflow-hidden flex flex-col">
        <div className="overflow-x-auto flex-1">
          <table className="w-full text-left text-xs">
            <thead className="bg-slate-900/80 text-slate-400 sticky top-0 z-10">
              <tr>
                {columns.map(({ col, label, width }) => (
                  <th
                    key={col}
                    style={{ width, minWidth: width }}
                    className="px-3 py-3 font-medium border-r border-slate-700/30 select-none cursor-pointer hover:text-white"
                    onClick={() => handleSort(col)}
                  >
                    <span className="flex items-center gap-1">
                      {label}
                      {sortCol === col && (
                        sortDesc ? <ChevronDown className="w-3 h-3" /> : <ChevronUp className="w-3 h-3" />
                      )}
                    </span>
                  </th>
                ))}
                <th className="px-3 py-3 font-medium text-right" style={{ width: 60 }}></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/30">
              {paginatedData.map(({ row, index }) => (
                <tr key={index} className="hover:bg-slate-700/20 transition-colors">
                  <td className="px-3 py-2 font-mono text-indigo-400 truncate" style={{ width: 100 }}>
                    {row[COLUMNS.ARTICLE_NO]}
                  </td>
                  <td className="px-3 py-2 font-medium text-slate-200 truncate" style={{ width: 220 }} title={row[COLUMNS.ARTICLE_NAME]}>
                    {row[COLUMNS.ARTICLE_NAME]}
                  </td>
                  <td className="px-3 py-2 truncate" style={{ width: 130 }}>
                    {row[COLUMNS.CLASSIFICATION] && String(row[COLUMNS.CLASSIFICATION]).trim() !== '' ? (
                      <span className={cn(
                        "px-1.5 py-0.5 rounded-[4px] text-[10px] font-bold border",
                        String(row[COLUMNS.CLASSIFICATION]).includes('OOC')
                          ? "bg-amber-500/10 text-amber-500 border-amber-500/20"
                          : "bg-slate-700/50 text-slate-400 border-slate-600/50"
                      )}>
                        {row[COLUMNS.CLASSIFICATION]}
                      </span>
                    ) : (
                      <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-red-500/10 text-red-400 border border-red-500/20">Empty</span>
                    )}
                  </td>
                  {launchDateCol >= 0 && (
                    <td className="px-3 py-2 truncate font-mono text-slate-300" style={{ width: 130 }}>
                      {isEmptyOrEpoch(row[launchDateCol]) ? (
                        <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-red-500/10 text-red-400 border border-red-500/20">Empty</span>
                      ) : (
                        formatDateValue(row[launchDateCol]) || String(row[launchDateCol])
                      )}
                    </td>
                  )}
                  {readyToOrderCol >= 0 && (
                    <td className="px-3 py-2 truncate font-mono text-slate-300" style={{ width: 130 }}>
                      {row[readyToOrderCol] !== null && row[readyToOrderCol] !== undefined && row[readyToOrderCol] !== '' ? (
                        formatDateValue(row[readyToOrderCol]) || String(row[readyToOrderCol])
                      ) : (
                        <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-slate-700/50 text-slate-500 border border-slate-600/50">—</span>
                      )}
                    </td>
                  )}
                  <td className="px-3 py-2 text-right" style={{ width: 60 }}>
                    <button
                      onClick={() => onEdit(index)}
                      className="p-1.5 text-slate-500 hover:text-indigo-400 hover:bg-indigo-400/10 rounded transition-colors"
                    >
                      <Edit2 className="w-4 h-4" />
                    </button>
                  </td>
                </tr>
              ))}
              {paginatedData.length === 0 && (
                <tr>
                  <td colSpan={columns.length} className="px-4 py-8 text-center text-slate-500">
                    No items found.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        <div className="bg-slate-900 border-t border-slate-700 p-4 flex items-center justify-between text-xs text-slate-500">
          <div>Showing {paginatedData.length} of {filteredData.length} items</div>
          <div className="flex items-center gap-2">
            <button
              disabled={page === 1}
              onClick={() => setPage(p => p - 1)}
              className="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-50 transition-colors"
            >
              Previous
            </button>
            <span className="text-slate-300">Page {page} of {totalPages || 1}</span>
            <button
              disabled={page === totalPages || totalPages === 0}
              onClick={() => setPage(p => p + 1)}
              className="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 disabled:opacity-50 transition-colors"
            >
              Next
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
