'use client'

import { useState, useEffect, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { filamentService, colorService } from '@/src/services/api';
import { Filament } from '@/src/types/filament';
import { trackEvent } from '@/src/components/MatomoAnalytics';
import { SaleManager } from '@/src/components/SaleManager';
// Removed unused imports for Bambu Lab color categorization
import '@/src/styles/select.css';

// Colors that only come as refills (no spools)
const REFILL_ONLY_COLORS = [
  'Beige',
  'Light Gray',
  'Yellow',
  'Orange',
  'Gold',
  'Bright Green',
  'Pink',
  'Magenta',
  'Maroon Red',
  'Purple',
  'Turquoise',
  'Cobalt Blue',
  'Brown',
  'Bronze',
  'Silver',
  'Blue Grey',
  'Dark Gray'
];

// Helper function to check if a filament should be refill-only
const isRefillOnly = (color: string, finish?: string): boolean => {
  // Translucent finish always has spool option
  if (finish === 'Translucent') {
    return false;
  }
  return REFILL_ONLY_COLORS.includes(color);
};

// Helper function to check if a filament is spool-only
const isSpoolOnly = (finish?: string, type?: string): boolean => {
  return finish === 'Translucent' || finish === 'Metal' || finish === 'Silk+' || (type === 'PPA' && finish === 'CF') || type === 'PA6' || type === 'PC';
};

// Helper function to filter colors based on material and finish
const getFilteredColors = (colors: Array<{id: string, name: string, hex: string, cena_refill?: number, cena_spulna?: number}>, type?: string, finish?: string) => {
  // PPA CF only has black color
  if (type === 'PPA' && finish === 'CF') {
    return colors.filter(color => color.name.toLowerCase() === 'black');
  }
  return colors;
};

interface FilamentWithId extends Filament {
  id: string;
  createdAt?: string;
  updatedAt?: string;
  boja_hex?: string;
}

// Finish options by filament type
const FINISH_OPTIONS_BY_TYPE: Record<string, string[]> = {
  'ABS': ['GF', 'Bez Finisha'],
  'PLA': ['85A', '90A', '95A HF', 'Aero', 'Basic', 'Basic Gradient', 'CF', 'FR', 'Galaxy', 'GF', 'Glow', 'HF', 'Marble', 'Matte', 'Metal', 'Silk Multi-Color', 'Silk+', 'Sparkle', 'Translucent', 'Wood'],
  'TPU': ['85A', '90A', '95A HF'],
  'PETG': ['Basic', 'CF', 'FR', 'HF', 'Translucent'],
  'PC': ['CF', 'FR', 'Bez Finisha'],
  'ASA': ['Bez Finisha'],
  'PA': ['CF', 'GF', 'Bez Finisha'],
  'PA6': ['CF', 'GF'],
  'PPA': ['CF'],
  'PVA': ['Bez Finisha'],
  'HIPS': ['Bez Finisha']
};

export default function AdminDashboard() {
  const router = useRouter();
  const [filaments, setFilaments] = useState<FilamentWithId[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editingFilament, setEditingFilament] = useState<FilamentWithId | null>(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [darkMode, setDarkMode] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [sortField, setSortField] = useState<string>('boja');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
  const [selectedFilaments, setSelectedFilaments] = useState<Set<string>>(new Set());
  const [searchTerm, setSearchTerm] = useState('');
  const [availableColors, setAvailableColors] = useState<Array<{id: string, name: string, hex: string, cena_refill?: number, cena_spulna?: number}>>([]);

  // Initialize dark mode - default to true for admin
  useEffect(() => {
    setMounted(true);
    const saved = localStorage.getItem('darkMode');
    if (saved !== null) {
      setDarkMode(JSON.parse(saved));
    } else {
      // Default to dark mode for admin
      setDarkMode(true);
    }
  }, []);

  useEffect(() => {
    if (!mounted) return;
    
    localStorage.setItem('darkMode', JSON.stringify(darkMode));
    if (darkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [darkMode, mounted]);

  // Check authentication
  useEffect(() => {
    const token = localStorage.getItem('authToken');
    const expiry = localStorage.getItem('tokenExpiry');
    
    if (!token || !expiry || Date.now() > parseInt(expiry)) {
      router.push('/upadaj');
    }
  }, [router]);

  // Fetch filaments
  const fetchFilaments = async () => {
    try {
      setLoading(true);
      const filaments = await filamentService.getAll();
      setFilaments(filaments);
    } catch (err) {
      setError('Greška pri učitavanju filamenata');
      console.error('Fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  const fetchAllData = async () => {
    // Fetch both filaments and colors
    await fetchFilaments();
    try {
      const colors = await colorService.getAll();
      setAvailableColors(colors.sort((a: any, b: any) => a.name.localeCompare(b.name)));
    } catch (error) {
      console.error('Error loading colors:', error);
    }
  };

  useEffect(() => {
    fetchAllData();
    
    // Refresh when window regains focus
    const handleFocus = () => {
      fetchAllData();
    };
    window.addEventListener('focus', handleFocus);
    
    return () => {
      window.removeEventListener('focus', handleFocus);
    };
  }, []);

  // Sorting logic
  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('asc');
    }
  };

  // Filter and sort filaments
  const filteredAndSortedFilaments = useMemo(() => {
    // First, filter by search term
    let filtered = filaments;
    if (searchTerm) {
      const search = searchTerm.toLowerCase();
      filtered = filaments.filter(f => 
        f.tip?.toLowerCase().includes(search) ||
        f.finish?.toLowerCase().includes(search) ||
        f.boja?.toLowerCase().includes(search) ||
        f.cena?.toLowerCase().includes(search)
      );
    }
    
    // Then sort if needed
    if (!sortField) return filtered;
    
    return [...filtered].sort((a, b) => {
      let aVal = a[sortField as keyof FilamentWithId];
      let bVal = b[sortField as keyof FilamentWithId];
      
      // Handle null/undefined values
      if (aVal === null || aVal === undefined) aVal = '';
      if (bVal === null || bVal === undefined) bVal = '';
      
      // Handle date fields
      if (sortField === 'created_at' || sortField === 'updated_at') {
        const aDate = new Date(String(aVal));
        const bDate = new Date(String(bVal));
        return sortOrder === 'asc' ? aDate.getTime() - bDate.getTime() : bDate.getTime() - aDate.getTime();
      }
      
      // Handle numeric fields
      if (sortField === 'kolicina' || sortField === 'refill' || sortField === 'spulna') {
        const aNum = Number(aVal) || 0;
        const bNum = Number(bVal) || 0;
        return sortOrder === 'asc' ? aNum - bNum : bNum - aNum;
      }
      
      // String comparison for other fields
      aVal = String(aVal).toLowerCase();
      bVal = String(bVal).toLowerCase();
      
      if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1;
      if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1;
      return 0;
    });
  }, [filaments, sortField, sortOrder, searchTerm]);

  const handleSave = async (filament: Partial<FilamentWithId>) => {
    try {
      // Extract only the fields the API expects
      const { id, ...dataForApi } = filament;
      
      // Ensure numeric fields are numbers
      const cleanData = {
        tip: dataForApi.tip || 'PLA',
        finish: dataForApi.finish || 'Basic',
        boja: dataForApi.boja || '',
        boja_hex: dataForApi.boja_hex || '#000000',
        refill: Number(dataForApi.refill) || 0,
        spulna: Number(dataForApi.spulna) || 0,
        cena: dataForApi.cena || '3499'
      };
      
      // Validate required fields
      if (!cleanData.tip || !cleanData.finish || !cleanData.boja) {
        setError('Tip, Finish, and Boja are required fields');
        return;
      }
      
      if (id) {
        await filamentService.update(id, cleanData);
        trackEvent('Admin', 'Update Filament', `${cleanData.tip} ${cleanData.finish} ${cleanData.boja}`);
      } else {
        await filamentService.create(cleanData);
        trackEvent('Admin', 'Create Filament', `${cleanData.tip} ${cleanData.finish} ${cleanData.boja}`);
      }
      
      setEditingFilament(null);
      setShowAddForm(false);
      fetchAllData();
    } catch (err: any) {
      if (err.response?.status === 401 || err.response?.status === 403) {
        setError('Sesija je istekla. Molimo prijavite se ponovo.');
        setTimeout(() => {
          router.push('/upadaj');
        }, 2000);
      } else {
        // Extract error message properly
        let errorMessage = 'Greška pri čuvanju filamenata';
        if (err.response?.data?.error) {
          errorMessage = err.response.data.error;
        } else if (err.response?.data?.message) {
          errorMessage = err.response.data.message;
        } else if (typeof err.response?.data === 'string') {
          errorMessage = err.response.data;
        } else if (err.message) {
          errorMessage = err.message;
        }
        
        setError(errorMessage);
        console.error('Save error:', err.response?.data || err.message);
      }
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Da li ste sigurni da želite obrisati ovaj filament?')) {
      return;
    }

    try {
      await filamentService.delete(id);
      fetchAllData();
    } catch (err) {
      setError('Greška pri brisanju filamenata');
      console.error('Delete error:', err);
    }
  };

  const handleBulkDelete = async () => {
    if (selectedFilaments.size === 0) {
      setError('Molimo izaberite filamente za brisanje');
      return;
    }

    if (!confirm(`Da li ste sigurni da želite obrisati ${selectedFilaments.size} filamenata?`)) {
      return;
    }

    try {
      // Delete all selected filaments
      await Promise.all(Array.from(selectedFilaments).map(id => filamentService.delete(id)));
      setSelectedFilaments(new Set());
      fetchAllData();
    } catch (err) {
      setError('Greška pri brisanju filamenata');
      console.error('Bulk delete error:', err);
    }
  };

  const toggleFilamentSelection = (filamentId: string) => {
    const newSelection = new Set(selectedFilaments);
    if (newSelection.has(filamentId)) {
      newSelection.delete(filamentId);
    } else {
      newSelection.add(filamentId);
    }
    setSelectedFilaments(newSelection);
  };

  const toggleSelectAll = () => {
    if (selectedFilaments.size === filteredAndSortedFilaments.length) {
      setSelectedFilaments(new Set());
    } else {
      setSelectedFilaments(new Set(filteredAndSortedFilaments.map(f => f.id)));
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('authToken');
    localStorage.removeItem('tokenExpiry');
    router.push('/upadaj');
  };

  if (loading) {
    return <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center">
      <div className="text-gray-600 dark:text-gray-400">Učitavanje...</div>
    </div>;
  }

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors">
      {/* Main Content - Full Screen */}
      <div className="w-full">
          <header className="bg-white dark:bg-gray-800 shadow transition-colors">
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 lg:py-6">
              <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <img 
                  src="/logo.png" 
                  alt="Filamenteka Admin" 
                  loading="lazy"
                  decoding="async"
                  className="h-20 sm:h-32 w-auto drop-shadow-lg"
                />
                <div className="flex flex-wrap gap-2 sm:gap-4 w-full sm:w-auto">
                  {!showAddForm && !editingFilament && (
                    <button
                      onClick={() => {
                        setShowAddForm(true);
                        window.scrollTo({ top: 0, behavior: 'smooth' });
                      }}
                      className="flex-1 sm:flex-initial px-3 sm:px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 text-sm sm:text-base"
                    >
                      Dodaj novi
                    </button>
                  )}
                  {selectedFilaments.size > 0 && (
                    <button
                      onClick={handleBulkDelete}
                      className="flex-1 sm:flex-initial px-3 sm:px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 text-sm sm:text-base"
                    >
                      Obriši izabrane ({selectedFilaments.size})
                    </button>
                  )}
                  <SaleManager 
                    filaments={filaments}
                    selectedFilaments={selectedFilaments}
                    onSaleUpdate={fetchFilaments}
                  />
                  <button
                    onClick={() => router.push('/')}
                    className="flex-1 sm:flex-initial px-3 sm:px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 text-sm sm:text-base"
                  >
                    Nazad na sajt
                  </button>
                  {mounted && (
                    <button
                      onClick={() => setDarkMode(!darkMode)}
                      className="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 rounded hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
                      title={darkMode ? 'Svetla tema' : 'Tamna tema'}
                    >
                      {darkMode ? '☀️' : '🌙'}
                    </button>
                  )}
                  <button
                    onClick={handleLogout}
                    className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
                  >
                    Odjava
                  </button>
                </div>
              </div>
            </div>
          </header>

          <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {error && (
          <div className="mb-4 p-4 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-400 rounded">
            {error}
          </div>
        )}

        {/* Search Bar and Sorting */}
        <div className="mb-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            {/* Search Input */}
            <div className="relative">
              <input
                type="text"
                placeholder="Pretraži po tipu, finishu, boji ili ceni..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full px-4 py-2 pl-10 pr-4 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:border-blue-500"
              />
              <svg className="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </div>
            
            {/* Sort Dropdown */}
            <div>
              <select
                value={`${sortField || 'boja'}-${sortOrder || 'asc'}`}
                onChange={(e) => {
                  try {
                    const [field, order] = e.target.value.split('-');
                    if (field && order) {
                      setSortField(field);
                      setSortOrder(order as 'asc' | 'desc');
                    }
                  } catch (error) {
                    console.error('Sort change error:', error);
                  }
                }}
                className="custom-select w-full px-3 py-2 text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:border-blue-500"
              >
                <option value="boja-asc">Sortiraj po: Boja (A-Z)</option>
                <option value="boja-desc">Sortiraj po: Boja (Z-A)</option>
                <option value="tip-asc">Sortiraj po: Tip (A-Z)</option>
                <option value="tip-desc">Sortiraj po: Tip (Z-A)</option>
                <option value="finish-asc">Sortiraj po: Finish (A-Z)</option>
                <option value="finish-desc">Sortiraj po: Finish (Z-A)</option>
                <option value="created_at-desc">Sortiraj po: Poslednje dodano</option>
                <option value="created_at-asc">Sortiraj po: Prvo dodano</option>
                <option value="updated_at-desc">Sortiraj po: Poslednje ažurirano</option>
                <option value="updated_at-asc">Sortiraj po: Prvo ažurirano</option>
                <option value="kolicina-desc">Sortiraj po: Količina (visoka-niska)</option>
                <option value="kolicina-asc">Sortiraj po: Količina (niska-visoka)</option>
              </select>
            </div>
          </div>
        </div>

        {/* Add/Edit Form */}
        {(showAddForm || editingFilament) && (
          <div className="mb-8">
            <FilamentForm
              key={editingFilament?.id || 'new'}
              filament={editingFilament || {}}
              filaments={filaments}
              availableColors={availableColors}
              onSave={handleSave}
              onCancel={() => {
                setEditingFilament(null);
                setShowAddForm(false);
              }}
            />
          </div>
        )}

        {/* Filaments Table */}
        <div className="overflow-x-auto bg-white dark:bg-gray-800 rounded-lg shadow">
          <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead className="bg-gray-50 dark:bg-gray-700">
              <tr>
                <th className="px-6 py-3 text-left">
                  <input
                    type="checkbox"
                    checked={filteredAndSortedFilaments.length > 0 && selectedFilaments.size === filteredAndSortedFilaments.length}
                    onChange={toggleSelectAll}
                    className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                  />
                </th>
                <th onClick={() => handleSort('tip')} className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
                  Tip {sortField === 'tip' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('finish')} className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
                  Finish {sortField === 'finish' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('boja')} className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
                  Boja {sortField === 'boja' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('refill')} className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
                  Refill {sortField === 'refill' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('spulna')} className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
                  Spulna {sortField === 'spulna' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('kolicina')} className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
                  Količina {sortField === 'kolicina' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th onClick={() => handleSort('cena')} className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700">
                  Cena {sortField === 'cena' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Popust</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">Akcije</th>
              </tr>
            </thead>
            <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
              {filteredAndSortedFilaments.map((filament) => (
                <tr key={filament.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <input
                      type="checkbox"
                      checked={selectedFilaments.has(filament.id)}
                      onChange={() => toggleFilamentSelection(filament.id)}
                      className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
                    />
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{filament.tip}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{filament.finish}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    <div className="flex items-center gap-2">
                      {filament.boja_hex && (
                        <div 
                          className="w-7 h-7 rounded border border-gray-300 dark:border-gray-600" 
                          style={{ backgroundColor: filament.boja_hex }}
                          title={filament.boja_hex}
                        />
                      )}
                      <span>{filament.boja}</span>
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    {filament.refill > 0 ? (
                      <span className="text-green-600 dark:text-green-400 font-bold">{filament.refill}</span>
                    ) : (
                      <span className="text-gray-400 dark:text-gray-500">0</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">
                    {filament.spulna > 0 ? (
                      <span className="text-blue-500 dark:text-blue-400 font-bold">{filament.spulna}</span>
                    ) : (
                      <span className="text-gray-400 dark:text-gray-500">0</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-gray-100">{filament.kolicina}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900 dark:text-gray-100">
                    {(() => {
                      // First check if filament has custom prices stored
                      const hasRefill = filament.refill > 0;
                      const hasSpool = filament.spulna > 0;
                      
                      if (!hasRefill && !hasSpool) return '-';
                      
                      // Parse prices from the cena field if available (format: "3499" or "3499/3999")
                      let refillPrice = 3499;
                      let spoolPrice = 3999;
                      
                      if (filament.cena) {
                        const prices = filament.cena.split('/');
                        if (prices.length === 1) {
                          // Single price - use for whatever is in stock
                          refillPrice = parseInt(prices[0]) || 3499;
                          spoolPrice = parseInt(prices[0]) || 3999;
                        } else if (prices.length === 2) {
                          // Two prices - refill/spool format
                          refillPrice = parseInt(prices[0]) || 3499;
                          spoolPrice = parseInt(prices[1]) || 3999;
                        }
                      } else {
                        // Fallback to color defaults if no custom price
                        const colorData = availableColors.find(c => c.name === filament.boja);
                        refillPrice = colorData?.cena_refill || 3499;
                        spoolPrice = colorData?.cena_spulna || 3999;
                      }
                      
                      return (
                        <>
                          {hasRefill && (
                            <span className="text-green-600 dark:text-green-400">
                              {refillPrice.toLocaleString('sr-RS')}
                            </span>
                          )}
                          {hasRefill && hasSpool && <span className="mx-1">/</span>}
                          {hasSpool && (
                            <span className="text-blue-500 dark:text-blue-400">
                              {spoolPrice.toLocaleString('sr-RS')}
                            </span>
                          )}
                          <span className="ml-1 text-gray-600 dark:text-gray-400">RSD</span>
                        </>
                      );
                    })()}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm">
                    {filament.sale_active && filament.sale_percentage ? (
                      <div>
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200">
                          -{filament.sale_percentage}%
                        </span>
                        {filament.sale_end_date && (
                          <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                            do {new Date(filament.sale_end_date).toLocaleDateString('sr-RS')}
                          </div>
                        )}
                      </div>
                    ) : (
                      <span className="text-gray-400 dark:text-gray-500">-</span>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button
                      onClick={() => {
                        setEditingFilament(filament);
                        setShowAddForm(false);
                        window.scrollTo({ top: 0, behavior: 'smooth' });
                      }}
                      className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 mr-3"
                      title="Izmeni"
                    >
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                      </svg>
                    </button>
                    <button
                      onClick={() => handleDelete(filament.id)}
                      className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300"
                      title="Obriši"
                    >
                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
          </main>
      </div>
    </div>
  );
}

// Filament Form Component
function FilamentForm({ 
  filament, 
  filaments,
  availableColors,
  onSave, 
  onCancel 
}: { 
  filament: Partial<FilamentWithId>, 
  filaments: FilamentWithId[],
  availableColors: Array<{id: string, name: string, hex: string, cena_refill?: number, cena_spulna?: number}>,
  onSave: (filament: Partial<FilamentWithId>) => void,
  onCancel: () => void 
}) {
  const [formData, setFormData] = useState({
    tip: filament.tip || (filament.id ? '' : 'PLA'), // Default to PLA for new filaments
    finish: filament.finish || (filament.id ? '' : 'Basic'), // Default to Basic for new filaments
    boja: filament.boja || '',
    boja_hex: filament.boja_hex || '',
    refill: isSpoolOnly(filament.finish, filament.tip) ? 0 : (filament.refill || 0),  // Store as number
    spulna: isRefillOnly(filament.boja || '', filament.finish) ? 0 : (filament.spulna || 0), // Store as number
    kolicina: filament.kolicina || 0,  // Default to 0, stored as number
    cena: '', // Price is now determined by color selection
    cena_refill: 0,
    cena_spulna: 0,
  });

  // Update form when filament prop changes
  useEffect(() => {
    // Extract prices from the cena field if it exists (format: "3499/3999" or just "3499")
    let refillPrice = 0;
    let spulnaPrice = 0;
    
    if (filament.cena) {
      const prices = filament.cena.split('/');
      refillPrice = parseInt(prices[0]) || 0;
      spulnaPrice = prices.length > 1 ? parseInt(prices[1]) || 0 : parseInt(prices[0]) || 0;
    }
    
    // Get default prices from color
    const colorData = availableColors.find(c => c.name === filament.boja);
    if (!refillPrice && colorData?.cena_refill) refillPrice = colorData.cena_refill;
    if (!spulnaPrice && colorData?.cena_spulna) spulnaPrice = colorData.cena_spulna;
    
    setFormData({
      tip: filament.tip || (filament.id ? '' : 'PLA'), // Default to PLA for new filaments
      finish: filament.finish || (filament.id ? '' : 'Basic'), // Default to Basic for new filaments
      boja: filament.boja || '',
      boja_hex: filament.boja_hex || '',
      refill: filament.refill || 0,  // Store as number
      spulna: filament.spulna || 0,  // Store as number
      kolicina: filament.kolicina || 0,  // Default to 0, stored as number
      cena: filament.cena || '', // Keep original cena for compatibility
      cena_refill: refillPrice || 3499,
      cena_spulna: spulnaPrice || 3999,
    });
  }, [filament, availableColors]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    
    if (name === 'refill' || name === 'spulna' || name === 'cena_refill' || name === 'cena_spulna') {
      // Convert to number for numeric fields
      const numValue = parseInt(value) || 0;
      setFormData({
        ...formData,
        [name]: numValue
      });
    } else if (name === 'tip') {
      // If changing filament type, reset finish if it's not compatible
      const newTypeFinishes = FINISH_OPTIONS_BY_TYPE[value] || [];
      const resetFinish = !newTypeFinishes.includes(formData.finish);
      const spoolOnly = isSpoolOnly(formData.finish, value);
      // If changing to PPA with CF finish and current color is not black, reset color
      const needsColorReset = value === 'PPA' && formData.finish === 'CF' && formData.boja.toLowerCase() !== 'black';
      setFormData({
        ...formData,
        [name]: value,
        ...(resetFinish ? { finish: '' } : {}),
        ...(spoolOnly ? { refill: 0 } : {}),
        ...(needsColorReset ? { boja: '' } : {})
      });
    } else if (name === 'boja') {
      // If changing to a refill-only color, reset spulna to 0
      const refillOnly = isRefillOnly(value, formData.finish);
      setFormData({
        ...formData,
        [name]: value,
        ...(refillOnly ? { spulna: 0 } : {})
      });
    } else if (name === 'finish') {
      // If changing to Translucent finish, enable spool option and disable refill
      const refillOnly = isRefillOnly(formData.boja, value);
      const spoolOnly = isSpoolOnly(value, formData.tip);
      // If changing to PPA CF and current color is not black, reset color
      const needsColorReset = formData.tip === 'PPA' && value === 'CF' && formData.boja.toLowerCase() !== 'black';
      setFormData({
        ...formData,
        [name]: value,
        ...(refillOnly ? { spulna: 0 } : {}),
        ...(spoolOnly ? { refill: 0 } : {}),
        ...(needsColorReset ? { boja: '' } : {})
      });
    } else {
      setFormData({
        ...formData,
        [name]: value
      });
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Calculate total quantity
    const totalQuantity = formData.refill + formData.spulna;
    
    // Prevent adding filaments with 0 quantity
    if (totalQuantity === 0) {
      alert('Količina mora biti veća od 0. Dodajte refill ili spulna.');
      return;
    }
    
    // Use the prices from the form (which can be edited)
    const refillPrice = formData.cena_refill;
    const spoolPrice = formData.cena_spulna;
    
    // Determine the price string based on what's in stock
    let priceString = '';
    if (formData.refill > 0 && formData.spulna > 0) {
      priceString = `${refillPrice}/${spoolPrice}`;
    } else if (formData.refill > 0) {
      priceString = String(refillPrice);
    } else if (formData.spulna > 0) {
      priceString = String(spoolPrice);
    } else {
      priceString = '3499/3999'; // Default when no stock
    }
    
    // Pass only the data we want to save
    const dataToSave = {
      id: filament.id,
      tip: formData.tip,
      finish: formData.finish,
      boja: formData.boja,
      boja_hex: formData.boja_hex,
      refill: formData.refill,
      spulna: formData.spulna,
      cena: priceString
    };
    
    onSave(dataToSave);
  };

  return (
    <div className="mb-8 p-6 bg-white dark:bg-gray-800 rounded-lg shadow transition-colors">
      <h2 className="text-xl font-bold mb-4 text-gray-900 dark:text-white">
        {filament.id ? 'Izmeni filament' : 'Dodaj novi filament'}
      </h2>
      <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Tip</label>
          <select
            name="tip"
            value={formData.tip}
            onChange={handleChange}
            required
            className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">Izaberi tip</option>
            <option value="ABS">ABS</option>
            <option value="ASA">ASA</option>
            <option value="PA6">PA6</option>
            <option value="PAHT">PAHT</option>
            <option value="PC">PC</option>
            <option value="PET">PET</option>
            <option value="PETG">PETG</option>
            <option value="PLA">PLA</option>
            <option value="PPA">PPA</option>
            <option value="PPS">PPS</option>
            <option value="TPU">TPU</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Finish</label>
          <select
            name="finish"
            value={formData.finish}
            onChange={handleChange}
            required
            className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">Izaberi finish</option>
            {(FINISH_OPTIONS_BY_TYPE[formData.tip] || []).map(finish => (
              <option key={finish} value={finish}>{finish}</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Boja</label>
          <select
            name="boja"
            value={formData.boja}
            onChange={(e) => {
              const selectedColorName = e.target.value;
              let hexValue = formData.boja_hex;
              
              // Check available colors from database
              const dbColor = availableColors.find(c => c.name === selectedColorName);
              if (dbColor) {
                hexValue = dbColor.hex;
              }
              
              handleChange({
                target: {
                  name: 'boja',
                  value: selectedColorName
                }
              } as any);
              
              // Also update the hex value and prices
              setFormData(prev => ({
                ...prev,
                boja_hex: hexValue,
                cena_refill: dbColor?.cena_refill || prev.cena_refill || 3499,
                cena_spulna: dbColor?.cena_spulna || prev.cena_spulna || 3999
              }));
            }}
            required
            className="custom-select w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">Izaberite boju</option>
            {getFilteredColors(availableColors, formData.tip, formData.finish).map(color => (
              <option key={color.id} value={color.name}>
                {color.name}
              </option>
            ))}
            <option value="custom">Druga boja...</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
            {formData.boja && formData.boja !== 'custom' ? `Hex kod za ${formData.boja}` : 'Hex kod boje'}
          </label>
          <div className="flex items-center gap-2">
            <input
              type="color"
              name="boja_hex"
              value={formData.boja_hex || '#000000'}
              onChange={handleChange}
              disabled={false}
              className="w-full h-10 px-1 py-1 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
            />
            {formData.boja_hex && (
              <span className="text-sm text-gray-600 dark:text-gray-400">{formData.boja_hex}</span>
            )}
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
            <span className="text-green-600 dark:text-green-400">Cena Refill</span>
          </label>
          <input
            type="number"
            name="cena_refill"
            value={formData.cena_refill || availableColors.find(c => c.name === formData.boja)?.cena_refill || 3499}
            onChange={handleChange}
            min="0"
            step="1"
            placeholder="3499"
            disabled={isSpoolOnly(formData.finish, formData.tip)}
            className={`w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md ${
              isSpoolOnly(formData.finish, formData.tip) 
                ? 'bg-gray-100 dark:bg-gray-600 cursor-not-allowed' 
                : 'bg-white dark:bg-gray-700'
            } text-green-600 dark:text-green-400 font-bold focus:outline-none focus:ring-2 focus:ring-green-500`}
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
            <span className="text-blue-500 dark:text-blue-400">Cena Spulna</span>
          </label>
          <input
            type="number"
            name="cena_spulna"
            value={formData.cena_spulna || availableColors.find(c => c.name === formData.boja)?.cena_spulna || 3999}
            onChange={handleChange}
            min="0"
            step="1"
            placeholder="3999"
            disabled={isRefillOnly(formData.boja, formData.finish)}
            className={`w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md ${
              isRefillOnly(formData.boja, formData.finish) 
                ? 'bg-gray-100 dark:bg-gray-600 cursor-not-allowed text-gray-400' 
                : 'bg-white dark:bg-gray-700 text-blue-500 dark:text-blue-400 font-bold focus:outline-none focus:ring-2 focus:ring-blue-500'
            }`}
          />
        </div>

        {/* Quantity inputs for refill, vakuum, and otvoreno */}
        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
            Refill
            {isSpoolOnly(formData.finish, formData.tip) && (
              <span className="text-xs text-gray-500 dark:text-gray-400 ml-2">(samo spulna postoji)</span>
            )}
          </label>
          <input
            type="number"
            name="refill"
            value={formData.refill}
            onChange={handleChange}
            min="0"
            step="1"
            placeholder="0"
            disabled={isSpoolOnly(formData.finish, formData.tip)}
            className={`w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md ${
              isSpoolOnly(formData.finish, formData.tip) 
                ? 'bg-gray-100 dark:bg-gray-600 cursor-not-allowed' 
                : 'bg-white dark:bg-gray-700'
            } text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500`}
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
            Spulna
            {isRefillOnly(formData.boja, formData.finish) && (
              <span className="text-xs text-gray-500 dark:text-gray-400 ml-2">(samo refil postoji)</span>
            )}
          </label>
          <input
            type="number"
            name="spulna"
            value={formData.spulna}
            onChange={handleChange}
            min="0"
            step="1"
            placeholder="0"
            disabled={isRefillOnly(formData.boja, formData.finish)}
            className={`w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md ${
              isRefillOnly(formData.boja, formData.finish) 
                ? 'bg-gray-100 dark:bg-gray-600 cursor-not-allowed' 
                : 'bg-white dark:bg-gray-700'
            } text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500`}
          />
        </div>


        {/* Total quantity display */}
        <div>
          <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Ukupna količina</label>
          <input
            type="number"
            name="kolicina"
            value={formData.refill + formData.spulna}
            readOnly
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-gray-100 dark:bg-gray-600 text-gray-900 dark:text-gray-100 cursor-not-allowed"
          />
        </div>

        <div className="md:col-span-2 flex justify-end gap-4 mt-4">
          <button
            type="button"
            onClick={onCancel}
            className="px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-200 rounded hover:bg-gray-400 dark:hover:bg-gray-500 transition-colors"
          >
            Otkaži
          </button>
          <button
            type="submit"
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
          >
            Sačuvaj
          </button>
        </div>
      </form>
    </div>
  );
}