'use client';

import { useState, useEffect } from 'react';
import { filamentService, productService, analyticsService } from '@/src/services/api';
import { Filament } from '@/src/types/filament';
import { Product, SalesStats } from '@/src/types/product';

export default function ProdajaPage() {
  const [salesStats, setSalesStats] = useState<SalesStats | null>(null);
  const [filaments, setFilaments] = useState<(Filament & { id: string })[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  // Filament sale form
  const [filamentSalePercentage, setFilamentSalePercentage] = useState(10);
  const [filamentSaleEndDate, setFilamentSaleEndDate] = useState('');
  const [filamentSaleEnabled, setFilamentSaleEnabled] = useState(true);

  // Product sale form
  const [productSalePercentage, setProductSalePercentage] = useState(10);
  const [productSaleEndDate, setProductSaleEndDate] = useState('');
  const [productSaleEnabled, setProductSaleEnabled] = useState(true);

  const [savingFilamentSale, setSavingFilamentSale] = useState(false);
  const [savingProductSale, setSavingProductSale] = useState(false);

  const fetchData = async () => {
    try {
      setLoading(true);
      const [filamentData, productData, salesData] = await Promise.all([
        filamentService.getAll(),
        productService.getAll().catch(() => []),
        analyticsService.getSales().catch(() => null),
      ]);
      setFilaments(filamentData);
      setProducts(productData);
      setSalesStats(salesData);
    } catch (err) {
      setError('Greska pri ucitavanju podataka');
      console.error('Fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const getCurrentDateTime = () => {
    const now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    return now.toISOString().slice(0, 16);
  };

  const handleFilamentBulkSale = async () => {
    if (!confirm('Primeniti popust na SVE filamente?')) return;
    setSavingFilamentSale(true);
    try {
      await filamentService.updateBulkSale({
        salePercentage: filamentSalePercentage,
        saleEndDate: filamentSaleEndDate || undefined,
        enableSale: filamentSaleEnabled,
      });
      await fetchData();
    } catch (err) {
      setError('Greska pri azuriranju popusta za filamente');
      console.error(err);
    } finally {
      setSavingFilamentSale(false);
    }
  };

  const handleClearFilamentSales = async () => {
    if (!confirm('Ukloniti SVE popuste sa filamenata?')) return;
    setSavingFilamentSale(true);
    try {
      await filamentService.updateBulkSale({
        salePercentage: 0,
        enableSale: false,
      });
      await fetchData();
    } catch (err) {
      setError('Greska pri brisanju popusta');
      console.error(err);
    } finally {
      setSavingFilamentSale(false);
    }
  };

  const handleProductBulkSale = async () => {
    if (!confirm('Primeniti popust na SVE proizvode?')) return;
    setSavingProductSale(true);
    try {
      await productService.updateBulkSale({
        salePercentage: productSalePercentage,
        saleEndDate: productSaleEndDate || undefined,
        enableSale: productSaleEnabled,
      });
      await fetchData();
    } catch (err) {
      setError('Greska pri azuriranju popusta za proizvode');
      console.error(err);
    } finally {
      setSavingProductSale(false);
    }
  };

  const handleClearProductSales = async () => {
    if (!confirm('Ukloniti SVE popuste sa proizvoda?')) return;
    setSavingProductSale(true);
    try {
      await productService.updateBulkSale({
        salePercentage: 0,
        enableSale: false,
      });
      await fetchData();
    } catch (err) {
      setError('Greska pri brisanju popusta');
      console.error(err);
    } finally {
      setSavingProductSale(false);
    }
  };

  const activeFilamentSales = filaments.filter(f => f.sale_active);
  const activeProductSales = products.filter(p => p.sale_active);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-white/40">Ucitavanje...</div>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Page Header */}
      <div>
        <h1 className="text-2xl font-black text-white tracking-tight" style={{ fontFamily: 'var(--font-display)' }}>Upravljanje popustima</h1>
        <p className="text-white/40 mt-1">
          {activeFilamentSales.length + activeProductSales.length} aktivnih popusta
        </p>
      </div>

      {error && (
        <div className="p-4 bg-red-900/20 text-red-400 rounded">
          {error}
        </div>
      )}

      {/* Overview Stats */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div className="bg-white/[0.04] p-5 rounded-2xl">
          <p className="text-sm text-white/40">Filamenti sa popustom</p>
          <p className="text-3xl font-bold text-purple-400 mt-1">{activeFilamentSales.length}</p>
          <p className="text-xs text-white/30 mt-1">od {filaments.length} ukupno</p>
        </div>
        <div className="bg-white/[0.04] p-5 rounded-2xl">
          <p className="text-sm text-white/40">Proizvodi sa popustom</p>
          <p className="text-3xl font-bold text-orange-400 mt-1">{activeProductSales.length}</p>
          <p className="text-xs text-white/30 mt-1">od {products.length} ukupno</p>
        </div>
        <div className="bg-white/[0.04] p-5 rounded-2xl">
          <p className="text-sm text-white/40">Ukupno aktivnih</p>
          <p className="text-3xl font-bold text-blue-400 mt-1">
            {activeFilamentSales.length + activeProductSales.length}
          </p>
        </div>
      </div>

      {/* Filament Sale Controls */}
      <div className="bg-white/[0.04] rounded-2xl p-6">
        <h2 className="text-lg font-semibold text-white mb-4">Popusti na filamente</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
          <div>
            <label className="block text-sm font-medium text-white/60 mb-1">Procenat popusta (%)</label>
            <input
              type="number"
              min="0"
              max="100"
              value={filamentSalePercentage}
              onChange={(e) => setFilamentSalePercentage(parseInt(e.target.value) || 0)}
              className="w-full px-3 py-2 border border-white/[0.08] rounded-md bg-white/[0.06] text-white/90"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-white/60 mb-1">Kraj popusta (opciono)</label>
            <input
              type="datetime-local"
              value={filamentSaleEndDate}
              onChange={(e) => setFilamentSaleEndDate(e.target.value)}
              min={getCurrentDateTime()}
              className="w-full px-3 py-2 border border-white/[0.08] rounded-md bg-white/[0.06] text-white/90"
            />
          </div>
          <div className="flex items-end">
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={filamentSaleEnabled}
                onChange={(e) => setFilamentSaleEnabled(e.target.checked)}
                className="w-4 h-4 text-purple-600"
              />
              <span className="text-sm text-white/60">
                Aktivan: <span className={filamentSaleEnabled ? 'text-green-400' : 'text-white/30'}>{filamentSaleEnabled ? 'Da' : 'Ne'}</span>
              </span>
            </label>
          </div>
        </div>
        <div className="flex gap-3">
          <button
            onClick={handleFilamentBulkSale}
            disabled={savingFilamentSale}
            className="px-4 py-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 disabled:opacity-50 text-sm"
          >
            {savingFilamentSale ? 'Cuvanje...' : 'Primeni na sve filamente'}
          </button>
          <button
            onClick={handleClearFilamentSales}
            disabled={savingFilamentSale}
            className="px-4 py-2 bg-white/[0.08] text-white/70 rounded-xl hover:bg-white/[0.1] disabled:opacity-50 text-sm"
          >
            Ukloni sve popuste
          </button>
        </div>
      </div>

      {/* Product Sale Controls */}
      <div className="bg-white/[0.04] rounded-2xl p-6">
        <h2 className="text-lg font-semibold text-white mb-4">Popusti na proizvode</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
          <div>
            <label className="block text-sm font-medium text-white/60 mb-1">Procenat popusta (%)</label>
            <input
              type="number"
              min="0"
              max="100"
              value={productSalePercentage}
              onChange={(e) => setProductSalePercentage(parseInt(e.target.value) || 0)}
              className="w-full px-3 py-2 border border-white/[0.08] rounded-md bg-white/[0.06] text-white/90"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-white/60 mb-1">Kraj popusta (opciono)</label>
            <input
              type="datetime-local"
              value={productSaleEndDate}
              onChange={(e) => setProductSaleEndDate(e.target.value)}
              min={getCurrentDateTime()}
              className="w-full px-3 py-2 border border-white/[0.08] rounded-md bg-white/[0.06] text-white/90"
            />
          </div>
          <div className="flex items-end">
            <label className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={productSaleEnabled}
                onChange={(e) => setProductSaleEnabled(e.target.checked)}
                className="w-4 h-4 text-orange-600"
              />
              <span className="text-sm text-white/60">
                Aktivan: <span className={productSaleEnabled ? 'text-green-400' : 'text-white/30'}>{productSaleEnabled ? 'Da' : 'Ne'}</span>
              </span>
            </label>
          </div>
        </div>
        <div className="flex gap-3">
          <button
            onClick={handleProductBulkSale}
            disabled={savingProductSale}
            className="px-4 py-2 bg-orange-600 text-white rounded-xl hover:bg-orange-700 disabled:opacity-50 text-sm"
          >
            {savingProductSale ? 'Cuvanje...' : 'Primeni na sve proizvode'}
          </button>
          <button
            onClick={handleClearProductSales}
            disabled={savingProductSale}
            className="px-4 py-2 bg-white/[0.08] text-white/70 rounded-xl hover:bg-white/[0.1] disabled:opacity-50 text-sm"
          >
            Ukloni sve popuste
          </button>
        </div>
      </div>

      {/* Active Sales List */}
      {(activeFilamentSales.length > 0 || activeProductSales.length > 0) && (
        <div className="bg-white/[0.04] rounded-2xl p-6">
          <h2 className="text-lg font-semibold text-white mb-4">Aktivni popusti</h2>

          {activeFilamentSales.length > 0 && (
            <div className="mb-6">
              <h3 className="text-sm font-medium text-purple-400 mb-2">Filamenti ({activeFilamentSales.length})</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-white/[0.06]">
                    <tr>
                      <th className="px-3 py-2 text-left text-white/60">Filament</th>
                      <th className="px-3 py-2 text-left text-white/60">Popust</th>
                      <th className="px-3 py-2 text-left text-white/60">Istice</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/[0.06]">
                    {activeFilamentSales.map(f => (
                      <tr key={f.id} className="hover:bg-white/[0.06]">
                        <td className="px-3 py-2 text-white/90">{f.tip} {f.finish} - {f.boja}</td>
                        <td className="px-3 py-2">
                          <span className="text-purple-300 font-medium">-{f.sale_percentage}%</span>
                        </td>
                        <td className="px-3 py-2 text-white/40">
                          {f.sale_end_date
                            ? new Date(f.sale_end_date).toLocaleDateString('sr-RS')
                            : 'Neograniceno'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {activeProductSales.length > 0 && (
            <div>
              <h3 className="text-sm font-medium text-orange-400 mb-2">Proizvodi ({activeProductSales.length})</h3>
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-white/[0.06]">
                    <tr>
                      <th className="px-3 py-2 text-left text-white/60">Proizvod</th>
                      <th className="px-3 py-2 text-left text-white/60">Popust</th>
                      <th className="px-3 py-2 text-left text-white/60">Istice</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/[0.06]">
                    {activeProductSales.map(p => (
                      <tr key={p.id} className="hover:bg-white/[0.06]">
                        <td className="px-3 py-2 text-white/90">{p.name}</td>
                        <td className="px-3 py-2">
                          <span className="text-orange-300 font-medium">-{p.sale_percentage}%</span>
                        </td>
                        <td className="px-3 py-2 text-white/40">
                          {p.sale_end_date
                            ? new Date(p.sale_end_date).toLocaleDateString('sr-RS')
                            : 'Neograniceno'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
