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

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

type TabType = 'all' | 'missingDeLong' | 'missingEnLong' | 'missingDeShort' | 'missingEnShort' | 'complete' | 'incomplete';

export function ProductDescriptions({ data, onEdit }: 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 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 === 'missingDeLong') result = result.filter(r => !r.row[COLUMNS.LONG_DE]);
    if (activeTab === 'missingEnLong') result = result.filter(r => !r.row[COLUMNS.LONG_EN]);
    if (activeTab === 'missingDeShort') result = result.filter(r => !r.row[COLUMNS.SHORT_DE]);
    if (activeTab === 'missingEnShort') 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);

    // 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, 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 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: 'missingDeLong', label: 'Missing DE Long' },
    { id: 'missingEnLong', label: 'Missing EN Long' },
    { id: 'missingDeShort', label: 'Missing DE Short' },
    { id: 'missingEnShort', label: 'Missing EN Short' },
    { 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>
        <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">
            <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' },
                  { col: COLUMNS.LINE, label: 'Line' },
                  { col: COLUMNS.LICENSE, label: 'License' },
                  { col: COLUMNS.LONG_DE, label: 'Long DE' },
                  { col: COLUMNS.SHORT_EN, label: 'Short EN' },
                ].map(({ col, label }) => (
                  <th 
                    key={col} 
                    className="px-4 py-3 font-medium cursor-pointer hover:text-white transition-colors select-none"
                    onClick={() => handleSort(col)}
                  >
                    <div className="flex items-center gap-1">
                      {label}
                      {sortCol === col && (
                        sortDesc ? <ChevronDown className="w-4 h-4" /> : <ChevronUp className="w-4 h-4" />
                      )}
                    </div>
                  </th>
                ))}
                <th className="px-4 py-3 font-medium text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/50">
              {paginatedData.map(({ row, index }) => (
                <tr key={index} className={cn("transition-colors", getRowColor(row))}>
                  <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-[300px] truncate" title={row[COLUMNS.ARTICLE_NAME]}>{row[COLUMNS.ARTICLE_NAME]}</td>
                  <td className="px-4 py-3 text-slate-300">{row[COLUMNS.LINE]}</td>
                  <td className="px-4 py-3 text-slate-300">{row[COLUMNS.LICENSE]}</td>
                  <td className="px-4 py-3"><Badge content={row[COLUMNS.SHORT_DE]} row={row} /></td>
                  <td className="px-4 py-3"><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={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>
  );
}
