import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types";
import editorScript from "./scripts/editor.inline";
import path from "path";

const Editor: QuartzComponent = ({ fileData, allFiles, displayClass }: QuartzComponentProps) => {
  if (!fileData.filePath) return null;

  const dIndex = process.argv.findIndex(arg => arg === "-d" || arg === "--directory");
  const baseDir = dIndex !== -1 ? process.argv[dIndex + 1] : "content";

  const absoluteBase = path.resolve(process.cwd(), baseDir);
  const absoluteFile = path.resolve(process.cwd(), fileData.filePath);
  const repoFilePath = path.relative(absoluteBase, absoluteFile);

  const directories = new Set<string>();
  for (const file of allFiles) {
    if (file.slug) {
      const parts = file.slug.split("/");
      if (parts.length > 1) {
        parts.pop();
        directories.add(parts.join("/"));
      }
    }
  }

  return (
    <div class={`editor-container ${displayClass ?? ""}`}>

      <div id="fab-container">
        <button id="new-button" class="fab" aria-label="New Note" title="New Note">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path>
            <polyline points="14 2 14 8 20 8"></polyline>
            <line x1="12" y1="18" x2="12" y2="12"></line>
            <line x1="9" y1="15" x2="15" y2="15"></line>
          </svg>
        </button>
        <button id="edit-button" class="fab" data-filepath={repoFilePath} aria-label="Edit Note" title="Edit Note">
          <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
          </svg>
        </button>
      </div>

      <div id="editor-layout" style="display: none;">
        <div id="file-path-controls">
          <div class="input-group">
            <label for="file-directory">Directory</label>
            <input type="text" id="file-directory" placeholder="e.g. thoughts/daily" list="folder-list" />
            <datalist id="folder-list">
              {Array.from(directories).sort().map(dir => (
                <option value={dir}></option>
              ))}
            </datalist>
          </div>
          <div class="input-group">
            <label for="file-name">Note Name</label>
            <input type="text" id="file-name" placeholder="e.g. My Idea" />
          </div>
        </div>

        <div id="editor-wrapper"></div>
        <div id="editor-controls">
          <input type="text" id="commit-subject" placeholder="Commit message..." maxlength={72} />
          <details id="commit-details">
            <summary>Add extended description...</summary>
            <textarea id="commit-body" rows={4} placeholder="Extended description..."></textarea>
          </details>
          <div class="editor-buttons">
            <button id="delete-button">Delete Note</button>
            <div class="editor-buttons-right">
              <button id="cancel-button">Cancel</button>
              <button id="save-button">Save</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Editor.afterDOMLoaded = editorScript;
Editor.css = `
  #fab-container {
    position: fixed;
    bottom: 2rem;
    right: 2rem;
    display: flex;
    flex-direction: row;
    gap: 1rem;
    z-index: 999;
  }

  .fab {
    width: 3.5rem;
    height: 3.5rem;
    border-radius: 50%;
    background: var(--secondary);
    color: var(--light);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    cursor: pointer;
    border: none;
    transition: transform 0.2s ease, background-color 0.2s ease;
  }

  .fab:hover:not(:disabled) {
    background: var(--tertiary);
    transform: scale(1.05);
  }

  .fab:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }

  #editor-layout {
    width: 100%;
    display: flex;
    flex-direction: column;
    margin-top: 1rem;
    margin-bottom: 2rem;
  }

  #editor-layout.is-new-note {
    margin-top: 6rem;
  }
  
  #file-path-controls {
    display: flex;
    gap: 1rem;
    margin-bottom: 1rem;
  }

  @media (max-width: 800px) {
    #editor-layout.is-new-note {
      margin-top: 1rem;
    }
  }

  @media (max-width: 600px) {
    #file-path-controls {
      flex-direction: column;
      gap: 0.5rem;
    }
  }

  .input-group {
    display: flex;
    flex-direction: column;
    flex: 1;
  }

  .input-group label {
    font-size: 0.8rem;
    color: var(--gray);
    margin-bottom: 0.2rem;
  }

  .input-group input {
    padding: 0.5rem;
    border: 1px solid var(--gray);
    border-radius: 4px;
    background: var(--light);
    color: var(--dark);
    font-family: inherit;
  }

  .input-group input:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }

  #editor-wrapper {
    width: 100%;
    border: 1px solid var(--darkgray);
    border-radius: 5px;
    overflow: hidden;
    background: #2a2a2a;
    cursor: text;
  }

  .cm-editor {
    min-height: 60vh;
    height: auto;
    background-color: #2a2a2a;
  }

  .cm-scroller {
    height: 100% !important;
    min-height: 60vh;
  }

  .cm-content {
    min-height: 100%;
  }

  #editor-controls {
    margin-top: 1rem;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }

  #commit-subject, #commit-body {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid var(--gray);
    border-radius: 4px;
    background: var(--light);
    color: var(--dark);
    font-family: inherit;
    box-sizing: border-box;
  }

  #commit-subject:disabled, #commit-body:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }

  #commit-details {
    margin-top: 0.2rem;
    margin-bottom: 1.5rem; /* Increased vertical spacing above the buttons */
  }

  #commit-details summary {
    cursor: pointer;
    color: var(--gray);
    font-size: 0.9rem;
    user-select: none;
    display: inline-block;
  }

  #commit-details summary:hover {
    color: var(--darkgray);
  }

  #commit-body {
    margin-top: 0.5rem;
    resize: vertical;
    min-height: 4rem;
  }

  .editor-buttons {
    display: flex;
    justify-content: space-between; /* Pushes Delete to left, Save/Cancel to right */
    align-items: center;
  }

  .editor-buttons-right {
    display: flex;
    gap: 0.5rem;
  }

  .editor-buttons button {
    padding: 0.5rem 1rem;
    cursor: pointer;
    border: none;
    border-radius: 4px;
    font-weight: bold;
  }

  .editor-buttons button:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  #save-button {
    background: var(--secondary);
    color: var(--light);
  }

  #save-button:hover:not(:disabled) {
    background: var(--tertiary);
  }

  #cancel-button {
    background: var(--lightgray);
    color: var(--dark);
  }

  #cancel-button:hover:not(:disabled) {
    background: var(--gray);
  }

  #delete-button {
    background: transparent;
    color: #e06c75; /* A distinct red color for destructive actions */
    border: 1px solid #e06c75;
  }

  #delete-button:hover:not(:disabled) {
    background: rgba(224, 108, 117, 0.1);
  }
  
  #delete-button:disabled {
    border-color: var(--gray);
    color: var(--gray);
  }

  @media (max-width: 800px) {
    #fab-container {
      bottom: 1.5rem;
      right: 1.5rem;
    }
    
    .fab {
      width: 3rem;
      height: 3rem;
    }
  }
`;

export default (() => Editor) satisfies QuartzComponentConstructor;
