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

interface ArticleDetailsProps {
  data: ExcelRow[];
  onEdit: (index: number) => void;
  rowStatuses: Record<string, string>;
}

type TabType = 'all' | 'missingDetailsDE' | 'missingDetailsEN' | 'missingAnyDetails' | 'lowStock';

export function ArticleDetails({ data, onEdit, rowStatuses }: ArticleDetailsProps) {
  const [activeTab, setActiveTab] = useState<TabType>('all');
  const [search, setSearch] = useState('');
  const [lineFilter, setLineFilter] = useState('');
  const [sortCol, setSortCol] = useState<number | null>(null);
  const [sortDesc, setSortDesc] = useState(false);
  const [pageSize, setPageSize] = useState(25);
  const [page, setPage] = useState(1);
  const [columnFilters, setColumnFilters] = useState<Record<number, string[]>>({});
  const [openFilterCol, setOpenFilterCol] = useState<number | null>(null);
  const [columnWidths, setColumnWidths] = useState<Record<number, number>>({
    [COLUMNS.ARTICLE_NO]: 100,
    [COLUMNS.ARTICLE_NAME]: 200,
    [COLUMNS.CLASSIFICATION]: 80,
    [COLUMNS.ITEM_AVAILABLE]: 80,
    [COLUMNS.DETAILS_DE]: 150,
    [COLUMNS.DETAILS_EN]: 150,
  });

  const lines = useMemo(() => Array.from(new Set(data.map(r => r[COLUMNS.LINE]).filter(Boolean))), [data]);

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

    // Tab filter
    if (activeTab === 'missingDetailsDE') result = result.filter(r => !r.row[COLUMNS.DETAILS_DE]);
    if (activeTab === 'missingDetailsEN') result = result.filter(r => !r.row[COLUMNS.DETAILS_EN]);
    if (activeTab === 'missingAnyDetails') result = result.filter(r => !r.row[COLUMNS.DETAILS_DE] || !r.row[COLUMNS.DETAILS_EN]);
    if (activeTab === 'lowStock') result = result.filter(r => Number(r.row[COLUMNS.ITEM_AVAILABLE] || 0) <= 0);

    // Search filter
    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)
      );
    }

    // Dropdown filters
    if (lineFilter) result = result.filter(r => r.row[COLUMNS.LINE] === lineFilter);

    // Column-specific filters (Excel-like)
    Object.entries(columnFilters).forEach(([colIdx, selectedValues]) => {
      const vals = selectedValues as string[];
      if (vals.length > 0) {
        result = result.filter(r => vals.includes(String(r.row[Number(colIdx)] || '')));
      }
    });

    // Sorting
    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, lineFilter, columnFilters, sortCol, sortDesc]);

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

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

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

  const handleResize = (colIndex: number, e: React.MouseEvent) => {
    e.preventDefault();
    const startX = e.pageX;
    const startWidth = columnWidths[colIndex] || 100;

    const onMouseMove = (moveEvent: MouseEvent) => {
      const newWidth = Math.max(60, startWidth + (moveEvent.pageX - startX));
      setColumnWidths(prev => ({ ...prev, [colIndex]: newWidth }));
    };

    const onMouseUp = () => {
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mouseup', onMouseUp);
    };

    window.addEventListener('mousemove', onMouseMove);
    window.addEventListener('mouseup', onMouseUp);
  };

  const getUniqueValues = (col: number) => {
    const values = data.map(r => String(r[col] || ''));
    return Array.from(new Set(values)).sort();
  };

  const toggleColumnFilter = (col: number, value: string) => {
    setColumnFilters(prev => {
      const current = prev[col] || [];
      const next = current.includes(value)
        ? current.filter(v => v !== value)
        : [...current, value];
      return { ...prev, [col]: next };
    });
    setPage(1);
  };

  const setBatchColumnFilter = (col: number, values: string[]) => {
    setColumnFilters(prev => ({ ...prev, [col]: values }));
    setPage(1);
  };

  const getBadge = (val: any, type: 'success' | 'warning' | 'error' | 'info' = 'info') => {
    if (!val) return <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>;
    
    const styles = {
      success: "bg-green-500/10 text-green-400 border-green-500/20",
      warning: "bg-yellow-500/10 text-yellow-400 border-yellow-500/20",
      error: "bg-red-500/10 text-red-400 border-red-500/20",
      info: "bg-blue-500/10 text-blue-400 border-blue-500/20"
    };

    return <span className={cn("inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium border", styles[type])}>{val}</span>;
  };

  const tabs: { id: TabType; label: string }[] = [
    { id: 'all', label: 'All Articles' },
    { id: 'missingDetailsDE', label: 'No Details DE' },
    { id: 'missingDetailsEN', label: 'No Details EN' },
    { id: 'missingAnyDetails', label: 'Missing Details' },
    { id: 'lowStock', label: 'Out of Stock' },
  ];

  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-4 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"
          />
        </div>
        {(Object.values(columnFilters) as string[][]).some(v => v.length > 0) && (
          <button
            onClick={() => {
              setColumnFilters({});
              setPage(1);
            }}
            className="flex items-center gap-2 px-4 py-2 bg-red-600/10 text-red-400 hover:bg-red-600 hover:text-white rounded-md text-sm font-medium transition-colors border border-red-600/20"
          >
            <XIcon className="w-4 h-4" />
            Clear All Column Filters
          </button>
        )}
        <select
          value={lineFilter}
          onChange={e => { setLineFilter(e.target.value); setPage(1); }}
          className="bg-slate-900 border border-slate-700 rounded-md px-4 py-2 text-sm text-white focus:outline-none focus:border-indigo-500"
        >
          <option value="">All Lines</option>
          {lines.map(l => <option key={l} value={String(l)}>{String(l)}</option>)}
        </select>
      </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" style={{ tableLayout: 'fixed' }}>
            <thead className="bg-slate-900/80 text-slate-400 sticky top-0 z-10">
              <tr>
                {[
                  { col: COLUMNS.ARTICLE_NO, label: 'SKU' },
                  { col: COLUMNS.ARTICLE_NAME, label: 'Name' },
                  { col: COLUMNS.CLASSIFICATION, label: 'Class' },
                  { col: COLUMNS.ITEM_AVAILABLE, label: 'Stock' },
                  { col: COLUMNS.DETAILS_DE, label: 'Details DE' },
                  { col: COLUMNS.DETAILS_EN, label: 'Details EN' },
                ].map(({ col, label }) => (
                  <th 
                    key={col} 
                    className="px-3 py-3 font-medium transition-colors select-none group relative border-r border-slate-700/30"
                    style={{ width: columnWidths[col] || 'auto', minWidth: columnWidths[col] || 'auto' }}
                  >
                    <div className="flex items-center justify-between gap-1 overflow-hidden">
                      <div className="flex items-center gap-1 cursor-pointer hover:text-white truncate" onClick={() => handleSort(col)}>
                        {label}
                        {sortCol === col && (
                          sortDesc ? <ChevronDown className="w-3 h-3 shrink-0" /> : <ChevronUp className="w-3 h-3 shrink-0" />
                        )}
                      </div>
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setOpenFilterCol(openFilterCol === col ? null : col);
                        }}
                        className={cn(
                          "p-1 rounded hover:bg-slate-700 transition-colors shrink-0",
                          (columnFilters[col]?.length || 0) > 0 ? "text-indigo-400 bg-indigo-400/10" : "text-slate-500 opacity-0 group-hover:opacity-100"
                        )}
                      >
                        <Filter className="w-3.5 h-3.5" />
                      </button>
                    </div>

                    {/* Resizer handle */}
                    <div
                      onMouseDown={(e) => handleResize(col, e)}
                      className="absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-indigo-500/50 group-hover:bg-slate-700/50 transition-colors z-20"
                    />

                    {openFilterCol === col && (
                      <ColumnFilterPopover
                        uniqueValues={getUniqueValues(col)}
                        selectedValues={columnFilters[col] || []}
                        onToggle={(val) => toggleColumnFilter(col, val)}
                        onSelectAll={(vals) => setBatchColumnFilter(col, vals)}
                        onClear={() => {
                          setColumnFilters(prev => {
                            const next = { ...prev };
                            delete next[col];
                            return next;
                          });
                          setOpenFilterCol(null);
                        }}
                        onClose={() => setOpenFilterCol(null)}
                      />
                    )}
                  </th>
                ))}
                <th className="px-3 py-3 font-medium text-right" style={{ width: 80 }}>Edit</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/30">
              {paginatedData.map(({ row, index }) => {
                const saveStatus = rowStatuses[String(row[COLUMNS.ARTICLE_NO])];
                return (
                  <tr
                    key={index}
                    className={cn(
                      "hover:bg-slate-700/20 transition-colors",
                      saveStatus === 'error'   ? "bg-red-400/20 border-l-4 border-l-red-500" :
                      saveStatus === 'pending' ? "bg-yellow-400/20 border-l-4 border-l-yellow-400" : ""
                    )}
                  >
                  <td className="px-3 py-2 font-mono text-indigo-400 truncate" style={{ width: columnWidths[COLUMNS.ARTICLE_NO] }}>{row[COLUMNS.ARTICLE_NO]}</td>
                  <td className="px-3 py-2 font-medium text-slate-200 truncate" style={{ width: columnWidths[COLUMNS.ARTICLE_NAME] }} title={row[COLUMNS.ARTICLE_NAME]}>
                    {row[COLUMNS.ARTICLE_NAME]}
                  </td>
                  <td className="px-3 py-2 truncate" style={{ width: columnWidths[COLUMNS.CLASSIFICATION] }}>
                    <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>
                  </td>
                  <td className="px-3 py-2 truncate" style={{ width: columnWidths[COLUMNS.ITEM_AVAILABLE] }}>
                    <span className={cn(
                        "font-mono font-bold",
                        Number(row[COLUMNS.ITEM_AVAILABLE] || 0) <= 0 ? "text-red-400" : "text-emerald-400"
                    )}>
                        {row[COLUMNS.ITEM_AVAILABLE] || 0}
                    </span>
                  </td>
                  <td className="px-3 py-2 truncate" style={{ width: columnWidths[COLUMNS.DETAILS_DE] }}>
                    {row[COLUMNS.DETAILS_DE] ? (
                        <div className="truncate text-slate-400" title={row[COLUMNS.DETAILS_DE]}>{row[COLUMNS.DETAILS_DE]}</div>
                    ) : getBadge(null)}
                  </td>
                  <td className="px-3 py-2 truncate" style={{ width: columnWidths[COLUMNS.DETAILS_EN] }}>
                    {row[COLUMNS.DETAILS_EN] ? (
                        <div className="truncate text-slate-400" title={row[COLUMNS.DETAILS_EN]}>{row[COLUMNS.DETAILS_EN]}</div>
                    ) : getBadge(null)}
                  </td>
                  <td className="px-3 py-2 text-right">
                    <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={7} className="px-4 py-8 text-center text-slate-500">
                    No articles 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} articles</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>
  );
}
