'use client'

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import axios from 'axios';
import { Filament } from '../../../src/types/filament';

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

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);

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

  // Fetch filaments
  const fetchFilaments = async () => {
    try {
      setLoading(true);
      const response = await axios.get(`${process.env.NEXT_PUBLIC_API_URL}/filaments`);
      setFilaments(response.data);
    } catch (err) {
      setError('Greška pri učitavanju filamenata');
      console.error('Fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

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

  const getAuthHeaders = () => ({
    headers: {
      Authorization: `Bearer ${localStorage.getItem('authToken')}`
    }
  });

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

    try {
      await axios.delete(`${process.env.NEXT_PUBLIC_API_URL}/filaments/${id}`, getAuthHeaders());
      await fetchFilaments();
    } catch (err) {
      alert('Greška pri brisanju filamenta');
      console.error('Delete error:', err);
    }
  };

  const handleSave = async (filament: Partial<FilamentWithId>) => {
    try {
      if (filament.id) {
        // Update existing
        await axios.put(
          `${process.env.NEXT_PUBLIC_API_URL}/filaments/${filament.id}`,
          filament,
          getAuthHeaders()
        );
      } else {
        // Create new
        await axios.post(
          `${process.env.NEXT_PUBLIC_API_URL}/filaments`,
          filament,
          getAuthHeaders()
        );
      }
      
      setEditingFilament(null);
      setShowAddForm(false);
      await fetchFilaments();
    } catch (err) {
      alert('Greška pri čuvanju filamenta');
      console.error('Save error:', err);
    }
  };

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

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

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900">
      <header className="bg-white dark:bg-gray-800 shadow">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex justify-between items-center">
            <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
              Admin Dashboard
            </h1>
            <div className="flex gap-4">
              <button
                onClick={() => setShowAddForm(true)}
                className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
              >
                Dodaj novi filament
              </button>
              <button
                onClick={handleLogout}
                className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700"
              >
                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>
        )}

        {/* Add/Edit Form */}
        {(showAddForm || editingFilament) && (
          <FilamentForm
            filament={editingFilament || {}}
            onSave={handleSave}
            onCancel={() => {
              setEditingFilament(null);
              setShowAddForm(false);
            }}
          />
        )}

        {/* Filaments Table */}
        <div className="overflow-x-auto">
          <table className="min-w-full bg-white dark:bg-gray-800 shadow rounded">
            <thead>
              <tr className="bg-gray-100 dark:bg-gray-700">
                <th className="px-4 py-2 text-left">Brand</th>
                <th className="px-4 py-2 text-left">Tip</th>
                <th className="px-4 py-2 text-left">Finish</th>
                <th className="px-4 py-2 text-left">Boja</th>
                <th className="px-4 py-2 text-left">Refill</th>
                <th className="px-4 py-2 text-left">Vakum</th>
                <th className="px-4 py-2 text-left">Otvoreno</th>
                <th className="px-4 py-2 text-left">Količina</th>
                <th className="px-4 py-2 text-left">Cena</th>
                <th className="px-4 py-2 text-left">Akcije</th>
              </tr>
            </thead>
            <tbody>
              {filaments.map((filament) => (
                <tr key={filament.id} className="border-t dark:border-gray-700">
                  <td className="px-4 py-2">{filament.brand}</td>
                  <td className="px-4 py-2">{filament.tip}</td>
                  <td className="px-4 py-2">{filament.finish}</td>
                  <td className="px-4 py-2">{filament.boja}</td>
                  <td className="px-4 py-2">{filament.refill}</td>
                  <td className="px-4 py-2">{filament.vakum}</td>
                  <td className="px-4 py-2">{filament.otvoreno}</td>
                  <td className="px-4 py-2">{filament.kolicina}</td>
                  <td className="px-4 py-2">{filament.cena}</td>
                  <td className="px-4 py-2">
                    <button
                      onClick={() => setEditingFilament(filament)}
                      className="text-blue-600 hover:text-blue-800 mr-2"
                    >
                      Izmeni
                    </button>
                    <button
                      onClick={() => handleDelete(filament.id)}
                      className="text-red-600 hover:text-red-800"
                    >
                      Obriši
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </main>
    </div>
  );
}

// Filament Form Component
function FilamentForm({ 
  filament, 
  onSave, 
  onCancel 
}: { 
  filament: Partial<FilamentWithId>, 
  onSave: (filament: Partial<FilamentWithId>) => void,
  onCancel: () => void 
}) {
  const [formData, setFormData] = useState({
    brand: filament.brand || '',
    tip: filament.tip || '',
    finish: filament.finish || '',
    boja: filament.boja || '',
    refill: filament.refill || '',
    vakum: filament.vakum || '',
    otvoreno: filament.otvoreno || '',
    kolicina: filament.kolicina || '',
    cena: filament.cena || '',
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onSave({
      ...filament,
      ...formData
    });
  };

  return (
    <div className="mb-8 p-6 bg-white dark:bg-gray-800 rounded shadow">
      <h2 className="text-xl font-bold mb-4">
        {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">Brand</label>
          <input
            type="text"
            name="brand"
            value={formData.brand}
            onChange={handleChange}
            required
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          />
        </div>
        
        <div>
          <label className="block text-sm font-medium mb-1">Tip</label>
          <select
            name="tip"
            value={formData.tip}
            onChange={handleChange}
            required
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          >
            <option value="">Izaberi tip</option>
            <option value="PLA">PLA</option>
            <option value="PETG">PETG</option>
            <option value="ABS">ABS</option>
            <option value="TPU">TPU</option>
            <option value="Silk PLA">Silk PLA</option>
            <option value="PLA Matte">PLA Matte</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Finish</label>
          <select
            name="finish"
            value={formData.finish}
            onChange={handleChange}
            required
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          >
            <option value="">Izaberi finish</option>
            <option value="Basic">Basic</option>
            <option value="Matte">Matte</option>
            <option value="Silk">Silk</option>
            <option value="Metal">Metal</option>
            <option value="Glow">Glow</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Boja</label>
          <input
            type="text"
            name="boja"
            value={formData.boja}
            onChange={handleChange}
            required
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Refill</label>
          <select
            name="refill"
            value={formData.refill}
            onChange={handleChange}
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          >
            <option value="">Ne</option>
            <option value="Da">Da</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Vakum</label>
          <input
            type="text"
            name="vakum"
            value={formData.vakum}
            onChange={handleChange}
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Otvoreno</label>
          <input
            type="text"
            name="otvoreno"
            value={formData.otvoreno}
            onChange={handleChange}
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Količina</label>
          <input
            type="text"
            name="kolicina"
            value={formData.kolicina}
            onChange={handleChange}
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          />
        </div>

        <div>
          <label className="block text-sm font-medium mb-1">Cena</label>
          <input
            type="text"
            name="cena"
            value={formData.cena}
            onChange={handleChange}
            className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
          />
        </div>

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