import { Document, Sentence } from '../../lib/documentApi';
import { Button } from '../ui/button';
import { FileText, ChevronLeft, ChevronRight, Plus, Trash2, Pencil, Check, X, Upload } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../ui/dialog';
import { Input } from '../ui/input';
import { useState } from 'react';

interface DocumentPanelProps {
  documents: Document[];
  selectedDocument: Document | null;
  currentPageIndex: number;
  onLoadDocument: (documentId: string) => void;
  onNewPage: () => void;
  onPageChange: (pageIndex: number) => void;
  onDeleteSentence: (sentenceId: string) => void;
  onDeleteDocument: (documentId: string) => void;
  onUpdateDocument: (documentId: string, title: string, description: string) => void;
  onLoadSentence: (sentence: Sentence) => void;
  loading: boolean;
}

export function DocumentPanel({
  documents,
  selectedDocument,
  currentPageIndex,
  onLoadDocument,
  onNewPage,
  onPageChange,
  onDeleteSentence,
  onDeleteDocument,
  onUpdateDocument,
  onLoadSentence,
  loading,
}: DocumentPanelProps) {
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const currentPage = selectedDocument?.pages[currentPageIndex];
  const totalPages = selectedDocument?.pages.length || 0;

  const handleDeleteClick = () => {
    setDeleteDialogOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!selectedDocument) return;

    setIsDeleting(true);
    try {
      await onDeleteDocument(selectedDocument.id);
      setDeleteDialogOpen(false);
    } finally {
      setIsDeleting(false);
    }
  };

  const handleEditClick = () => {
    if (!selectedDocument) return;
    setEditTitle(selectedDocument.title);
    setEditDescription(selectedDocument.description || '');
    setIsEditing(true);
  };

  const handleSaveEdit = async () => {
    if (!selectedDocument || !editTitle.trim()) return;

    await onUpdateDocument(selectedDocument.id, editTitle, editDescription);
    setIsEditing(false);
  };

  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditTitle('');
    setEditDescription('');
  };

  return (
    <div className="bg-white rounded-lg shadow p-6 space-y-6">
      {/* Document Selector */}
      <div>
        <h3 className="text-lg font-semibold text-gray-900 mb-3">Učitaj dokument</h3>
        <Select onValueChange={onLoadDocument} disabled={loading}>
          <SelectTrigger>
            <SelectValue placeholder="Odaberi dokument..." />
          </SelectTrigger>
          <SelectContent>
            {documents.length === 0 ? (
              <div className="p-2 text-sm text-gray-500">Nema spremljenih dokumenata</div>
            ) : (
              documents.map((doc) => (
                <SelectItem key={doc.id} value={doc.id}>
                  {doc.title}
                </SelectItem>
              ))
            )}
          </SelectContent>
        </Select>
      </div>

      {/* Current Document Info */}
      {selectedDocument && (
        <>
          <div className="border-t pt-4">
            {isEditing ? (
              <div className="space-y-3">
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Naslov</label>
                  <Input
                    value={editTitle}
                    onChange={(e) => setEditTitle(e.target.value)}
                    placeholder="Naslov dokumenta"
                    autoFocus
                  />
                </div>
                <div>
                  <label className="text-sm font-medium text-gray-700 mb-1 block">Opis</label>
                  <textarea
                    value={editDescription}
                    onChange={(e) => setEditDescription(e.target.value)}
                    placeholder="Dodajte opis dokumenta..."
                    className="flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
                  />
                </div>
                <div className="flex gap-2">
                  <Button
                    size="sm"
                    onClick={handleSaveEdit}
                    disabled={!editTitle.trim()}
                  >
                    <Check className="h-4 w-4 mr-1" />
                    Spremi
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={handleCancelEdit}
                  >
                    <X className="h-4 w-4 mr-1" />
                    Odustani
                  </Button>
                </div>
              </div>
            ) : (
              <>
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-lg font-semibold text-gray-900">
                    <FileText className="inline h-5 w-5 mr-2" />
                    {selectedDocument.title}
                  </h3>
                  <div className="flex gap-1">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleEditClick}
                    >
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={handleDeleteClick}
                      className="text-red-600 hover:text-red-800 hover:bg-red-50"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
                {selectedDocument.description && (
                  <p className="text-sm text-gray-600 mb-3">{selectedDocument.description}</p>
                )}
              </>
            )}
          </div>

          {/* Page Navigation */}
          <div className="border-t pt-4">
            <div className="flex items-center justify-between mb-3">
              <h4 className="font-semibold text-gray-900">Stranice</h4>
              <span className="text-sm text-gray-600">
                {currentPageIndex + 1} / {totalPages}
              </span>
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => onPageChange(currentPageIndex - 1)}
                disabled={currentPageIndex === 0}
              >
                <ChevronLeft className="h-4 w-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                className="flex-1"
                onClick={onNewPage}
              >
                <Plus className="h-4 w-4 mr-1" />
                Nova stranica
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => onPageChange(currentPageIndex + 1)}
                disabled={currentPageIndex >= totalPages - 1}
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* Sentence List */}
          <div className="border-t pt-4">
            <h4 className="font-semibold text-gray-900 mb-3">Popis rečenica</h4>
            {currentPage && currentPage.sentences.length > 0 ? (
              <div className="space-y-2 max-h-96 overflow-y-auto">
                {currentPage.sentences.map((sentence, index) => (
                  <div
                    key={sentence.id}
                    className="p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                  >
                    <div className="flex justify-between items-start mb-2">
                      <span className="text-xs font-semibold text-gray-500">
                        Rečenica {index + 1}
                      </span>
                      <div className="flex gap-2">
                        <button
                          onClick={() => onLoadSentence(sentence)}
                          className="text-blue-600 hover:text-blue-800 transition-colors"
                          aria-label="Učitaj rečenicu"
                          title="Učitaj rečenicu u gornju traku"
                        >
                          <Upload className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => onDeleteSentence(sentence.id)}
                          className="text-red-600 hover:text-red-800 transition-colors"
                          aria-label="Obriši rečenicu"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </div>
                    <div className="flex flex-wrap gap-1">
                      {sentence.tokens.map((token) => (
                        <span
                          key={token.id}
                          className="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded"
                        >
                          {token.displayText}
                        </span>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-gray-500 text-center py-4">
                Nema rečenica na ovoj stranici
              </p>
            )}
          </div>
        </>
      )}

      {/* Delete Confirmation Dialog */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Obriši dokument</DialogTitle>
            <DialogDescription>
              Jeste li sigurni da želite obrisati dokument "{selectedDocument?.title}"?
              Ova radnja se ne može poništiti.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteDialogOpen(false)}
              disabled={isDeleting}
            >
              Odustani
            </Button>
            <Button
              variant="destructive"
              onClick={handleConfirmDelete}
              disabled={isDeleting}
            >
              {isDeleting ? 'Brisanje...' : 'Obriši'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

