import React, { useState, useMemo } from 'react';
import { filamentService, colorService } from '@/src/services/api';
import { Filament } from '@/src/types/filament';

interface BulkFilamentPriceEditorProps {
  filaments: Array<Filament & { id: string }>;
  onUpdate: () => void;
}

export function BulkFilamentPriceEditor({ filaments, onUpdate }: BulkFilamentPriceEditorProps) {
  const [showModal, setShowModal] = useState(false);
  const [loading, setLoading] = useState(false);

  // Filters
  const [selectedMaterial, setSelectedMaterial] = useState<string>('');
  const [selectedFinish, setSelectedFinish] = useState<string>('');
  const [searchTerm, setSearchTerm] = useState('');

  // Price inputs
  const [newRefillPrice, setNewRefillPrice] = useState<string>('');
  const [newSpoolPrice, setNewSpoolPrice] = useState<string>('');

  // Get unique materials and finishes
  const materials = useMemo(() =>
    [...new Set(filaments.map(f => f.tip))].sort(),
    [filaments]
  );

  const finishes = useMemo(() =>
    [...new Set(filaments.map(f => f.finish))].sort(),
    [filaments]
  );

  // Filter filaments based on selections
  const filteredFilaments = useMemo(() => {
    return filaments.filter(f => {
      const matchesMaterial = !selectedMaterial || f.tip === selectedMaterial;
      const matchesFinish = !selectedFinish || f.finish === selectedFinish;
      const matchesSearch = !searchTerm ||
        f.boja.toLowerCase().includes(searchTerm.toLowerCase()) ||
        f.tip.toLowerCase().includes(searchTerm.toLowerCase()) ||
        f.finish.toLowerCase().includes(searchTerm.toLowerCase());

      return matchesMaterial && matchesFinish && matchesSearch;
    });
  }, [filaments, selectedMaterial, selectedFinish, searchTerm]);

  // Group filaments by color (since multiple filaments can have same color)
  const colorGroups = useMemo(() => {
    const groups = new Map<string, Array<Filament & { id: string }>>();
    filteredFilaments.forEach(f => {
      const existing = groups.get(f.boja) || [];
      existing.push(f);
      groups.set(f.boja, existing);
    });
    return Array.from(groups.entries()).sort((a, b) => a[0].localeCompare(b[0]));
  }, [filteredFilaments]);

  const handleApplyPrices = async () => {
    const refillPrice = parseInt(newRefillPrice);
    const spoolPrice = parseInt(newSpoolPrice);

    if (isNaN(refillPrice) && isNaN(spoolPrice)) {
      alert('Molimo unesite bar jednu cenu (refill ili spulna)');
      return;
    }

    if ((refillPrice && refillPrice < 0) || (spoolPrice && spoolPrice < 0)) {
      alert('Cena ne može biti negativna');
      return;
    }

    if (filteredFilaments.length === 0) {
      alert('Nema filamenata koji odgovaraju filterima');
      return;
    }

    const confirmMsg = `Želite da promenite cene za ${filteredFilaments.length} filament(a)?
${selectedMaterial ? `\nMaterijal: ${selectedMaterial}` : ''}
${selectedFinish ? `\nFiniš: ${selectedFinish}` : ''}
${!isNaN(refillPrice) ? `\nRefill cena: ${refillPrice}` : ''}
${!isNaN(spoolPrice) ? `\nSpulna cena: ${spoolPrice}` : ''}`;

    if (!confirm(confirmMsg)) {
      return;
    }

    setLoading(true);
    try {
      // Update each filament
      await Promise.all(
        filteredFilaments.map(async (filament) => {
          // Parse current prices
          const prices = filament.cena.split('/');
          const currentRefillPrice = parseInt(prices[0]) || 3499;
          const currentSpoolPrice = prices.length > 1 ? parseInt(prices[1]) || 3999 : 3999;

          // Use new prices if provided, otherwise keep current
          const finalRefillPrice = !isNaN(refillPrice) ? refillPrice : currentRefillPrice;
          const finalSpoolPrice = !isNaN(spoolPrice) ? spoolPrice : currentSpoolPrice;

          // Build price string based on quantities
          let priceString = '';
          if (filament.refill > 0 && filament.spulna > 0) {
            priceString = `${finalRefillPrice}/${finalSpoolPrice}`;
          } else if (filament.refill > 0) {
            priceString = String(finalRefillPrice);
          } else if (filament.spulna > 0) {
            priceString = String(finalSpoolPrice);
          } else {
            priceString = `${finalRefillPrice}/${finalSpoolPrice}`;
          }

          return filamentService.update(filament.id, {
            tip: filament.tip,
            finish: filament.finish,
            boja: filament.boja,
            boja_hex: filament.boja_hex,
            refill: filament.refill,
            spulna: filament.spulna,
            cena: priceString
          });
        })
      );

      alert(`Uspešno ažurirano ${filteredFilaments.length} filament(a)!`);
      setNewRefillPrice('');
      setNewSpoolPrice('');
      onUpdate();
      setShowModal(false);
    } catch (error) {
      console.error('Error updating prices:', error);
      alert('Greška pri ažuriranju cena');
    } finally {
      setLoading(false);
    }
  };

  const resetFilters = () => {
    setSelectedMaterial('');
    setSelectedFinish('');
    setSearchTerm('');
    setNewRefillPrice('');
    setNewSpoolPrice('');
  };

  return (
    <>
      <button
        onClick={() => setShowModal(true)}
        className="flex-1 sm:flex-initial px-3 sm:px-4 py-2 bg-indigo-500 text-white rounded hover:bg-indigo-600 text-sm sm:text-base"
      >
        Masovno editovanje cena
      </button>

      {showModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-5xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-xl font-bold text-gray-900 dark:text-white">
                Masovno editovanje cena
              </h2>
              <button
                onClick={() => setShowModal(false)}
                className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 text-2xl"
              >
                ✕
              </button>
            </div>

            {/* Filters */}
            <div className="mb-4 p-4 bg-gray-100 dark:bg-gray-700 rounded space-y-3">
              <h3 className="font-semibold text-gray-900 dark:text-white mb-2">Filteri:</h3>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Materijal
                  </label>
                  <select
                    value={selectedMaterial}
                    onChange={(e) => setSelectedMaterial(e.target.value)}
                    className="w-full px-3 py-2 border rounded dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                  >
                    <option value="">Svi materijali</option>
                    {materials.map(m => (
                      <option key={m} value={m}>{m}</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Finiš
                  </label>
                  <select
                    value={selectedFinish}
                    onChange={(e) => setSelectedFinish(e.target.value)}
                    className="w-full px-3 py-2 border rounded dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                  >
                    <option value="">Svi finiševi</option>
                    {finishes.map(f => (
                      <option key={f} value={f}>{f}</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Pretraga
                  </label>
                  <input
                    type="text"
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    placeholder="Pretraži boju, tip, finiš..."
                    className="w-full px-3 py-2 border rounded dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                  />
                </div>
              </div>

              <p className="text-sm text-gray-600 dark:text-gray-400">
                Prikazano: {filteredFilaments.length} filament(a)
              </p>
            </div>

            {/* Price inputs */}
            <div className="mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 rounded">
              <h3 className="font-semibold text-gray-900 dark:text-white mb-3">
                Nove cene za filtrirane filamente:
              </h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Refill cena
                  </label>
                  <input
                    type="number"
                    value={newRefillPrice}
                    onChange={(e) => setNewRefillPrice(e.target.value)}
                    placeholder="Npr. 3499"
                    className="w-full px-3 py-2 border rounded dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                    Spulna cena
                  </label>
                  <input
                    type="number"
                    value={newSpoolPrice}
                    onChange={(e) => setNewSpoolPrice(e.target.value)}
                    placeholder="Npr. 3999"
                    className="w-full px-3 py-2 border rounded dark:bg-gray-600 dark:border-gray-500 dark:text-white"
                  />
                </div>
              </div>
              <p className="text-sm text-gray-600 dark:text-gray-400 mt-2">
                Napomena: Možete promeniti samo refill, samo spulna, ili obe cene. Prazna polja će zadržati postojeće cene.
              </p>
            </div>

            {/* Preview */}
            <div className="flex-1 overflow-y-auto mb-4">
              <h3 className="font-semibold text-gray-900 dark:text-white mb-2">
                Pregled filamenata ({colorGroups.length} boja):
              </h3>
              {colorGroups.length === 0 ? (
                <p className="text-gray-500 dark:text-gray-400 text-center py-8">
                  Nema filamenata koji odgovaraju filterima
                </p>
              ) : (
                <table className="w-full text-sm">
                  <thead className="bg-gray-100 dark:bg-gray-700 sticky top-0">
                    <tr>
                      <th className="px-3 py-2 text-left text-gray-900 dark:text-white">Boja</th>
                      <th className="px-3 py-2 text-left text-gray-900 dark:text-white">Tip</th>
                      <th className="px-3 py-2 text-left text-gray-900 dark:text-white">Finiš</th>
                      <th className="px-3 py-2 text-left text-gray-900 dark:text-white">Refill</th>
                      <th className="px-3 py-2 text-left text-gray-900 dark:text-white">Spulna</th>
                      <th className="px-3 py-2 text-left text-gray-900 dark:text-white">Trenutna cena</th>
                      <th className="px-3 py-2 text-left text-gray-900 dark:text-white">Nova cena</th>
                    </tr>
                  </thead>
                  <tbody>
                    {colorGroups.map(([color, filamentGroup]) =>
                      filamentGroup.map((f, idx) => {
                        const prices = f.cena.split('/');
                        const currentRefillPrice = parseInt(prices[0]) || 3499;
                        const currentSpoolPrice = prices.length > 1 ? parseInt(prices[1]) || 3999 : 3999;

                        const refillPrice = parseInt(newRefillPrice);
                        const spoolPrice = parseInt(newSpoolPrice);

                        const finalRefillPrice = !isNaN(refillPrice) ? refillPrice : currentRefillPrice;
                        const finalSpoolPrice = !isNaN(spoolPrice) ? spoolPrice : currentSpoolPrice;

                        let newPriceString = '';
                        if (f.refill > 0 && f.spulna > 0) {
                          newPriceString = `${finalRefillPrice}/${finalSpoolPrice}`;
                        } else if (f.refill > 0) {
                          newPriceString = String(finalRefillPrice);
                        } else if (f.spulna > 0) {
                          newPriceString = String(finalSpoolPrice);
                        }

                        const priceChanged = newPriceString !== f.cena;

                        return (
                          <tr
                            key={`${f.id}-${idx}`}
                            className={`border-b dark:border-gray-700 ${priceChanged ? 'bg-yellow-50 dark:bg-yellow-900/20' : ''}`}
                          >
                            <td className="px-3 py-2 text-gray-900 dark:text-white">{f.boja}</td>
                            <td className="px-3 py-2 text-gray-700 dark:text-gray-300">{f.tip}</td>
                            <td className="px-3 py-2 text-gray-700 dark:text-gray-300">{f.finish}</td>
                            <td className="px-3 py-2 text-gray-700 dark:text-gray-300">{f.refill}</td>
                            <td className="px-3 py-2 text-gray-700 dark:text-gray-300">{f.spulna}</td>
                            <td className="px-3 py-2 text-gray-700 dark:text-gray-300">{f.cena}</td>
                            <td className={`px-3 py-2 font-semibold ${priceChanged ? 'text-green-600 dark:text-green-400' : 'text-gray-700 dark:text-gray-300'}`}>
                              {newPriceString || f.cena}
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              )}
            </div>

            {/* Actions */}
            <div className="flex justify-between gap-4 pt-4 border-t dark:border-gray-700">
              <button
                onClick={resetFilters}
                disabled={loading}
                className="px-4 py-2 bg-gray-300 text-gray-700 rounded hover:bg-gray-400 disabled:opacity-50"
              >
                Resetuj filtere
              </button>
              <div className="flex gap-2">
                <button
                  onClick={() => setShowModal(false)}
                  disabled={loading}
                  className="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 disabled:opacity-50"
                >
                  Zatvori
                </button>
                <button
                  onClick={handleApplyPrices}
                  disabled={loading || filteredFilaments.length === 0}
                  className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 disabled:opacity-50"
                >
                  {loading ? 'Čuvanje...' : `Primeni cene (${filteredFilaments.length})`}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
