'use client';

import { useState, useEffect, useCallback } from 'react';
import { clsx } from 'clsx';
import { Edit, Save, X, Trash2, Loader2 } from 'lucide-react';
import type { Document } from '@/lib/types';
import { saveDocument, deleteFile } from '@/lib/api';
import { ConfirmationModal } from './confirmation-modal';
import { CommitHistory } from './commit-history';
import { useToast } from './toast';

function formatRelativeTime(dateStr: string): string {
  const now = Date.now();
  const then = new Date(dateStr).getTime();
  const diffMs = now - then;
  const diffMin = Math.floor(diffMs / 60000);
  if (diffMin < 1) return 'just now';
  if (diffMin < 60) return `${diffMin}m ago`;
  const diffHr = Math.floor(diffMin / 60);
  if (diffHr < 24) return `${diffHr}h ago`;
  const diffDays = Math.floor(diffHr / 24);
  if (diffDays === 1) return 'yesterday';
  if (diffDays < 30) return `${diffDays}d ago`;
  return new Date(dateStr).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

interface DocumentViewerProps {
  document: Document;
  onClose?: () => void;
  onMutate?: () => void;
}

export function DocumentViewer({ document: doc, onClose, onMutate }: DocumentViewerProps) {
  const [editing, setEditing] = useState(false);
  const [editContent, setEditContent] = useState(doc.content);
  const [saving, setSaving] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const { showToast } = useToast();

  // Reset when document changes
  useEffect(() => {
    setEditContent(doc.content);
    setEditing(false);
  }, [doc.path, doc.content, doc.name]);

  const handleSave = useCallback(async () => {
    setSaving(true);
    try {
      const result = await saveDocument(
        doc.vaultFullName,
        doc.path,
        editContent,
        `Update ${doc.name} via KnowHub`
      );
      if (result) {
        showToast('Document saved', 'success');
        setEditing(false);
        onMutate?.();
      } else {
        showToast('Failed to save document', 'error');
      }
    } catch {
      showToast('Failed to save document', 'error');
    } finally {
      setSaving(false);
    }
  }, [doc.vaultFullName, doc.path, doc.name, editContent, showToast, onMutate]);

  const handleDelete = useCallback(async () => {
    setDeleting(true);
    try {
      const success = await deleteFile(doc.vaultFullName, doc.path);
      if (success) {
        showToast('Document deleted', 'success');
        setShowDeleteConfirm(false);
        onClose?.();
        onMutate?.();
      } else {
        showToast('Failed to delete document', 'error');
      }
    } catch {
      showToast('Failed to delete document', 'error');
    } finally {
      setDeleting(false);
    }
  }, [doc.vaultFullName, doc.path, showToast, onClose, onMutate]);

  // Ctrl+S handler
  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key === 's' && editing) {
        e.preventDefault();
        handleSave();
      }
    }
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [editing, handleSave]);

  return (
    <>
      <div className="flex flex-col h-full">
        {/* Header bar -- blue accent */}
        <div className="border-b border-border bg-surface px-6 py-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3 min-w-0">
              <h1 className="text-lg font-semibold text-text-primary truncate">
                {doc.name}
              </h1>
            </div>

            <div className="flex items-center gap-2 shrink-0">
              {editing ? (
                <>
                  <button
                    onClick={() => {
                      setEditContent(doc.content);
                      setEditing(false);
                    }}
                    className="px-3 py-1.5 text-sm rounded-md border border-border text-text-secondary hover:text-text-primary hover:bg-surface-elevated transition-colors"
                  >
                    Discard
                  </button>
                  <button
                    onClick={handleSave}
                    disabled={saving}
                    className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md bg-document text-white font-medium hover:opacity-90 transition-opacity disabled:opacity-60"
                  >
                    {saving ? (
                      <Loader2 size={14} className="animate-spin" />
                    ) : (
                      <Save size={14} />
                    )}
                    {saving ? 'Saving...' : 'Save'}
                    <kbd className="text-[10px] text-white/60 ml-1">Ctrl+S</kbd>
                  </button>
                </>
              ) : (
                <>
                  <CommitHistory vaultFullName={doc.vaultFullName} path={doc.path} />
                  <button
                    onClick={() => setEditing(true)}
                    className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border border-border text-text-secondary hover:text-text-primary hover:bg-surface-elevated transition-colors"
                  >
                    <Edit size={14} />
                    Edit
                  </button>
                  <button
                    onClick={() => setShowDeleteConfirm(true)}
                    className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-md border border-border text-error hover:bg-surface-elevated transition-colors"
                  >
                    <Trash2 size={14} />
                    Delete
                  </button>
                </>
              )}
              {onClose && (
                <button
                  onClick={onClose}
                  className="p-1 rounded-md hover:bg-surface-elevated text-text-muted hover:text-text-primary transition-colors ml-2"
                  aria-label="Close viewer"
                >
                  <X size={18} />
                </button>
              )}
            </div>
          </div>

          {/* Save info */}
          <p className="text-xs text-text-muted mt-1">
            Last saved {formatRelativeTime(doc.lastModified)} by {doc.lastModifiedBy}
          </p>
        </div>

        {/* Content area */}
        <div className="flex-1 overflow-y-auto px-6 py-6">
          <div className="max-w-[680px] mx-auto">
            {editing ? (
              <textarea
                value={editContent}
                onChange={(e) => setEditContent(e.target.value)}
                className="w-full min-h-[400px] text-sm leading-relaxed text-text-primary bg-transparent resize-none outline-none font-mono"
                autoFocus
              />
            ) : (
              <pre className="text-sm leading-relaxed text-text-secondary whitespace-pre-wrap font-sans">
                {doc.content}
              </pre>
            )}
          </div>
        </div>

      </div>

      <ConfirmationModal
        open={showDeleteConfirm}
        title="Delete Document"
        description={`Are you sure you want to delete "${doc.name}"? This cannot be undone.`}
        confirmLabel={deleting ? 'Deleting...' : 'Delete'}
        onConfirm={handleDelete}
        onCancel={() => setShowDeleteConfirm(false)}
      />
    </>
  );
}
