import React, { useState, useMemo } from 'react';
import { Filament } from '../types/filament';
import { ColorCell } from './ColorCell';
import { getFilamentColor, getColorStyle, getContrastColor } from '../data/bambuLabColors';
import '../styles/select.css';

interface FilamentTableProps {
  filaments: Filament[];
  loading?: boolean;
  error?: string;
}

export const FilamentTable: React.FC<FilamentTableProps> = ({ filaments, loading, error }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [sortField, setSortField] = useState<keyof Filament>('boja');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
  
  // Filter states
  const [filterBrand, setFilterBrand] = useState('');
  const [filterTip, setFilterTip] = useState('');
  const [filterFinish, setFilterFinish] = useState('');
  const [filterStatus, setFilterStatus] = useState('');

  // Get unique values for filters
  const uniqueBrands = useMemo(() => [...new Set(filaments.map(f => f.brand))].sort(), [filaments]);
  const uniqueTips = useMemo(() => [...new Set(filaments.map(f => f.tip))].sort(), [filaments]);
  const uniqueFinishes = useMemo(() => [...new Set(filaments.map(f => f.finish))].sort(), [filaments]);

  const filteredAndSortedFilaments = useMemo(() => {
    let filtered = filaments.filter(filament => {
      // Search filter
      const matchesSearch = Object.values(filament).some(value =>
        value.toLowerCase().includes(searchTerm.toLowerCase())
      );
      
      // Brand filter
      const matchesBrand = !filterBrand || filament.brand === filterBrand;
      
      // Type filter
      const matchesTip = !filterTip || filament.tip === filterTip;
      
      // Finish filter
      const matchesFinish = !filterFinish || filament.finish === filterFinish;
      
      // Status filter
      let matchesStatus = true;
      if (filterStatus) {
        if (filterStatus === 'new') {
          matchesStatus = filament.vakum.toLowerCase().includes('vakuum') && !filament.otvoreno;
        } else if (filterStatus === 'opened') {
          matchesStatus = filament.otvoreno.toLowerCase().includes('otvorena');
        } else if (filterStatus === 'refill') {
          matchesStatus = filament.refill.toLowerCase() === 'da';
        }
      }
      
      return matchesSearch && matchesBrand && matchesTip && matchesFinish && matchesStatus;
    });

    filtered.sort((a, b) => {
      const aValue = a[sortField];
      const bValue = b[sortField];
      
      if (sortOrder === 'asc') {
        return aValue.localeCompare(bValue);
      } else {
        return bValue.localeCompare(aValue);
      }
    });

    return filtered;
  }, [filaments, searchTerm, sortField, sortOrder, filterBrand, filterTip, filterFinish, filterStatus]);

  const handleSort = (field: keyof Filament) => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('asc');
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-gray-900 dark:border-gray-100"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-100 dark:bg-red-900 border border-red-400 dark:border-red-600 text-red-700 dark:text-red-200 px-4 py-3 rounded">
        Greška: {error}
      </div>
    );
  }

  return (
    <div className="w-full">
      <div className="space-y-4 mb-4">
        {/* Search Bar */}
        <div>
          <input
            type="text"
            placeholder="Pretraži filamente..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        {/* Filter Row */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          {/* Brand Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Brend
            </label>
            <select
              value={filterBrand}
              onChange={(e) => setFilterBrand(e.target.value)}
              className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Svi brendovi</option>
              {uniqueBrands.map(brand => (
                <option key={brand} value={brand}>{brand}</option>
              ))}
            </select>
          </div>

          {/* Type Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Tip
            </label>
            <select
              value={filterTip}
              onChange={(e) => setFilterTip(e.target.value)}
              className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Svi tipovi</option>
              {uniqueTips.map(tip => (
                <option key={tip} value={tip}>{tip}</option>
              ))}
            </select>
          </div>

          {/* Finish Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Završna obrada
            </label>
            <select
              value={filterFinish}
              onChange={(e) => setFilterFinish(e.target.value)}
              className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Sve obrade</option>
              {uniqueFinishes.map(finish => (
                <option key={finish} value={finish}>{finish}</option>
              ))}
            </select>
          </div>

          {/* Status Filter */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Status
            </label>
            <select
              value={filterStatus}
              onChange={(e) => setFilterStatus(e.target.value)}
              className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="">Svi statusi</option>
              <option value="new">Novi (vakuum)</option>
              <option value="opened">Otvoreni</option>
              <option value="refill">Refill</option>
            </select>
          </div>
        </div>

        {/* Clear Filters Button */}
        {(filterBrand || filterTip || filterFinish || filterStatus) && (
          <button
            onClick={() => {
              setFilterBrand('');
              setFilterTip('');
              setFilterFinish('');
              setFilterStatus('');
            }}
            className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300"
          >
            Obriši filtere
          </button>
        )}
      </div>
      
      <div className="overflow-x-auto">
        <table className="min-w-full bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-700">
          <thead>
            <tr className="bg-gray-100 dark:bg-gray-700">
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('brand')}
              >
                Brend {sortField === 'brand' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('tip')}
              >
                Tip {sortField === 'tip' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('finish')}
              >
                Završna obrada {sortField === 'finish' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('boja')}
              >
                Boja {sortField === 'boja' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('refill')}
              >
                Refill {sortField === 'refill' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('vakum')}
              >
                Vakum {sortField === 'vakum' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('otvoreno')}
              >
                Otvoreno {sortField === 'otvoreno' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b border-r dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('kolicina')}
              >
                Količina {sortField === 'kolicina' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
              <th 
                className="px-4 py-2 border-b dark:border-gray-600 cursor-pointer hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100"
                onClick={() => handleSort('cena')}
              >
                Cena {sortField === 'cena' && (sortOrder === 'asc' ? '↑' : '↓')}
              </th>
            </tr>
          </thead>
          <tbody>
            {filteredAndSortedFilaments.map((filament, index) => {
              const colorMapping = getFilamentColor(filament.boja);
              const cellStyle = getColorStyle(colorMapping);
              const textColor = Array.isArray(colorMapping.hex) 
                ? '#000000' 
                : getContrastColor(colorMapping.hex);
              
              return (
                <tr 
                  key={index} 
                  className="hover:bg-gray-50 dark:hover:bg-gray-750 transition-colors bg-white dark:bg-gray-800"
                >
                  <td className="px-4 py-2 border-b border-r dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.brand}</td>
                  <td className="px-4 py-2 border-b border-r dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.tip}</td>
                  <td className="px-4 py-2 border-b border-r dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.finish}</td>
                  <td 
                    className="px-4 py-2 border-b border-r dark:border-gray-700"
                    style={{
                      ...cellStyle,
                      color: textColor
                    }}
                  >
                    <ColorCell colorName={filament.boja} />
                  </td>
                  <td className="px-4 py-2 border-b border-r dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.refill}</td>
                  <td className="px-4 py-2 border-b border-r dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.vakum}</td>
                  <td className="px-4 py-2 border-b border-r dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.otvoreno}</td>
                  <td className="px-4 py-2 border-b border-r dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.kolicina}</td>
                  <td className="px-4 py-2 border-b dark:border-gray-700 text-gray-900 dark:text-gray-100">{filament.cena}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      
      <div className="mt-4 text-sm text-gray-600 dark:text-gray-400">
        Prikazano {filteredAndSortedFilaments.length} od {filaments.length} filamenata
      </div>
    </div>
  );
};