import { useState, useEffect } from 'react';
import { Layout } from '../components/layout/Layout';
import { TokenTray } from '../components/znakopis/TokenTray';
import { DocumentPanel } from '../components/znakopis/DocumentPanel';
import { CreateDocumentDialog } from '../components/znakopis/CreateDocumentDialog';
import { useSentenceStore, SentenceToken } from '../stores/sentenceStore';
import { documentApi, Document, Sentence } from '../lib/documentApi';
import { toast } from 'sonner';
import { Button } from '../components/ui/button';
import { Save, FileText } from 'lucide-react';

function Znakopis() {
  const { currentTokens, clearTokens, setTokens } = useSentenceStore();
  const [documents, setDocuments] = useState<Document[]>([]);
  const [selectedDocument, setSelectedDocument] = useState<Document | null>(null);
  const [currentPageIndex, setCurrentPageIndex] = useState(0);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);

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

  const loadDocuments = async () => {
    try {
      setLoading(true);
      const docs = await documentApi.getDocuments();
      setDocuments(docs);
    } catch (error) {
      console.error('Failed to load documents:', error);
      toast.error('Greška pri učitavanju dokumenata');
    } finally {
      setLoading(false);
    }
  };

  const handleSaveDocument = async () => {
    if (currentTokens.length === 0) {
      toast.error('Dodajte riječi u rečenicu prije spremanja');
      return;
    }

    try {
      setSaving(true);

      let document = selectedDocument;

      // Create new document if none selected
      if (!document) {
        const title = `Dokument ${new Date().toLocaleDateString('hr-HR')}`;
        document = await documentApi.createDocument({
          title,
          description: 'Novi dokument',
        });
        setSelectedDocument(document);
      }

      // Create sentence with current tokens
      const tokens = currentTokens.map((token) => ({
        termId: token.termId,
        displayText: token.displayText,
        isPunctuation: token.isPunctuation,
      }));

      await documentApi.createSentence(document.id, currentPageIndex, { tokens });

      // Reload document to get updated data
      const updatedDoc = await documentApi.getDocument(document.id);
      setSelectedDocument(updatedDoc);
      
      // Update documents list
      await loadDocuments();

      // Clear current tokens
      clearTokens();

      toast.success('Rečenica spremljena!');
    } catch (error) {
      console.error('Failed to save document:', error);
      toast.error('Greška pri spremanju dokumenta');
    } finally {
      setSaving(false);
    }
  };

  const handleLoadDocument = async (documentId: string) => {
    try {
      setLoading(true);
      const doc = await documentApi.getDocument(documentId);
      setSelectedDocument(doc);
      setCurrentPageIndex(0);
      toast.success(`Učitan dokument: ${doc.title}`);
    } catch (error) {
      console.error('Failed to load document:', error);
      toast.error('Greška pri učitavanju dokumenta');
    } finally {
      setLoading(false);
    }
  };

  const handleNewDocument = () => {
    setCreateDialogOpen(true);
  };

  const handleCreateDocument = async (title: string, description: string) => {
    try {
      const document = await documentApi.createDocument({
        title,
        description: description || undefined,
      });

      setSelectedDocument(document);
      setCurrentPageIndex(0);
      clearTokens();

      // Reload documents list
      await loadDocuments();

      setCreateDialogOpen(false);
      toast.success(`Dokument "${title}" kreiran`);
    } catch (error) {
      console.error('Failed to create document:', error);
      toast.error('Greška pri kreiranju dokumenta');
    }
  };

  const handleNewPage = async () => {
    if (!selectedDocument) {
      toast.error('Prvo spremite dokument');
      return;
    }

    try {
      const nextPageIndex = selectedDocument.pages.length;
      await documentApi.createPage(selectedDocument.id, `Stranica ${nextPageIndex + 1}`);
      
      // Reload document
      const updatedDoc = await documentApi.getDocument(selectedDocument.id);
      setSelectedDocument(updatedDoc);
      setCurrentPageIndex(nextPageIndex);
      
      toast.success('Nova stranica dodana');
    } catch (error) {
      console.error('Failed to create page:', error);
      toast.error('Greška pri dodavanju stranice');
    }
  };

  const handleDeleteSentence = async (sentenceId: string) => {
    try {
      await documentApi.deleteSentence(sentenceId);

      // Reload document
      if (selectedDocument) {
        const updatedDoc = await documentApi.getDocument(selectedDocument.id);
        setSelectedDocument(updatedDoc);
      }

      toast.success('Rečenica obrisana');
    } catch (error) {
      console.error('Failed to delete sentence:', error);
      toast.error('Greška pri brisanju rečenice');
    }
  };

  const handleLoadSentence = (sentence: Sentence) => {
    try {
      // Convert DocumentTokens to SentenceTokens
      // Filter out tokens without termId or term (punctuation-only tokens)
      const sentenceTokens: SentenceToken[] = sentence.tokens
        .filter((token) => token.termId && token.term)
        .map((token) => ({
          id: `token-${token.id}`,
          termId: token.termId!,
          term: token.term,
          displayText: token.displayText,
          isPunctuation: token.isPunctuation,
        }));

      // Load tokens into the store
      setTokens(sentenceTokens);

      toast.success('Rečenica učitana u gornju traku');
    } catch (error) {
      console.error('Failed to load sentence:', error);
      toast.error('Greška pri učitavanju rečenice');
    }
  };

  const handleDeleteDocument = async (documentId: string) => {
    try {
      await documentApi.deleteDocument(documentId);

      // Clear selected document
      setSelectedDocument(null);
      setCurrentPageIndex(0);
      clearTokens();

      // Reload documents list
      await loadDocuments();

      toast.success('Dokument obrisan');
    } catch (error) {
      console.error('Failed to delete document:', error);
      toast.error('Greška pri brisanju dokumenta');
    }
  };

  const handleUpdateDocument = async (documentId: string, title: string, description: string) => {
    try {
      await documentApi.updateDocument(documentId, { title, description });

      // Reload document
      const updatedDoc = await documentApi.getDocument(documentId);
      setSelectedDocument(updatedDoc);

      // Reload documents list
      await loadDocuments();

      toast.success('Dokument ažuriran');
    } catch (error) {
      console.error('Failed to update document:', error);
      toast.error('Greška pri ažuriranju dokumenta');
    }
  };

  return (
    <Layout>
      <div className="space-y-4">
        {/* Header */}
        <div className="flex justify-between items-center">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">Znakopis</h1>
            <p className="text-gray-600">Složite riječi u rečenice i spremite dokument</p>
          </div>
          <div className="flex gap-2">
            <Button onClick={handleNewDocument} variant="outline">
              <FileText className="h-4 w-4 mr-2" />
              Novi dokument
            </Button>
            <Button onClick={handleSaveDocument} disabled={saving || currentTokens.length === 0}>
              <Save className="h-4 w-4 mr-2" />
              {saving ? 'Spremanje...' : 'Spremi'}
            </Button>
          </div>
        </div>

        {/* Two-column layout */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Left: Token Tray (2/3 width) - Full version for editing */}
          <div className="lg:col-span-2">
            <TokenTray compact={false} />
          </div>

          {/* Right: Document Panel (1/3 width) */}
          <div className="lg:col-span-1">
            <DocumentPanel
              documents={documents}
              selectedDocument={selectedDocument}
              currentPageIndex={currentPageIndex}
              onLoadDocument={handleLoadDocument}
              onNewPage={handleNewPage}
              onPageChange={setCurrentPageIndex}
              onDeleteSentence={handleDeleteSentence}
              onDeleteDocument={handleDeleteDocument}
              onUpdateDocument={handleUpdateDocument}
              onLoadSentence={handleLoadSentence}
              loading={loading}
            />
          </div>
        </div>

        {/* Create Document Dialog */}
        <CreateDocumentDialog
          open={createDialogOpen}
          onOpenChange={setCreateDialogOpen}
          onCreate={handleCreateDocument}
        />
      </div>
    </Layout>
  );
}

export default Znakopis;

