import { useState, useEffect } from 'react';
import { Layout } from '../components/layout/Layout';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Plus, Pencil, Trash2, Video, Search } from 'lucide-react';
import api from '../lib/api';
import { Term } from '../types/term';
import { TermForm } from '../components/admin/TermForm';
import { VideoUpload } from '../components/admin/VideoUpload';
import { toast } from 'sonner';

export function AdminTerms() {
  const [terms, setTerms] = useState<Term[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editingTerm, setEditingTerm] = useState<Term | null>(null);
  const [uploadingVideoFor, setUploadingVideoFor] = useState<Term | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  const fetchTerms = async () => {
    try {
      setIsLoading(true);
      const params = new URLSearchParams();
      if (searchQuery) params.append('query', searchQuery);
      params.append('page', page.toString());
      params.append('limit', '20');

      const response = await api.get(`/api/terms?${params.toString()}`);
      setTerms(response.data.terms);
      setTotalPages(response.data.pagination.totalPages);
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to fetch terms');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchTerms();
  }, [page, searchQuery]);

  const handleDelete = async (id: string) => {
    if (!confirm('Jeste li sigurni da želite obrisati ovu riječ?')) return;

    try {
      await api.delete(`/api/terms/${id}`);
      toast.success('Riječ uspješno obrisana');
      fetchTerms();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to delete term');
    }
  };

  const handleFormSuccess = () => {
    setShowCreateForm(false);
    setEditingTerm(null);
    fetchTerms();
  };

  const handleVideoUploadSuccess = () => {
    setUploadingVideoFor(null);
    fetchTerms();
  };

  if (isLoading && terms.length === 0) {
    return (
      <Layout>
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"></div>
            <p className="mt-4 text-muted-foreground">Učitavanje...</p>
          </div>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <h1 className="text-3xl font-bold text-foreground">Upravljanje riječima</h1>
          <Button onClick={() => setShowCreateForm(true)} disabled={showCreateForm || !!editingTerm}>
            <Plus className="h-4 w-4 mr-2" />
            Dodaj riječ
          </Button>
        </div>

        {/* Search Bar */}
        <div className="flex gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              type="text"
              placeholder="Pretraži riječi..."
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setPage(1);
              }}
              className="pl-10"
            />
          </div>
        </div>

        {/* Create/Edit Form */}
        {(showCreateForm || editingTerm) && (
          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-xl font-semibold mb-4">
              {editingTerm ? 'Uredi riječ' : 'Dodaj novu riječ'}
            </h2>
            <TermForm
              term={editingTerm || undefined}
              onSuccess={handleFormSuccess}
              onCancel={() => {
                setShowCreateForm(false);
                setEditingTerm(null);
              }}
            />
          </div>
        )}

        {/* Video Upload Modal */}
        {uploadingVideoFor && (
          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-xl font-semibold mb-4">
              Video za: {uploadingVideoFor.wordText}
            </h2>
            <VideoUpload
              term={uploadingVideoFor}
              onSuccess={handleVideoUploadSuccess}
              onCancel={() => setUploadingVideoFor(null)}
            />
          </div>
        )}

        {/* Terms Table */}
        <div className="bg-white rounded-lg shadow overflow-hidden">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Riječ
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Vrsta
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  CEFR
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Video
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Akcije
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {terms.map((term) => (
                <tr key={term.id}>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{term.wordText}</div>
                    {term.shortDescription && (
                      <div className="text-sm text-gray-500">{term.shortDescription}</div>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {term.wordType}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {term.cefrLevel}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      term.media && term.media.length > 0
                        ? 'bg-green-100 text-green-800'
                        : 'bg-gray-100 text-gray-800'
                    }`}>
                      {term.media && term.media.length > 0 ? `${term.media.length} video(a)` : 'Nema videa'}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <div className="flex justify-end gap-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setUploadingVideoFor(term)}
                        title="Dodaj/Upravljaj videom"
                      >
                        <Video className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setEditingTerm(term)}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDelete(term.id)}
                      >
                        <Trash2 className="h-4 w-4 text-red-600" />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex justify-center gap-2">
            <Button
              variant="outline"
              onClick={() => setPage(p => Math.max(1, p - 1))}
              disabled={page === 1}
            >
              Prethodna
            </Button>
            <span className="flex items-center px-4">
              Stranica {page} od {totalPages}
            </span>
            <Button
              variant="outline"
              onClick={() => setPage(p => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
            >
              Sljedeća
            </Button>
          </div>
        )}
      </div>
    </Layout>
  );
}

