import { useCallback, useEffect, useState } from "react";
import { Download, Eye, Pencil, Plus, Trash2 } from "lucide-react";

import OmsorgButton from "../../components/ui/OmsorgButton";
import { useAuth } from "../../app/AuthContext";
import UploadDocumentDialog from "./UploadDocumentDialog";
import EditDocumentDialog from "./EditDocumentDialog";
import DocumentViewerDialog from "./DocumentViewerDialog";

function formatDate(value) {
  if (!value) return "—";
  return new Date(value).toLocaleDateString("de-DE");
}

function formatSize(bytes) {
  if (bytes == null) return "—";
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function groupByCategory(documents) {
  const groups = new Map();
  for (const doc of documents) {
    const key = doc.category ?? "Sonstiges";
    if (!groups.has(key)) {
      groups.set(key, []);
    }
    groups.get(key).push(doc);
  }
  return groups;
}

export default function DocumentsList({ employeeId }) {
  const { hasPermission } = useAuth();
  const canCreate = hasPermission("Documents", "Create");
  const canView = hasPermission("Documents", "View");
  const canEdit = hasPermission("Documents", "Edit");
  const canDelete = hasPermission("Documents", "Delete");

  const [documents, setDocuments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [editingDocument, setEditingDocument] = useState(null);
  const [viewingDocument, setViewingDocument] = useState(null);
  const [busyDocumentId, setBusyDocumentId] = useState(null);

  const loadDocuments = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    const result = await window.omsorg.documents.list({ entityType: "Employee", entityId: employeeId });

    if (result.ok) {
      setDocuments(result.data ?? []);
    } else {
      setError("Dokumente konnten nicht geladen werden.");
    }

    setIsLoading(false);
  }, [employeeId]);

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

  function handleUploaded() {
    setIsDialogOpen(false);
    loadDocuments();
  }

  function handleUpdated() {
    setEditingDocument(null);
    loadDocuments();
  }

  async function handleDownload(doc) {
    setBusyDocumentId(doc.id);
    await window.omsorg.documents.download(doc.id, doc.fileName);
    setBusyDocumentId(null);
  }

  async function handleDelete(doc) {
    if (!window.confirm(`Dokument "${doc.fileName}" wirklich löschen?`)) {
      return;
    }

    setBusyDocumentId(doc.id);
    const result = await window.omsorg.documents.delete(doc.id);
    setBusyDocumentId(null);

    if (result.ok) {
      loadDocuments();
    }
  }

  const groups = groupByCategory(documents);

  return (
    <div className="employee-tab-content">
      <div className="page-heading">
        <h3>Dokumente</h3>

        {canCreate && (
          <OmsorgButton icon={Plus} variant="secondary" onClick={() => setIsDialogOpen(true)}>
            Hochladen
          </OmsorgButton>
        )}
      </div>

      {error && <p className="login-error">{error}</p>}
      {isLoading && <p>Lädt...</p>}

      {!isLoading && documents.length === 0 && <p>Noch kein Dokument hochgeladen.</p>}

      {!isLoading &&
        Array.from(groups.entries()).map(([category, categoryDocuments]) => (
          <div key={category}>
            <h4>{category}</h4>
            <div className="facility-contacts-list">
              {categoryDocuments.map((doc) => (
                <div key={doc.id} className="facility-contact-row">
                  <div>
                    <strong>{doc.fileName}</strong>
                    <p>{doc.description || "—"}</p>
                    <p>
                      {formatSize(doc.sizeBytes)} · {doc.uploadedByUsername ?? "—"} ·{" "}
                      {formatDate(doc.createdAt)}
                    </p>
                  </div>

                  <div>
                    {canView && (
                      <OmsorgButton
                        variant="secondary"
                        icon={Eye}
                        onClick={() => setViewingDocument(doc)}
                        disabled={busyDocumentId === doc.id}
                      >
                        Anzeigen
                      </OmsorgButton>
                    )}

                    {canView && (
                      <OmsorgButton
                        variant="secondary"
                        icon={Download}
                        onClick={() => handleDownload(doc)}
                        disabled={busyDocumentId === doc.id}
                      >
                        Herunterladen
                      </OmsorgButton>
                    )}

                    {canEdit && (
                      <OmsorgButton
                        variant="secondary"
                        icon={Pencil}
                        onClick={() => setEditingDocument(doc)}
                        disabled={busyDocumentId === doc.id}
                      >
                        Bearbeiten
                      </OmsorgButton>
                    )}

                    {canDelete && (
                      <OmsorgButton
                        variant="secondary"
                        icon={Trash2}
                        onClick={() => handleDelete(doc)}
                        disabled={busyDocumentId === doc.id}
                      >
                        Löschen
                      </OmsorgButton>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}

      {isDialogOpen && (
        <UploadDocumentDialog
          employeeId={employeeId}
          onClose={() => setIsDialogOpen(false)}
          onUploaded={handleUploaded}
        />
      )}

      {editingDocument && (
        <EditDocumentDialog
          doc={editingDocument}
          onClose={() => setEditingDocument(null)}
          onUpdated={handleUpdated}
        />
      )}

      {viewingDocument && (
        <DocumentViewerDialog doc={viewingDocument} onClose={() => setViewingDocument(null)} />
      )}
    </div>
  );
}
