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

interface ProductDescriptionsProps {
  data: ExcelRow[];
  headers: string[];
  asinColumnIndex: number | null;
  onEdit: (index: number) => void;
  rowStatuses: Record<string, string>;
}

type TabType = 'all' | 'missingLongDE' | 'missingLongEN' | 'missingShortDE' | 'missingShortEN' | 'complete' | 'incomplete';

// Description columns that should only have Present/Missing filters
const DESCRIPTION_COLUMNS = [COLUMNS.LONG_DE, COLUMNS.LONG_EN, COLUMNS.SHORT_DE, COLUMNS.SHORT_EN];

export function ProductDescriptions({ data, headers, asinColumnIndex, onEdit, rowStatuses }: ProductDescriptionsProps) {
  const [activeTab, setActiveTab] = useState<TabType>('all');
  const [search, setSearch] = useState('');
  const [lineFilter, setLineFilter] = useState('');
  const [licenseFilter, setLicenseFilter] = 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]: 250,
    [COLUMNS.ASIN]: asinColumnIndex !== null ? 150 : 0,
    [COLUMNS.LINE]: 80,
    [COLUMNS.LICENSE]: 120,
    [COLUMNS.CLASSIFICATION]: 100,
    [COLUMNS.LONG_DE]: 80,
    [COLUMNS.LONG_EN]: 80,
    [COLUMNS.SHORT_DE]: 80,
    [COLUMNS.SHORT_EN]: 80,
  });

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

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

    // Tab filter
    if (activeTab === 'missingLongDE') result = result.filter(r => !r.row[COLUMNS.LONG_DE]);
    if (activeTab === 'missingLongEN') result = result.filter(r => !r.row[COLUMNS.LONG_EN]);
    if (activeTab === 'missingShortDE') result = result.filter(r => !r.row[COLUMNS.SHORT_DE]);
    if (activeTab === 'missingShortEN') result = result.filter(r => !r.row[COLUMNS.SHORT_EN]);

    if (activeTab === 'complete') result = result.filter(r =>
      r.row[COLUMNS.LONG_DE] && r.row[COLUMNS.LONG_EN] &&
      r.row[COLUMNS.SHORT_DE] && r.row[COLUMNS.SHORT_EN]
    );
    if (activeTab === 'incomplete') result = result.filter(r =>
      !r.row[COLUMNS.LONG_DE] || !r.row[COLUMNS.LONG_EN] ||
      !r.row[COLUMNS.SHORT_DE] || !r.row[COLUMNS.SHORT_EN]
    );

    // 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);
    if (licenseFilter) result = result.filter(r => r.row[COLUMNS.LICENSE] === licenseFilter);

    // Column-specific filters (Excel-like)
    console.log('[Filter] applying columnFilters:', columnFilters, 'result count before:', result.length);
    Object.entries(columnFilters).forEach(([colIdx, selectedValues]) => {
      const col = Number(colIdx);
      const vals = selectedValues as string[];
      if (vals.length > 0) {
        // For description columns, filter by present/missing
        if (DESCRIPTION_COLUMNS.includes(col)) {
          result = result.filter(r => {
            const hasValue = Boolean(r.row[col]);
            const shouldInclude = (vals.includes('Present') && hasValue) || (vals.includes('Missing') && !hasValue);
            return shouldInclude;
          });
        } else {
          // For other columns, use regular value matching
          const before = result.length;
          result = result.filter(r => {
            const cellVal = String(r.row[col] ?? '').trim();
            return vals.some(v => v.trim() === cellVal);
          });
          console.log('[Filter] col', col, 'vals', vals, 'before:', before, 'after:', result.length);
        }
      }
    });

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

    return result;
  }, [data, activeTab, search, lineFilter, licenseFilter, 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) => {
    // For description columns, return only 'Present' and 'Missing'
    if (DESCRIPTION_COLUMNS.includes(col)) {
      return ['Present', 'Missing'];
    }
    // For other columns, return actual unique values
    const values = data.map(r => String(r[col] || ''));
    return Array.from(new Set(values)).sort();
  };

  const toggleColumnFilter = (col: number, value: string) => {
    console.log('[Filter] toggleColumnFilter called, col:', col, 'value:', JSON.stringify(value));
    setColumnFilters(prev => {
      const current = prev[col] || [];
      const next = current.includes(value)
        ? current.filter(v => v !== value)
        : [...current, value];
      const updated = { ...prev, [col]: next };
      console.log('[Filter] new columnFilters:', updated);
      return updated;
    });
    setPage(1);
  };

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

  const getRowColor = (row: ExcelRow) => {
    // EOL Rule: OOC Classification and 0 or negative stock (Item Available)
    const classification = String(row[COLUMNS.CLASSIFICATION] || '').toUpperCase().trim();
    const stock = Number(row[COLUMNS.ITEM_AVAILABLE] || 0);

    if (classification === 'OOC' && stock <= 0) {
      return 'bg-yellow-500/10 hover:bg-yellow-500/20'; // EOL Highlight
    }

    const fields = [
      row[COLUMNS.LONG_DE], row[COLUMNS.LONG_EN],
      row[COLUMNS.SHORT_DE], row[COLUMNS.SHORT_EN]
    ];
    const filled = fields.filter(Boolean).length;
    if (filled === 4) return 'bg-green-900/10 hover:bg-green-900/20';
    if (filled === 0) return 'bg-red-900/10 hover:bg-red-900/20';
    return 'bg-yellow-900/10 hover:bg-yellow-900/20';
  };

  const Badge = ({ content, row }: { content: any, row: ExcelRow }) => {
    if (content) return <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-500/20 text-green-400 border border-green-500/30">✓</span>;

    // EOL Exception: OOC and stock <= 0
    const classification = String(row[COLUMNS.CLASSIFICATION] || '').toUpperCase().trim();
    const stock = Number(row[COLUMNS.ITEM_AVAILABLE] || 0);

    if (classification === 'OOC' && stock <= 0) {
      return <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-500/20 text-yellow-400 border border-yellow-500/30">EOL not neccessary</span>;
    }

    return <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-500/20 text-red-400 border border-red-500/30">✗ Missing</span>;
  };

  const tabs: { id: TabType; label: string }[] = [
    { id: 'all', label: 'All Products' },
    { id: 'missingLongDE', label: 'Missing Long DE' },
    { id: 'missingLongEN', label: 'Missing Long EN' },
    { id: 'missingShortDE', label: 'Missing Short DE' },
    { id: 'missingShortEN', label: 'Missing Short EN' },
    { id: 'complete', label: 'Complete' },
    { id: 'incomplete', label: 'Incomplete' },
  ];

  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-blue-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 p-4 rounded-xl border border-slate-700 shadow-sm">
        <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-400" />
          <input
            type="text"
            placeholder="Search Article Name or No..."
            value={search}
            onChange={e => { setSearch(e.target.value); setPage(1); }}
            className="w-full pl-9 pr-4 py-2 bg-slate-900 border border-slate-700 rounded-md text-sm text-white focus:outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-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"
          >
            <X 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-blue-500"
        >
          <option value="">All Lines</option>
          {lines.map(l => <option key={l} value={String(l)}>{String(l)}</option>)}
        </select>
        <select
          value={licenseFilter}
          onChange={e => { setLicenseFilter(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-blue-500"
        >
          <option value="">All Licenses</option>
          {licenses.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-sm" style={{ tableLayout: 'fixed' }}>
            <thead className="bg-slate-900/50 text-slate-400 sticky top-0 z-10">
              <tr>
                {[
                  { col: COLUMNS.ARTICLE_NO, label: 'Article No.' },
                  { col: COLUMNS.ARTICLE_NAME, label: 'Article Name' },
                  ...(asinColumnIndex !== null ? [{ col: asinColumnIndex, label: 'ASIN' }] : []),
                  { col: COLUMNS.LINE, label: 'Line' },
                  { col: COLUMNS.LICENSE, label: 'License' },
                  { col: COLUMNS.CLASSIFICATION, label: 'Classification' },
                  { col: COLUMNS.LONG_DE, label: 'Long DE' },
                  { col: COLUMNS.LONG_EN, label: 'Long EN' },
                  { col: COLUMNS.SHORT_DE, label: 'Short DE' },
                  { col: COLUMNS.SHORT_EN, label: 'Short EN' },
                ].map(({ col, label }) => (
                  <th
                    key={col}
                    className="px-4 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-4 h-4 shrink-0" /> : <ChevronUp className="w-4 h-4 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-blue-400 bg-blue-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-blue-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-4 py-3 font-medium text-right" style={{ width: 100 }}>Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/50">
              {paginatedData.map(({ row, index }) => {
                const saveStatus = rowStatuses[String(row[COLUMNS.ARTICLE_NO])];
                return (
                  <tr 
                    key={index} 
                    className={cn(
                      "transition-colors", 
                      getRowColor(row),
                      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-4 py-3 font-mono text-slate-300 text-xs truncate" style={{ width: columnWidths[COLUMNS.ARTICLE_NO] }}>{row[COLUMNS.ARTICLE_NO]}</td>
                  <td className="px-4 py-3 font-medium text-white truncate" style={{ width: columnWidths[COLUMNS.ARTICLE_NAME] }} title={row[COLUMNS.ARTICLE_NAME]}>{row[COLUMNS.ARTICLE_NAME]}</td>
                  {asinColumnIndex !== null && (
                    <td className="px-4 py-3 font-mono text-slate-300 text-xs truncate" style={{ width: columnWidths[asinColumnIndex] || 150 }} title={row[asinColumnIndex]}>{row[asinColumnIndex] || '—'}</td>
                  )}
                  <td className="px-4 py-3 text-slate-300 text-xs truncate" style={{ width: columnWidths[COLUMNS.LINE] }}>{row[COLUMNS.LINE]}</td>
                  <td className="px-4 py-3 text-slate-300 text-xs truncate" style={{ width: columnWidths[COLUMNS.LICENSE] }} title={row[COLUMNS.LICENSE]}>{row[COLUMNS.LICENSE] || '—'}</td>
                  <td className="px-4 py-3 truncate" style={{ width: columnWidths[COLUMNS.CLASSIFICATION] }}>
                    <span className={cn(
                      "px-2 py-0.5 rounded 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-4 py-3" style={{ width: columnWidths[COLUMNS.LONG_DE] }}><Badge content={row[COLUMNS.LONG_DE]} row={row} /></td>
                  <td className="px-4 py-3" style={{ width: columnWidths[COLUMNS.LONG_EN] }}><Badge content={row[COLUMNS.LONG_EN]} row={row} /></td>
                  <td className="px-4 py-3" style={{ width: columnWidths[COLUMNS.SHORT_DE] }}><Badge content={row[COLUMNS.SHORT_DE]} row={row} /></td>
                  <td className="px-4 py-3" style={{ width: columnWidths[COLUMNS.SHORT_EN] }}><Badge content={row[COLUMNS.SHORT_EN]} row={row} /></td>
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => onEdit(index)}
                      className="inline-flex items-center gap-2 px-3 py-1.5 bg-blue-600/10 text-blue-400 hover:bg-blue-600 hover:text-white rounded-md transition-colors font-medium"
                    >
                      <Edit2 className="w-4 h-4" />
                      Edit
                    </button>
                  </td>
                </tr>
                );
              })}
              {paginatedData.length === 0 && (
                <tr>
                  <td colSpan={asinColumnIndex !== null ? 10 : 9} className="px-4 py-8 text-center text-slate-500">
                    No products found matching the criteria.
                  </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, filteredData.length)} to {Math.min(page * pageSize, filteredData.length)} of {filteredData.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>
    </div>
  );
}
