'use client';

import React, { useState, useEffect } from 'react';
import { colorRequestService } from '@/src/services/api';

interface ColorRequest {
  id: string;
  color_name: string;
  material_type: string;
  finish_type: string;
  user_email: string;
  user_phone: string;
  user_name: string;
  description: string;
  reference_url: string;
  status: 'pending' | 'approved' | 'rejected' | 'completed';
  admin_notes: string;
  request_count: number;
  created_at: string;
  updated_at: string;
  processed_at: string;
  processed_by: string;
}

export default function ZahteviPage() {
  const [requests, setRequests] = useState<ColorRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState({ status: '', admin_notes: '' });

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

  const fetchRequests = async () => {
    try {
      const data = await colorRequestService.getAll();
      setRequests(data);
    } catch (error) {
      setError('Failed to fetch color requests');
      console.error('Error:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleStatusUpdate = async (id: string) => {
    try {
      await colorRequestService.updateStatus(id, editForm.status, editForm.admin_notes);
      await fetchRequests();
      setEditingId(null);
      setEditForm({ status: '', admin_notes: '' });
    } catch (error) {
      setError('Failed to update request');
      console.error('Error:', error);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this request?')) return;

    try {
      await colorRequestService.delete(id);
      await fetchRequests();
    } catch (error) {
      setError('Failed to delete request');
      console.error('Error:', error);
    }
  };

  const getStatusBadge = (status: string) => {
    const colors = {
      pending: 'bg-yellow-900/30 text-yellow-300',
      approved: 'bg-green-900/30 text-green-300',
      rejected: 'bg-red-900/30 text-red-300',
      completed: 'bg-blue-900/30 text-blue-300'
    };
    return colors[status as keyof typeof colors] || 'bg-white/[0.06] text-white/60';
  };

  const getStatusLabel = (status: string) => {
    const labels = {
      pending: 'Na cekanju',
      approved: 'Odobreno',
      rejected: 'Odbijeno',
      completed: 'Zavrseno'
    };
    return labels[status as keyof typeof labels] || status;
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    const month = date.toLocaleDateString('sr-RS', { month: 'short' });
    const capitalizedMonth = month.charAt(0).toUpperCase() + month.slice(1);
    return `${capitalizedMonth} ${date.getDate()}, ${date.getFullYear()}`;
  };

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

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <div>
        <h1 className="text-2xl font-bold text-white">Zahtevi za Boje</h1>
        <p className="text-white/40 mt-1">{requests.length} zahteva ukupno</p>
      </div>

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

      <div className="bg-white/[0.04] rounded-2xl shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-white/[0.06]">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/40 uppercase tracking-wider">
                  Boja
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/40 uppercase tracking-wider">
                  Materijal/Finis
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/40 uppercase tracking-wider">
                  Broj Zahteva
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/40 uppercase tracking-wider">
                  Korisnik
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/40 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/40 uppercase tracking-wider">
                  Datum
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-white/40 uppercase tracking-wider">
                  Akcije
                </th>
              </tr>
            </thead>
            <tbody className="bg-white/[0.04] divide-y divide-white/[0.06]">
              {requests.map((request) => (
                <tr key={request.id} className="hover:bg-white/[0.06]">
                  <td className="px-4 py-3">
                    <div>
                      <div className="font-medium text-white/90">{request.color_name}</div>
                      {request.description && (
                        <div className="text-sm text-white/40 mt-1">{request.description}</div>
                      )}
                      {request.reference_url && (
                        <a
                          href={request.reference_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-xs text-blue-400 hover:underline"
                        >
                          Pogledaj referencu
                        </a>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-sm">
                      <div className="text-white/90">{request.material_type}</div>
                      {request.finish_type && (
                        <div className="text-white/40">{request.finish_type}</div>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-purple-900/30 text-purple-300">
                      {request.request_count || 1} {(request.request_count || 1) === 1 ? 'zahtev' : 'zahteva'}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-sm">
                      {request.user_email ? (
                        <a href={`mailto:${request.user_email}`} className="text-blue-400 hover:underline">
                          {request.user_email}
                        </a>
                      ) : (
                        <span className="text-white/30">Anonimno</span>
                      )}
                      {request.user_phone && (
                        <div className="mt-1">
                          <a href={`tel:${request.user_phone}`} className="text-blue-400 hover:underline">
                            {request.user_phone}
                          </a>
                        </div>
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    {editingId === request.id ? (
                      <div className="space-y-2">
                        <select
                          value={editForm.status}
                          onChange={(e) => setEditForm({ ...editForm, status: e.target.value })}
                          className="text-sm border rounded px-2 py-1 bg-white/[0.06] border-white/[0.08] text-white/90"
                        >
                          <option value="">Izaberi status</option>
                          <option value="pending">Na cekanju</option>
                          <option value="approved">Odobreno</option>
                          <option value="rejected">Odbijeno</option>
                          <option value="completed">Zavrseno</option>
                        </select>
                        <textarea
                          placeholder="Napomene..."
                          value={editForm.admin_notes}
                          onChange={(e) => setEditForm({ ...editForm, admin_notes: e.target.value })}
                          className="text-sm border rounded px-2 py-1 w-full bg-white/[0.06] border-white/[0.08] text-white/90"
                          rows={2}
                        />
                      </div>
                    ) : (
                      <div>
                        <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${getStatusBadge(request.status)}`}>
                          {getStatusLabel(request.status)}
                        </span>
                        {request.admin_notes && (
                          <div className="text-xs text-white/30 mt-1">{request.admin_notes}</div>
                        )}
                        {request.processed_by && (
                          <div className="text-xs text-white/30 mt-1">
                            od {request.processed_by}
                          </div>
                        )}
                      </div>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    <div className="text-sm text-white/40">
                      {formatDate(request.created_at)}
                    </div>
                    {request.processed_at && (
                      <div className="text-xs text-white/30">
                        Obradjeno: {formatDate(request.processed_at)}
                      </div>
                    )}
                  </td>
                  <td className="px-4 py-3">
                    {editingId === request.id ? (
                      <div className="space-x-2">
                        <button
                          onClick={() => handleStatusUpdate(request.id)}
                          className="text-green-400 hover:text-green-300 text-sm"
                        >
                          Sacuvaj
                        </button>
                        <button
                          onClick={() => {
                            setEditingId(null);
                            setEditForm({ status: '', admin_notes: '' });
                          }}
                          className="text-white/40 hover:text-white/60 text-sm"
                        >
                          Otkazi
                        </button>
                      </div>
                    ) : (
                      <div className="space-x-2">
                        <button
                          onClick={() => {
                            setEditingId(request.id);
                            setEditForm({
                              status: request.status,
                              admin_notes: request.admin_notes || ''
                            });
                          }}
                          className="text-blue-400 hover:text-blue-300 text-sm"
                        >
                          Izmeni
                        </button>
                        <button
                          onClick={() => handleDelete(request.id)}
                          className="text-red-400 hover:text-red-300 text-sm"
                        >
                          Obrisi
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {requests.length === 0 && (
          <div className="text-center py-8 text-white/40">
            Nema zahteva za boje
          </div>
        )}
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white/[0.04] p-4 rounded-2xl shadow">
          <div className="text-sm text-white/40">Ukupno Zahteva</div>
          <div className="text-2xl font-bold text-white/90">
            {requests.length}
          </div>
        </div>
        <div className="bg-white/[0.04] p-4 rounded-2xl shadow">
          <div className="text-sm text-white/40">Na Cekanju</div>
          <div className="text-2xl font-bold text-yellow-400">
            {requests.filter(r => r.status === 'pending').length}
          </div>
        </div>
        <div className="bg-white/[0.04] p-4 rounded-2xl shadow">
          <div className="text-sm text-white/40">Odobreno</div>
          <div className="text-2xl font-bold text-green-400">
            {requests.filter(r => r.status === 'approved').length}
          </div>
        </div>
        <div className="bg-white/[0.04] p-4 rounded-2xl shadow">
          <div className="text-sm text-white/40">Zavrseno</div>
          <div className="text-2xl font-bold text-blue-400">
            {requests.filter(r => r.status === 'completed').length}
          </div>
        </div>
      </div>
    </div>
  );
}
